Search This Blog

Resource owner password flow with Identity Server 4 and ASP.NET core

Resource owner password flow with Identity Server 4

Few week ago I described how to build a custom Jwt authentication.
Today I will show how we can use Identity server together with Resource owner password flow to authenticate and authorise your client to access your api.

1. Identity server

Identity server is a framework which implements Open ID Connect and OAuth 2.0 protocols.
The purpose of Identity server is to centralize the identity management and at the same time decouple your api(s) from authentication and authorization logic.
Centralizing has many advantages:

If you have multiple apis, you can hold your identities in a common place

If you have multiple apis, it provides single sign on - user only sign in into one client and is automatically sign in in all apis. This works because all clients will redirect to the same authority which will be able to verify that the user is already logged in

It provides a powerful way to configure client access to your api

There are many more advantages like the Open ID connect protocol implementation which handles consents and the handling of different authentication flows.
In this post, we will be looking at the Resource owner password flow. It is the simplest flow but comes with two disavantages:

We lose Single Sign On as the user has to send username/password for each issuance of valid token

We lose third party integration support from ID server as there is no redirect flow
But if your application doesn’t need those, then It would be the easiest flow to implement.

1.1 Configure the identity provider

The identity provider is a server responsible for holding all identities and providing access tokens which can be used to access protected resources. The api/identity resources are the resources that you wish to protect.
Api resources would be apis that you wish to protect, grant access to only certain clients.
Identity resources would be pieces of information from the identity itself that you wish to protect, like the address, the name or date of birth contained in the identity for example.

What the identity provider will provide is an access token which can be used to access either the Apis or the identity information. The identity information can be retrieved from the UserInfo endpoint on the identity provider. We will see next that we can configure the middleware in the client to authomatically retrieve the identity claims by setting the property GetClaimsFromUserInfoEndpoint to true.

In this example, we will have 3 pieces:

The identity provider

Our api we wish to protect

Our client - could be a website or an app or a client software, for this example I will use a client software

So let’s start by configuring the identity provider. First we create an empty asp.net core project and add identityServer4 package.

Then from the Startup file we register the identity service and add the middleware.

Take note that AddTestUsers adds a profile service and a resource owner password validator which we would need to provide when not using test users. We can see from the Identity Server code what AddTestUser does:

2. Protect an API

Let’s start a web api project and add IdentityServer4.AccessTokenValidation.
This library allows us to protect the api by using the IdentityServerAuthentication middleware which will validate the access tokens.

In the option, we specify the endpoint of the identity provider, our api name, the secret to connect from the api to the identity provider via the introspection endpoint - this is useful when we use reference token as it allows us to be protected against an unauthorized request possessing a reference token and trying to check the state of the access token. More info here https://tools.ietf.org/html/rfc7662.

Now that we have configured our API and that it is now protected behind access token validation, we can register it in the identity provider in the api resource section:

Every ApiResource come with a default scope which is the name of the api. For instance here I named it api, therefore I will be able to give to a client AllowedScopes = { "api" } which will provide an access token with Scopes = [ 'api' ].

Lastly what we need to do is to configure a client which will be trying to get an access token to access the API.

3. Configure a client

A client can be a website or a mobile app or a software client.
In this example I will be creating a Console App and use the IdentityModel package to request for an access token.

Here we add a secret for the client to connect to the identity provider.
We specify the flow to be ResourceOwnderPassword which means that the user will always provide username/password to connect. And we allow the client to connect to the api resource. This will mean that when the identity provider generates an access token to this client, it will be able to use the access to token to authenticate on the protected API.

Earlier we talked about the introspection endpoint, if we want to change the Jwt token to a reference token, this can be done by setting on the Client the property:

AccessTokenType = AccessTokenType.Reference

If we change that, the token generated will be a reference token - an opaque token - which allows to authenticate on the API and from the API, it will consult the identity provider given its API secret and the reference token to get access to the identity of the user. The advantage of this is that it is all done in a back channel and the reference token is a totally opaque token with no information in it, in contrast to the JWT token which contains some readable information (when not encrypted). An other point is that with the JWT token, the API does not consult the introspection and the token is valid during its whole lifespan whereas for the reference token, it is used to get the identity therefore on each requests, the latest authorizations can be fetched.

You must have noticed that we also allowed IdentityServerConstants.StandardScopes.OpenId and IdentityServerConstants.StandardScopes.Email. Those are identity resources.

We can define some properties to be retrieved from the identity:

// -- This is in the Identity provider
public static IEnumerable<IdentityResource> GetIdentityResources()
{
return new List<IdentityResource>
{
new IdentityResources.OpenId(),
new IdentityResources.Email()
};
}

The default Identity resources englobe a set of UserClaims to be retrieved when requesting for the identity resources.
For example, IdentityResources.Email is defined as followed in IdentityServer4 source code:

This means that the Identity resource Email allows to retrieve the email and verified email claims from the identity.

Next we create a console app, and add the IdentityModel package. We then use the TokenClient to request for a token and we can then use that token to request for the data in the api.
We start by requesting a token:

And that’s it, the client should be able to retrieve the access token, use it to get the protected data from the API and lastly get from the identity provider the identity resources it is allowed to get.

Conclusion

Today we saw how to implement a Resource owner password flow using Identity server 4. We saw the aspects needed to build an identity provider, how to protect an API and allow a client to access its data. We also saw how we could allow identity claims to be retrieved from the identity provider and how we could allow client to retrieve those. If you have any question leave it here or hit me on Twitter @Kimserey_Lam. See you next time!

Comments

Hi thanks for the tutorial. Can I use ResourceOwnerPassword granttype to view an IS4 protected app (not api) from an external application. I tried to summarize it on SO question. https://stackoverflow.com/questions/45283512/identityserver-4-integration-of-external-application . I implemented ROP, I can get the accesstoken from external app, can i use this token to view my protected app. hope it's not a silly question. Regards.

Post a Comment

Popular posts from this blog

Absolute layout and relative layout Xamarin formsIn Xamarin Forms, layouts are used to position elements in the page.
There are multiple layouts available like stack layout, grid layout, table layout, absolute layout and relative layout.
Stack layout is straight to grasp the concept, we stack elements one by one horizontally or vertically.
Grid layout is also straight forward, we define rows and columns and we place the elements by indicating the row index and column index.
On the other hand, absolute layout and relative layout isn’t that straight forward because in Xamarin it is NOT the same as positions in CSS.So today, we will see how and when we can use absolute layout and/or relative layout in our advantage.
This post is composed by two parts: 1. Absolute layout
2. Relative layout
1. Absolute layoutThe first thing to understand is that absolute layout has nothing to do with CSS absolute position.
In Xamarin Forms. absolute layout allows us to position elements in the page by pre…

Build an accordion view in Xamarin.FormsFew weeks ago I posted about absolute and relative layouts.
Layouts are called Layouts because they contain children which are placed in a particular way.
Xamarin.Forms has a lot of layouts and views to structure pages like grid, table view or list view.Today I would like to show you how we can use some of these basic views to build an Accordion view.Here’s a preview of the Accordion view:Full source code available on GitHub - https://github.com/Kimserey/AccordionView/blob/master/Accordion/AccordionView.csThis post will be composed of four steps:Create a BindablePropertyDefine the accordion expandable sectionDefine the accordion viewUsage sample1. Create a BindablePropertyAs we saw in one of my previous post,
Xamarin.Forms works around data bindings.
View properties are bound to viewmodel properties.Default views like Label, Button, ListView or TableView come with the necessary bindable properties like BackgroundColor, TextColor, ItemsSource, It…

Use Font Awesome from your Xamarin.Forms projectIcons are important in mobile applications where space is limited.
We use icon everywhere to convey action intent like + would be to add an item or a bin would be to delete one.
There are two ways to add icons to our mobile app:with imageswith fontsToday we will see the second option - how we can add Font awesome to our Xamarin.Android project and how we can use it from Xamarin.Forms.
This post will be composed by three parts: 1. Why Font Awesome
2. Add Font Awesome to the Droid project
3. Use with Xamarin.Forms
1. Why Font AwesomeIf you are familiar with Web development, you must have encountered Font awesome http://fontawesome.io/.
It is an icon font containing lots of icon for every type of usage.
The advantaged of using a font is that we can leverage the text options, like text color or text size, to easily update the style of the icon to match our app.Let’s see how we can bring Font Awesome to the Droid project.2. Add Font awesome…