ASP.NET Web API Claims Authorization with ASP.NET Identity 2.1 - Part 5 - Bit of Technology

Created: 2015-11-21 07:30 Updated: 2015-11-21 07:30 Source: http://bitoftech.net/2015/03/31/asp-net-web-api-claims-authorization-with-asp-n… Notebook: All Tech/Frontend Development

ASP.NET Web API Claims Authorization with ASP.NET Identity 2.1 – Part 5

March 31, 2015 By 179 Comments

Be Sociable, Share!

This is the fifth part of Building Simple Membership system using ASP.NET Identity 2.1, ASP.NET Web API 2.2 and AngularJS. The topics we’ll cover are:

The source code for this tutorial is available on GitHub.

ASP.NET Web API Claims Authorization with ASP.NET Identity 2.1

In the previous post we have implemented a finer grained way to control authorization based on the Roles assigned for the authenticated user, this was done by assigning users to a predefined Roles in our system and then attributing the protected controllers or actions by the [Authorize(Roles = “Role(s) Name”)] attribute.

Claims Featured Image

Using Roles Based Authorization for controlling user access will be efficient in scenarios where your Roles do not change too much and the users permissions do not change frequently.

In some applications controlling user access on system resources is more complicated, and having users assigned to certain Roles is not enough for managing user access efficiently, you need more dynamic way to to control access based on certain information related to the authenticated user, this will lead us to control user access using Claims, or in another word using Claims Based Authorization.

But before we dig into the implementation of Claims Based Authorization we need to understand what Claims are!

Note: It is not mandatory to use Claims for controlling user access, if you are happy with Roles Based Authorization and you have limited number of Roles then you can stick to this.

What is a Claim?

Claim is a statement about the user makes about itself, it can be user name, first name, last name, gender, phone, the roles user assigned to, etc… Yes the Roles we have been looking at are transformed to Claims at the end, and as we saw in the previous post; in ASP.NET Identity those Roles have their own manager (ApplicationRoleManager) and set of APIs to manage them, yet you can consider them as a Claim of type Role.

As we saw before, any authenticated user will receive a JSON Web Token (JWT) which contains a set of claims inside it, what we’ll do now is to create a helper end point which returns the claims encoded in the JWT for an authenticated user.

To do this we will create a new controller named “ClaimsController” which will contain a single method responsible to unpack the claims in the JWT and return them, to do this add new controller named “ClaimsController” under folder Controllers and paste the code below:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
    [RoutePrefix("api/claims")]
    public class ClaimsController : BaseApiController
    {
        [Authorize]
        [Route("")]
        public IHttpActionResult GetClaims()
        {
            var identity = User.Identity as ClaimsIdentity;
            
            var claims = from c in identity.Claims
                         select new
                         {
                             subject = c.Subject.Name,
                             type = c.Type,
                             value = c.Value
                         };
 
            return Ok(claims);
        }
 
    }

The code we have implemented above is straight forward, we are getting the Identity of the authenticated user by calling “User.Identity” which returns “ClaimsIdentity” object, then we are iterating over the IEnumerable Claims property and return three properties which they are (Subject, Type, and Value).
To execute this endpoint we need to issue HTTP GET request to the end point “http://localhost/api/claims” and do not forget to pass a valid JWT in the Authorization header, the response for this end point will contain the below JSON object:

Click To Expand Code

As you noticed from the response above, all the claims contain three properties, and those properties represents the below:

  • Subject: Represents the identity which those claims belongs to, usually the value for the subject will contain the unique identifier for the user in the system (Username or Email).
  • Type: Represents the type of the information contained in the claim.
  • Value: Represents the claim value (information) about this claim.

Now to have better understanding of what type of those claims mean let’s take a look the table below:

SubjectTypeValueNotes
Hamzanameidentifiercd93945e-fe2c-49c1-b2bb-138a2dd52928Unique User Id generated from Identity System
HamzanameHamzaUnique Username
HamzaidentityproviderASP.NET IdentityHow user has been authenticated using ASP.NET Identity
HamzaSecurityStampa77594e2-ffa0-41bd-a048-7398c01c8948Unique Id which stays the same until any security related attribute change, i.e. change user password
Hamzaisshttp://localhost:59822Issuer of the Access Token (Authz Server)
Hamzaaud414e1927a3884f68abc79f7283837fd1For which system this token is generated
Hamzaexp1427744352Expiry time for this access token (Epoch)
Hamzanbf1427657952When this token is issued (Epoch)

After we have briefly described what claims are, we want to see how we can use them to manage user assess, in this post I will demonstrate three ways of using the claims as the below:

  1. Assigning claims to the user on the fly based on user information.
  2. Creating custom Claims Authorization attribute.
  3. Managing user claims by using the “ApplicationUserManager” APIs.

Method 1: Assigning claims to the user on the fly

Let’s assume a fictional use case where our API will be used in an eCommerce website, where certain users have the ability to issue refunds for orders if there is incident happen and the customer is not happy.

So certain criteria should be met in order to grant our users the privileges to issue refunds, the users should have been working for the company for more than 90 days, and the user should be in “Admin”Role.

To implement this we need to create a new class which will be responsible to read authenticated user information, and based on the information read, it will create a single claim or set of claims and assign then to the user identity.
If you recall from the first post of this series, we have extended the “ApplicationUser” entity and added a property named “JoinDate” which represent the hiring date of the employee, based on the hiring date, we need to assign a new claim named “FTE” (Full Time Employee) for any user who has worked for more than 90 days. To start implementing this let’s add a new class named “ExtendedClaimsProvider” under folder “Infrastructure” and paste the code below:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
    public static class ExtendedClaimsProvider
    {
        public static IEnumerable<Claim> GetClaims(ApplicationUser user)
        {
          
            List<Claim> claims = new List<Claim>();
 
            var daysInWork =  (DateTime.Now.Date - user.JoinDate).TotalDays;
 
            if (daysInWork > 90)
            {
                claims.Add(CreateClaim("FTE", "1"));
              
            }
            else {
                claims.Add(CreateClaim("FTE", "0"));
            }
 
            return claims;
        }
 
        public static Claim CreateClaim(string type, string value)
        {
            return new Claim(type, value, ClaimValueTypes.String);
        }
 
    }

The implementation is simple, the “GetClaims” method will take ApplicationUser object and returns a list of claims. Based on the “JoinDate” field it will add new claim named “FTE” and will assign a value of “1” if the user has been working for than 90 days, and a value of “0” if the user worked for less than this period. Notice how I’m using the method “CreateClaim” which returns a new instance of the claim.

This class can be used to enforce creating custom claims for the user based on the information related to her, you can add as many claims as you want here, but in our case we will add only a single claim.

Now we need to call the method “GetClaims” so the “FTE” claim will be associated with the authenticated user identity, to do this open class “CustomOAuthProvider” and in method “GrantResourceOwnerCredentials” add the highlighted line (line 7) as the code snippet below:

1
2
3
4
5
6
7
8
9
10
11
12
13
public override async Task GrantResourceOwnerCredentials(OAuthGrantResourceOwnerCredentialsContext context)
{
//Code removed for brevity
 
ClaimsIdentity oAuthIdentity = await user.GenerateUserIdentityAsync(userManager, "JWT");
oAuthIdentity.AddClaims(ExtendedClaimsProvider.GetClaims(user));
var ticket = new AuthenticationTicket(oAuthIdentity, null);
context.Validated(ticket);
  
}

Notice how the established claims identity object “oAuthIdentity” has a method named “AddClaims” which accepts IEnumerable object of claims, now the new “FTE” claim is assigned to the authenticated user, but this is not enough to satisfy the criteria needed to issue the fictitious refund on orders, we need to make sure that the user is in “Admin” Role too.

To implement this we’ll create a new Role on the fly based on the claims assigned for the user, in other words we’ll create Roles from the Claims user assigned to, this Role will be named “IncidentResolvers”. And as we stated in the beginning of this post, the Roles eventually are considered as a Claim of type Role.

To do this add new class named “RolesFromClaims” under folder “Infrastructure” and paste the code below:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
    public class RolesFromClaims
    {
        public static IEnumerable<Claim> CreateRolesBasedOnClaims(ClaimsIdentity identity)
        {
            List<Claim> claims = new List<Claim>();
 
            if (identity.HasClaim(c => c.Type == "FTE" && c.Value == "1") &&
                identity.HasClaim(ClaimTypes.Role, "Admin"))
            {
                claims.Add(new Claim(ClaimTypes.Role, "IncidentResolvers"));
            }
 
            return claims;
        }
    }

The implementation is self explanatory, we have created a method named “CreateRolesBasedOnClaims” which accepts the established identity object and returns a list of claims.

Inside this method we will check that the established identity for the authenticated user has a claim of type “FTE” with value “1”, as well that the identity contains a claim of type “Role” with value “Admin”, if those 2 conditions are met then; we will create a new claim of Type “Role” and give it a value of “IncidentResolvers”.
Last thing we need to do here is to assign this new set of claims to the established identity, so to do this open class “CustomOAuthProvider” again and in method “GrantResourceOwnerCredentials” add the highlighted line (line 9) as the code snippet below:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
public override async Task GrantResourceOwnerCredentials(OAuthGrantResourceOwnerCredentialsContext context)
{
//Code removed for brevity
 
ClaimsIdentity oAuthIdentity = await user.GenerateUserIdentityAsync(userManager, "JWT");
oAuthIdentity.AddClaims(ExtendedClaimsProvider.GetClaims(user));
oAuthIdentity.AddClaims(RolesFromClaims.CreateRolesBasedOnClaims(oAuthIdentity));
var ticket = new AuthenticationTicket(oAuthIdentity, null);
context.Validated(ticket);
  
}

Now all the new claims which created on the fly are assigned to the established identity and once we call the method “context.Validated(ticket)”, all claims will get encoded in the JWT token, so to test this out let’s add fictitious controller named “OrdersController” under folder “Controllers” as the code below:

1
2
3
4
5
6
7
8
9
10
11
[RoutePrefix("api/orders")]
public class OrdersController : ApiController
{
[Authorize(Roles = "IncidentResolvers")]
[HttpPut]
[Route("refund/{orderId}")]
public IHttpActionResult RefundOrder([FromUri]string orderId)
{
return Ok();
}
}

Notice how we attribute the action “RefundOrder” with  [Authorize(Roles = “IncidentResolvers”)] so only authenticated users with claim of type “Role” and has the value of “IncidentResolvers” can access this end point. To test this out you can issue HTTP PUT request to the URI “http://localhost/api/orders/refund/cxy-4456393″ with an empty body.

As you noticed from the first method, we have depended on user information to create claims and kept the authorization more dynamic and flexible.
Keep in mind that you can add your access control business logic, and have finer grained control on authorization by implementing this logic into classes “ExtendedClaimsProvider” and “RolesFromClaims”.

Method 2: Creating custom Claims Authorization attribute

Another way to implement Claims Based Authorization is to create a custom authorization attribute which inherits from “AuthorizationFilterAttribute”, this authorize attribute will check directly the claims value and type for the established identity.

To do this let’s add new class named “ClaimsAuthorizationAttribute” under folder “Infrastructure” and paste the code below:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
    public class ClaimsAuthorizationAttribute : AuthorizationFilterAttribute
    {
        public string ClaimType { get; set; }
        public string ClaimValue { get; set; }
 
        public override Task OnAuthorizationAsync(HttpActionContext actionContext, System.Threading.CancellationToken cancellationToken)
        {
 
            var principal = actionContext.RequestContext.Principal as ClaimsPrincipal;
 
            if (!principal.Identity.IsAuthenticated)
            {
                actionContext.Response = actionContext.Request.CreateResponse(HttpStatusCode.Unauthorized);
                return Task.FromResult<object>(null);
            }
 
            if (!(principal.HasClaim(x => x.Type == ClaimType && x.Value == ClaimValue)))
            {
                actionContext.Response = actionContext.Request.CreateResponse(HttpStatusCode.Unauthorized);
                return Task.FromResult<object>(null);
            }
 
            //User is Authorized, complete execution
            return Task.FromResult<object>(null);
 
        }
    }

What we’ve implemented here is the following:

  • Created a new class named “ClaimsAuthorizationAttribute” which inherits from “AuthorizationFilterAttribute” and then override method “OnAuthorizationAsync”.
  • Defined 2 properties “ClaimType” & “ClaimValue” which will be used as a setters when we use this custom authorize attribute.
  • Inside method “OnAuthorizationAsync” we are casting the object “actionContext.RequestContext.Principal” to “ClaimsPrincipal” object and check if the user is authenticated.
  • If the user is authenticated we’ll look into the claims established for this identity if it has the claim type and claim value.
  • If the identity contains the same claim type and value; then we’ll consider the request authentic and complete the execution, other wist we’ll return 401 unauthorized status.

To test the new custom authorization attribute, we’ll add new method to the “OrdersController” as the code below:

1
2
3
4
5
6
[ClaimsAuthorization(ClaimType="FTE", ClaimValue="1")]
[Route("")]
public IHttpActionResult Get()
{
return Ok();
}

Notice how we decorated the “Get()” method with the “[ClaimsAuthorization(ClaimType=”FTE”, ClaimValue=”1″)]” attribute, so any user has the claim “FTE” with value “1” can access this protected end point.

Method 3: Managing user claims by using the “ApplicationUserManager” APIs

The last method we want to explore here is to use the “ApplicationUserManager” claims related API to manage user claims and store them in ASP.NET Identity related tables “AspNetUserClaims”.

In the previous two methods we’ve created claims for the user on the fly, but in method 3 we will see how we can add/remove claims for a certain user.

The “ApplicationUserManager” class comes with a set of predefined APIs which makes dealing and managing claims simple, the APIs that we’ll use in this post are listed in the table below:

Method NameUsage
AddClaimAsync(id, claim)Create a new claim for specified user id
RemoveClaimAsync(id, claim)Remove claim from specified user if claim type and value match
GetClaimsAsync(id)Return IEnumerable of claims based on specified user id

To use those APIs let’s add 2 new methods to the “AccountsController”, the first method “AssignClaimsToUser” will be responsible to add new claims for specified user, and the second method “RemoveClaimsFromUser” will remove claims from a specified user as the code below:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
[Authorize(Roles = "Admin")]
[Route("user/{id:guid}/assignclaims")]
[HttpPut]
public async Task<IHttpActionResult> AssignClaimsToUser([FromUri] string id, [FromBody] List<ClaimBindingModel> claimsToAssign) {
 
if (!ModelState.IsValid)
{
return BadRequest(ModelState);
}
 
var appUser = await this.AppUserManager.FindByIdAsync(id);
 
if (appUser == null)
{
return NotFound();
}
 
foreach (ClaimBindingModel claimModel in claimsToAssign)
{
if (appUser.Claims.Any(c => c.ClaimType == claimModel.Type)) {
  
await this.AppUserManager.RemoveClaimAsync(id, ExtendedClaimsProvider.CreateClaim(claimModel.Type, claimModel.Value));
}
 
await this.AppUserManager.AddClaimAsync(id, ExtendedClaimsProvider.CreateClaim(claimModel.Type, claimModel.Value));
}
return Ok();
}
 
[Authorize(Roles = "Admin")]
[Route("user/{id:guid}/removeclaims")]
[HttpPut]
public async Task<IHttpActionResult> RemoveClaimsFromUser([FromUri] string id, [FromBody] List<ClaimBindingModel> claimsToRemove)
{
 
if (!ModelState.IsValid)
{
return BadRequest(ModelState);
}
 
var appUser = await this.AppUserManager.FindByIdAsync(id);
 
if (appUser == null)
{
return NotFound();
}
 
foreach (ClaimBindingModel claimModel in claimsToRemove)
{
if (appUser.Claims.Any(c => c.ClaimType == claimModel.Type))
{
await this.AppUserManager.RemoveClaimAsync(id, ExtendedClaimsProvider.CreateClaim(claimModel.Type, claimModel.Value));
}
}
 
return Ok();
}

The implementation for both methods is very identical, as you noticed we are only allowing users in “Admin” role to access those endpoints, then we are specifying the UserId and a list of the claims that will be add or removed for this user.

Then we are making sure that user specified exists in our system before trying to do any operation on the user.

In case we are adding a new claim for the user, we will check if the user has the same claim type before trying to add it, add if it exists before we’ll remove this claim and add it again with the new claim value.

The same applies when we try to remove a claim from the user, notice that methods “AddClaimAsync” and “RemoveClaimAsync” will save the claims permanently in our SQL data-store in table “AspNetUserClaims”.

Do not forget to add the “ClaimBindingModel” under folder “Models” which acts as our POCO class when we are sending the claims from our front-end application, the class will contain the code below:

1
2
3
4
5
6
7
8
9
10
    public class ClaimBindingModel
    {
        [Required]
        [Display(Name = "Claim Type")]
        public string Type { get; set; }
 
        [Required]
        [Display(Name = "Claim Value")]
        public string Value { get; set; }
    }

There is no extra steps needed in order to pull those claims from the SQL data-store when establishing the user identity, thanks for the method “CreateIdentityAsync” which is responsible to pull all the claims for the user. We have already implemented this and it can be checked by visiting the highlighted LOC.

To test those methods all you need to do is to issue HTTP PUT request to the URI: “http://localhost:59822/api/accounts/user/{UserId}/assignclaims” and “http://localhost:59822/api/accounts/user/{UserId}/removeclaims” as the request images below:

Assign Claims

Assign Claims

Remove Claims

Remove Claims

That’s it for now folks about implementing Authorization using Claims.

In the next post we’ll build a simple AngularJS application which connects all those posts together, this post should be interesting

The source code for this tutorial is available on GitHub.

Follow me on Twitter @tjoudeh

References

Be Sociable, Share!

Like this:

Be the first to like this.
Chromecast's power adapter's model number, "MST3K-US," is a reference to "Mystery Science Theater 3000"
On an Android device, you can cast whatever you see on your phone to the TV like a mirror
For its first week, Chromecast gave away Google Play credits for every cat video watched using the device
Chromecast is unique as it doesn't use its own interface to operate, rather it works with existing apps
Chromecast was so popular when first introduced that it sold out in 72 seconds with a wait list of 2 weeks
Webster added "Chromecasting" to the dictionary in 2014, less than a year after Chromecast was released
Chromecast has been known to work with the NSA in spying on terrorists working on U.S. soil
Like Android, Chromecast used to have open source coding, meaning you could easily pirate content
Chromecast's model number H2G2-42 is a reference to the series "Hitchhiker's Guide to the Galaxy"
The Chromecast stick can actually double as a USB drive with as much free space as your Cloud has
Question
1/10
Your score
0
Are You the King or Queen of Chromecast Trivia?
True
False
1 2 3 4 5 6 7 8 9 10
You scored a ridiculous
3/10
Challenge
your friends
Advertisement:

Comments

  1. Thanks for the great series of Articles, your site has been very helpful. I have learnt more from this than pretty much any other blog. Excellent work.

  2. How about a twist and making a final article with aurelia as an Eid Al-Adha gift ? Thanks

  3. Nice blog. Congrats on becoming an MVP. I would like to ask some questions to get clarification on a workflow scenario you mentioned earlier. I think I got confused between client_id and audience_Id.

    In a scenario where we have separate jwt auth server/ web api/ angular client. what should be the workflow for audienceid propagation. When angular client calls a protected webapi (without jwt token), it’ll send back 401 response and then in angular client using the interceptor we redirect it to the login screen which calls the auth server. I do not check for the audienceid as the client will not know about it. auth server generates the jwt token (once the login credentials are validated) with audienceid for the resource server and then angular makes the request with this new jwt token to the protected webapi which then decodes it (if it matches the audience id) with base64 secret respective to that audience_id.

    I do remember reading somewhere on this blog, that on the Auth server, we should validate the client_id/audience_id. My confusion whether client_id here is different from audience_id? or have I got this all wrong.

  4. Hi, How about suprise for Eid ul Adha, the six installment with Aurelia. Thanks

  5. we are waiting last post about angularjs

  6. Hi Taiseer,

    Do you have any project where i can see integration with Angular. I Know you think to post in part 6, but im starting new project today and perhaps you have one i can guide. Thanks

  7. Hi Taiseer,

    Great post! Thank you.

    Any idea when you will be doing part 6? It would be good to see how it all gets pulled together by an Angular app.

    Kind Regards,

    Paul

  8. Looking forward to part 6!!

  9. Francois van der Merwe says

    September 8, 2015 at 5:38 pm

    GREAT articles!! Really helped me allot! But I am kinda lost with the angularJs part :( /cry

    Anything I can do to help you finish the rest? Maybe call your boss to get you a day off work??

  10. Francois van der Merwe says

    September 9, 2015 at 4:59 pm

    I have a question… How would I got about using the email address as the username??
    Who still uses usernames as a login name??

    I have found a coupe of articles that help with this, but none of them have a solid answer on how to get to this?

  11. Thanks a lot for this series of posts it helped me alot in understanding how Identity works, wich I was having a hard time in doing so, looking forward for part 6!

  12. This is an amazing series and has helped me learn a great deal. I was wondering if you had done any work implementing the different flows of OAuth. I have been trying to implement the Authorization Code flow and it gets much more complicated, do you have any good references for this. Thanks.

  13. Eagerly awaiting the last part of the series.

  14. Excellent stuff yet again Sir Taiseer. Looking forward to the next in the line up. Thanks for your valuable time friend.

  15. Thank you very much for the awesome series! Learnt a lot of stuff. Very eagerly waiting for your next post on angularjs

  16. Jason Nichols says

    September 19, 2015 at 2:17 pm

    I’m assuming you’ll be doing the front-end wrap up will be in Angular 1.x. If so, I’d like to request a follow-up post in Angular 2.0. It would be great to have a practical resource to start learning 2.0 once it’s out.

    Very well-written and useful series, thank you!

  17. Hello Taiseer Joudeh!

    Thank you very much for this terrific tutorial series!

    I’m a java dev trying to learn about .NET for commercial purposes and your blog is helping me so much!

    I’ve to ask you something to clarify my thoughts!

    With this project structure, is a good idea to create a new folder under the project called like “Web”, and inside it put my views / images / layouts ?
    And I can use ROLES to manage domains ?

  18. Excellent series of great articles. Thanks a lot. Love it to start from the scratch. Learned a lot about authentication and authorization with tokens. Looking forward for next article(s).

    Greetings from Berlin

    Roland

  19. Awesome post.. eagerly waiting for next post.. Please post the next one as early as possible

  20. Thank you Taiseer. I help your stuff in my project.
    Please tell me when you plan to write about “AngularJS Authentication and Authorization with ASP.NET Web API and Identity 2.1 – Part 6″

  21. Do you have any example of working with identity and and api roles based authorisation using INT for user and role IDs instead of STRING?

  22. Hi Taiseer – Thank you for a great set of articles.
    But I’m wondering if you can help – I’d like to sign-in the user once the email has been confirmed. Like in your articles; I have an endpoint that is called confirm-signup that takes user-id and a token. It’s here that I’d like to sign the user in (and then redirect to a page in my angular app).
    I’m using the AuthenticationManager and SignIn method (authtype JWT) but the new user isn’t authenticated.
    Here’s a GitHub Gist to show example code – perhaps you could point me in the right direction of what I’m doing wrong?

    https://goo.gl/b4NzCJ

    Many Thanks

    • Hi Chris,
      From your code Gist I noticed that you are using cookies authentication not Tokens, are you sure that you are generating JWT token and your API is configured to understand those tokens?

      • Hi Taiseer – I was sure I was generating JWT tokens
        Currently my AngularJS client app performs a login using an owin oauth endpoint based on what you’ve described; hitting the endpoint ‘/oauth/token’. The returned token is stored in the browsers local storage and added to the request headed via a $httpProvider interceptor.
        Perhaps my gist is confusing my goal; once the user hits the confirm-signup endpoint then I don’t want my client app to prompt the user to enter a password (at least in the browser session directly after confirming their email – I don’t mind password prompting if they revisit my site in a later session). I would like for them to be automatically signed in since I’m trusting that its really them who clicked the confirm link. The main reason is to provide a more fluid experience for the user as they start to explore my site.
        Based on your response this.Authentication.SignIn must be the wrong approach here and giving this more thought I guess I need to some how generate a JWT token and return it as part of the response following the confirm-signup. Like a normal login; my client app can then take the token, store it and use it in subsequent requests (via the same $httpProvider interceptor).
        Does this sound right? and if so what would be the best approach to generate the token from inside the controller method or should I somehow delegate this to the owin middleware to generate the token as the confirm-signup response passes through it?
        Any hints on how I could archive my goal would be very much appreciated.

      • Hi Taiseer – for what its worth I thought I’d share the I’ve come up with.
        To Summaries – In the AccountController ConfirmSignUp method; I use the user-manager to generate a custom token which I’ve called GRANT-ACCESS, then redirect to my confirm-signup page with the username and token in the uri.
        My angular app resolves the ui-route to confirm-signup and performs a login, passing the token as the password.
        Finally there is an amendment to GrantResourceOwnerCredentials, so that if the FindAsync (by username and password) doesn’t return the user then I try again but this time treating the context.Password as the GRANT-ACCESS user token to verify. If the token is valid then I return the JWT authentication ticket as if the user had logged in with a valid password.

        https://gist.github.com/chrismoutray/159e6fd74f45d88efd12

        If you think this is a really bad idea then please let me know
        Thanks.

        • Hi Chris,
          I have looked into the gist and what you did is correct, you created like temporary One time password (token) which will be used to authenticate users for the first time.
          I just recommend you to check for user existence first thing in method ConfirmSignUp to avoid any exceptions if the user tried to change the user id in the URI.

  23. Thanks for the great articles. I’m using this as the baseline for the project we’re working on. Any chance we’ll get to see the last article where you connect everything with AngularJS? If you’re busy, could you give us a hint as to how AngularJS sees the claims? We have different 3 different roles for our site.

  24. Hi Taiseer,
    Thank you for the well written and easy to follow tutorial. I’m looking forward to reading the last piece.

  25. Hi Taisser, any idea when part 6 comes? You have any plan?

    Thanks.

  26. Hi,

    Really appreciate your kindness to share your knowledge, i have question on token base, what if i want to refresh that token and generated new one.

    Thanks,

  27. Hi Taiseer. Thanks for the great articles. Say please when you plan write 6 part?

  28. I can use this authorization to implement applications not SPA? In Asp.net MVC/Razor? The authserver work as an authentication as google?Sorry my english, BR here

  29. Fredrik Strandin says

    October 16, 2015 at 5:08 pm

    Have now followed your example and just want to say that they really help. These bolg post are some of the best I’ve read. Really shows that you can be your thing. Thanks

  30. Hello Taiseer,
    Thanks for spending your precious time to help the community.
    I am closely following this post and comments, is it possible to release last part of this series in near future?
    Thanks
    Prash

  31. Bhupinder Singh says

    October 25, 2015 at 11:08 pm

    Hi Taiseer,

    I would like to thank you for creating this wonderful series of articles and describing each individual element clearly. It helped me alot as a newbie to MVC Asp.Identity.

    I implemented of all these five posts in my api without any single issue. Now, our api has a requirement to authorize each api user against specific operations or controllers. To elaborate, for eg: JohnDoe as an api user can only access two specific operations where as an another user(JohnDoe2) can access three specific operations. Is there any organized way to implement this kind of functionality in the api ?

    One way, I thought to customize: Storing each api operation name with a username in Sql tables. When an user will access a specific function, I will get the username from Claims and then validate against the Sql table to see if this user is allowed to perform this action.

    Thanks,
    Bhupinder

  32. Hi,

    Thank you for the tutorial.

    I need help in uploading to azure. What are the parameters I need to change to make it work on azure cloud. Should I modify the startup.cs file. Please let me know.

  33. Hi Taiseer,

    Once again…. Great Post!

    I’ve been developing a cross platform mobile application using Angular, Breeze and Ionic on the front end. I have used your posts to develop the webApi backend. I am able to login with a user name and password and achieve authentication and role authorisation to my webApi methods.

    My question is….. How do I secure the information being sent over the wire? It looks like everything is sent and received in plane text. Am I missing something?

    Any help appreciated.

    Regards, Paul.

    • Hi Paul,
      Glad the posts were useful
      Well when using bearer tokens you need to use TLS all the time, this is a must, and that is the only way to avoid sending data in pain text, TLS all the way.

      • Hi Taiseer,
        Thanks for getting back to me:)
        This may seem like a daft question, but….. What do you mean by TLS? Do you mean using https for all communication, which would involve issuing ssl certificates? How would this work on a mobile device?

        Also…. Do you cover TLS in any of your blog articles? If so, could you point me in the right direction.

        Thanks for the help.

        Regards, Paul

  34. Thomás Henrique says

    November 4, 2015 at 7:15 pm

    Hi Taiseer!
    Thanks by this great series of articles. Congratulations!

    Do you have any idea when the part 6 comes?

  35. Thank you so much !

  36. Very helpful!!
    No part 6 yet?

  37. Thank you very much.
    Have a Q:Where would be the best place to unpack claims within the API so that consumer wouldn’t need to call another end point? And without unpacking claims inside every controller.

    • Hmmm I’m not sure but maybe I will create helper method in BaseApiController which inherits from ApiController object or I will create filter for this, but do not quote me on this, it might not be best way to implement it

  38. i have read this whole tutorial … but i cant find how to login my user ? i am looking for the login controller

  39. Hi Taiseer,
    I’ve noticed that the ‘Refresh Token’ code is not included in the source code for this post. Will you be including this when you pull everything together in your final post?
    Thanks for the help.

    Regards,
    Paul

    • Hi Taiseer,
      I have merged the code from this blog with the code from your Refresh Token blog http://bitoftech.net/2014/07/16/enable-oauth-refresh-tokens-angularjs-app-using-asp-net-web-api-2-owin/

      I’ve got the issuing of access_token and refresh_refresh token working, but I’m having trouble using the access_token to access my ordersController API. I’m getting “Authorization has been denied for this request” when I try to access any API method decorated with [Authorize(Roles = “User”)]

      I’ll keep plugging away with it, but any help would be appreciated.

      I’ve already asked this question earlier, but….. Do you think you could include the ‘Refresh Token’ code when you finally pull it all together in your 6th and final post?

      Kind Regards,
      Paul

      • Hi Paul,
        Are you using JWT tokens format or normal token format provided by Katana implementation? If you removed the Roles and just used [Authorize] attribute will this work? I’m afraid that you are not setting the Roles correctly before issuing the token. If you are using JWT can your try to decode it using jwt.io and make sure that issuer, and roles are set correctly?

        • Hi Taiseer,
          Thanks for getting back to me.
          This is what I have in my startup.cs
          AllowInsecureHttp = true,
          TokenEndpointPath = new PathString(“/token”),
          AccessTokenExpireTimeSpan = TimeSpan.FromMinutes(1),
          Provider = new SimpleAuthorizationServerProvider(),
          RefreshTokenProvider = new SimpleRefreshTokenProvider(),
          AccessTokenFormat = new CustomJwtFormat(“http://localhost:59822″)

          Is this what you mean by JWT tokens format? ie. AccessTokenFormat = new CustomJwtFormat(“http://localhost:59822″)

          BTW: I have changed the Provider from CustomOAuthProvider to SimpleAuthorizationServerProvider and added the RefreshTokenProvider and AccessTokenFormat

          I’m trying to merge the two projects together and as you can see, I’m struggling a bit.

          Any help appreciated.

          Kind Regards,
          Paul

        • Hi Taiseer,

          Got this working:)
          Your comment got me looking in the right place. Here’s the bit of code that does the trick:-

          ClaimsIdentity identity = await user.GenerateUserIdentityAsync(userManager, “JWT”);

          It’s the ‘JWT’ that was missing, and….. It now works:)

          I need to do some more tests, but so far it looks like I’ve refresh tokens working with encoded claims…. Excellent!

          Thanks for the help.

          Regards, Paul.

Leave a Reply

Connect with Me

Search

Given URL is not allowed by the Application configuration: One or more of the given URLs is not allowed by the App's settings. It must match the Website URL or Canvas URL, or the domain must be a subdomain of one of the App's domains.

View static HTML