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:
- Configure ASP.NET Identity with ASP.NET Web API (Accounts Management) – Part 1.
- ASP.NET Identity 2.1 Accounts Confirmation, and Password/User Policy Configuration – Part 2.
- Implement JSON Web Tokens Authentication in ASP.NET Web API and Identity 2.1 – Part 3.
- ASP.NET Identity 2.1 Roles Based Authorization with ASP.NET Web API – Part 4.
- ASP.NET Web API Claims Authorization with ASP.NET Identity 2.1 – (This Post)
- AngularJS Authentication and Authorization with ASP.NET Web API and Identity 2.1 – Part 6
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.
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:
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 |
[ { "subject": "Hamza", "type": "http://schemas.xmlsoap.org/ws/2005/05/identity/claims/nameidentifier", "value": "cd93945e-fe2c-49c1-b2bb-138a2dd52928" }, { "subject": "Hamza", "type": "http://schemas.xmlsoap.org/ws/2005/05/identity/claims/name", "value": "Hamza" }, { "subject": "Hamza", "type": "http://schemas.microsoft.com/accesscontrolservice/2010/07/claims/identityprovider", "value": "ASP.NET Identity" }, { "subject": "Hamza", "type": "AspNet.Identity.SecurityStamp", "value": "a77594e2-ffa0-41bd-a048-7398c01c8948" }, { "subject": "Hamza", "type": "iss", "value": "http://localhost:59822" }, { "subject": "Hamza", "type": "aud", "value": "414e1927a3884f68abc79f7283837fd1" }, { "subject": "Hamza", "type": "exp", "value": "1427744352" }, { "subject": "Hamza", "type": "nbf", "value": "1427657952" } ] |
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:
Subject | Type | Value | Notes |
---|---|---|---|
Hamza | nameidentifier | cd93945e-fe2c-49c1-b2bb-138a2dd52928 | Unique User Id generated from Identity System |
Hamza | name | Hamza | Unique Username |
Hamza | identityprovider | ASP.NET Identity | How user has been authenticated using ASP.NET Identity |
Hamza | SecurityStamp | a77594e2-ffa0-41bd-a048-7398c01c8948 | Unique Id which stays the same until any security related attribute change, i.e. change user password |
Hamza | iss | http://localhost:59822 | Issuer of the Access Token (Authz Server) |
Hamza | aud | 414e1927a3884f68abc79f7283837fd1 | For which system this token is generated |
Hamza | exp | 1427744352 | Expiry time for this access token (Epoch) |
Hamza | nbf | 1427657952 | When 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:
- Assigning claims to the user on the fly based on user information.
- Creating custom Claims Authorization attribute.
- 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 Name | Usage |
---|---|
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:
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 🙂
Thanks man , great article. really useful. +1
Can’t wait till the last post.
Any recommendation on how to host the whole solution in Azure ?
Hi Damon,
Azure web sites is the simplest way to do it, please follow this link
I have follows all post and waiting for the last. Is it ready yet?
This is IMO an absolute anti pattern. This only creates a stronger coupling between your controller/business code and you authZ policy (even stronger than the standard AuthorizeAttrinbute – and that was bad already). They should be decoupled from each other.
Claims are only input to authorization decisions – not the answer.
Hi Dom, so you recommend creating ClaimsAuthorizationAttribute as you have done already in the Identity model using something similar to this attribute?
Probably more like this
https://github.com/IdentityModel/Thinktecture.IdentityModel/tree/master/source/Owin.ResourceAuthorization
https://github.com/IdentityModel/Thinktecture.IdentityModel/tree/master/source/Owin.ResourceAuthorization.WebApi
https://github.com/IdentityModel/Thinktecture.IdentityModel/tree/master/source/Owin.ResourceAuthorization.Mvc
Feel free to contribute.
But my main point is – regardless how you do it – keep controller and authZ logic separate. Otherwise this will become a maintenance nightmare.
These days I personally tend to dump the whole attribute idea in favour of “traditional” means of injecting code – e.g. using DI.
Thank you Dom for the advice, I agree with you. Will work on the post and update it soon.
Taiseer, did you ever make any modifications per Dominick’s suggestions?
To be honest no, but I highly recommend you to check the ThinkTecture identity server and their custom Authorize attribute which uses scopes, it is the right way to have finer grained control.
What is DI?
@dominick “But my main point is – regardless how you do it – keep controller and authZ logic separate. Otherwise this will become a maintenance nightmare.”
Above went above my head, if you dont mind giving a pointer?
As always, great! Thanks! If I have an mvc site with several pages, and one page contains SPA, how to integrate identity system in such type of application. How to combine JWT and Cookie authentication?
Hi Taiseer,
First off I’d like to thank you for the taking the time to answer my first question and posting all the tutorial + part 5, very kind of you.I spent some time trying out and re-reading from part 1 thru 4 and I’ve found some mistakes that I’ve done and some other that was caused by my misinterpretation of some things.
In the SPA solution I have right now we are not using any AngularJS for our front end, we are using MVC controllers to display our views, so I am using a WEB API Account controller for the logic and a MVC controller to call the views. Thing is whenever I tried to call the ChangePassword method (from web API) I always get a 401 unauthorized response, it seems like my credentials never get passed along after I logged in and called /oauth/token once. I am able with Postman to change the password like you showed at the end of part 2, which is why I am thinking that my JWT does not get passed or there’s an issue with the header and its params. Is this behavior normal or is it the way I’ve implemented things around the JWT logic, like my front end JavaScript to login and call the TokenEndPointPath ?
P.S I feel like the error I am having is what you are explaining right here :
https://auth0.com/blog/2014/06/24/authenticating-your-angular-app-with-auth0-and-asp-net-owin/
“The implementation for this controller is pretty straight forward. We are just sending an HTTP GET request to the secured http://auth0api.azurewebsites.net/api/shipments endpoint. If the call has succeeded we will set the returned shipments in the $scope and if it failed because the user is unauthorized (HTTP status code 401) then we’ll redirect the user to the application root.
Now to be able to access the secured end point we have to send the JSON Web Token in the authorization header for this request. As you notice, we are not setting the token value inside this controller. The right way to do this is to use AngularJS Interceptors. Thankfully, `auth0-angularjs module makes implementing this very simple. This interceptor will allow us to capture every XHR request and manipulate it before sending it to the back-end API so we’ll be able to set the bearer token if the token exists in the cookie store (user is authenticated).”
Hi Simon,
You are right, you are not setting the bearer token in the Authorization header when you call “ChangePassword” endpoint, this depends on how you are building the front-end application, so in case of an Angular App, you need to set the headers manually for each request. Now because you are using MVC app to render the views it seems there is no AuthZ header sent, please use fiddler to monitor the request. This SO answer might help.
Hi Taiseer.
I’m finding this article series very interesting. I’ve also been thinking how third-party authentication would fit into this, i.e. Google, Twitter, etc. I’ve had a quick read over your other article titled “ASP.NET Web API 2 external logins with Facebook and Google in AngularJS app” and my initial thoughts are I could follow the article as is and instead of doing step #9 “Generate Local Access Token” I would integrate the access token into the JWT.
Would this be correct (or I am over-simplifying it :))?
Thanks
James
Hi James, it is the same, if you configured the format of token to use JWT then you can follow this post and it should work.
That’s great to know. Really looking forward to the final part. Many thanks for such a useful and interesting series.
Always a most valuable resource – You’re on a tear here Taiseer! 🙂
Thanks John for your comment, but I guess I need to update this post based on Dominick feedback 🙂
You’re Rock!
I look forward to continuing
Glad you like it, thanks for your comment 🙂
could you briefly explain how you would take your series and extend it for mulitple applications and single sign on?
thank you!
I too would love to see adding multiple applications, if only on the claims/roles side, for me. My goal for this is to have a single location (these posts) that handle users. Then have multiple sites calling this central app for authorization and claims.
Hi,
I will also appreciate if an update could be done to extend this project for multiple applications and single sign on.
Secondly, in regards to creating CustomUserValidator in part 2 of this series, Am developing an application will be split into two admin registration and user registration which i want the users to register with any email address (e.g gmail.com, yahoo.com) while the admin will only register with the official company email (e.g admin@company.com)
/// List _allowedEmailDomains = new List { “outlook.com”, “hotmail.com”, “gmail.com”, “yahoo.com” };
/// ListAdmin _allowedAdminEmailDomains = new List { “company1.com”, “company2.com”};
How can i separate the logic for this or conditionally configure this, since the validation logic for the user admin are called in the startup.cs
Should i create separate authorization server for users and admin, Or i can use one while using roles and claims will separate them. Please advice me.
Thanks.
Thank you for making these. When do you think the next post will be up? I am anxiously waiting for that hook up to AngularJS.
Thanks for your comment, most probably next Tuesday, will do my best to finish it!
Taiseer,
I am a faithful subscriber to your posts and have benefitted greatly from your tutorials. Like most of us I eagerly await your postings but realize they are an uncompensated effort. Still, they can’t come fast enough for me! I have multiple projects in progress including this current series Authentication Server, and a separate Resource Server and I’ve separated them by combining and following some of your other tutorials. My greatest need is for your next scheduled post to show the AngularJS frontend and JWT example as you have planned in part 6. I imagine it would be more in-depth and lengthy than the previous 5 parts. Any idea of an estimate or ETA?
Thanks again for the work you do…
Tony, thank you so much for your comment, you know that it is hard to manage your time between your full day work, family and blogging, but I will do my best to publish it next Tuesday, I’ve received the same comment from different readers so hopefully I will not let you down 🙂
Taiseer,
Thank you very much for all the hard work that you put into this posts.
I can tell you that your effort reaches so many places in the world. I’m from Costa Rica and as Tony said we’re eagerly waiting for your next post about Angular. We’ll use your example as a template for our future Angular developments.
Again thank you very much and keep up the good work.
You are welcome Rolando, happy to hear that I have readers from Costa Rica 🙂 will do my best to post it this Tuesday.
I’m eagerly waiting for the Part 6. Your posts are great! Taiseer
Hi Taiseer,
I have found a another way to manage claims without using [Authorize(Roles = “Admin”)] or a custom authorize class which inherits from the Authorize attribute
What I am doing is decorating my service methods with this
[ClaimsPrincipalPermission(SecurityAction.Demand, Operation = “Operation”, Resource = “DeleteRecord”)]
and then create a class called CheckClaim which inherits from ClaimsAuthorizationManager. I then override its Checkacess method where I check the claim using
context.Principal.HasClaim(action, resource); //action and resource are found in the authorizationContext
Then it needs a web.config entry in the configsection like so
With that config entry, the CheckClaim class’s CheckAccess method gets called for all api methods that are decorated with the ClaimsPrincipalPermission attribute.
Let me know your thoughts on this. I for one feel that with this in place you wont have to convert claims into roles. I am still early into researching this and would like to know if there are any issues you see with going this way.
looks like web.config content in my comment above was removed by this forum application 🙂
Taiseer,
I really appreciate your taking the time to do this. I’ve got everything wired up and even hooked into an angularjs frontend, but what I’m wondering is that if its feasible to pass back to the client custom claims with the jwt token, or if I should be sending over another response to the backend with the token in the header to get at that info.
I can see where it adds the custom claims to the response, but what shows up on the otherside is just the access_token, token_type and expires_in in the json object.
Thanks again for taking the time to do this!
Jason
Hi Jason, You can add them to the response but I prefer to create dedicated endpoint to get extra data about the user, but all the claims are already in the JWT and you can just decode it and read the claims, right?
It looks like thats the part that I haven’t figured out yet. Is decoding the JWT on the client side. I’ll have to start looking into that and how I can do that. Thanks for the insight
Hello again, Taiseer!
Can we use JWT authentication in MVC web apps instead of Cookie or Form authentication? For example, on login page user enter his credentials which sends to our Authorization Server. Auth Server checks creds and returns JWT-token and our Web app use it to show user pages which [Authorize]’ed.
The point of all this is that I do not want to use authentication with AngilarJS, because in this case, the attacker can view the contents of the pages being not even authorized simply by disabling JavaScript
Hi Nail,
You can but in your MVC controllers, you will be responsible to set the Authorization header value for each request to any protected resource.
But who said that attacker can has access to server resource from AngularJS application when the JS is disabled? Remember that all this Authorization and data protection is done on the server side, so JavaScript has nothing to do it with the security part here.
Hi Taiseer Joudeh,
I have posted this Question twice before One in Part Two and the other in this part, Since i did not have any response to the two, am posting it again if you could just give me a hint on how to fix this issue.
In regards to creating CustomUserValidator in part 2 of this series, Am developing an application will be split into two registration one for admin registration and user registration which i want the users to register with any email address (e.g gmail.com, yahoo.com) while the admin will only register with the official company email (e.g admin@company.com)
/// List _allowedEmailDomains = new List { “outlook.com”, “hotmail.com”, “gmail.com”, “yahoo.com” };
I only want the admin to have a specified email before the could register,
/// ListAdmin _allowedAdminEmailDomains = new List { “company1.com”, “company2.com”};
How can i separate the logic for this or conditionally configure this, since the CustomUserValidator is called from a single point in the startup.cs
Should i create separate authorization server for users and admin, Or there is a way to seperate the logic. Please advice me.
Thanks.
Hi Taiseer,
I was just wondering when the last part will be posted?
Thanks.
Looking forward to this last post as well.
Hi Taiseer!
First of all, I’d like to thank these fantastic posts you have, they were really helpful!
Now the question I have might sound a bit basic, but it’s something that is giving me some headaches…
I have implemented OAuth Token Authentication using one of your samples as a base and I am using a role-claim encoded in the accessto ken and using it to authorize access to an API. But, I think role-based authorization won’t scale well in my app, so I was thinking in a more granular authorization using claims, like you have in this post. My question is: Should these claims be encoded in the JWT or should we do some a query for the claims of a user to a store everytime we receive a request? Is it ok in a security-perspective to have all those claims encoded in the access token?
Thanks in advance!
Bruno
Hi Taiseer,
Great articles, looking forward to the next post …
Referring to Nail’s comments…
“We want to use JWT authentication in MVC web apps instead of Cookie or Form authentication. For example, on login page user enter his credentials which sends to our Authorization Server. Auth Server checks creds and returns JWT-token and our Web app use it to show user pages which [Authorize]’ed.”
You also mentioned that “…in your MVC controllers, you will be responsible to set the Authorization header value for each request to any protected resource. “
If it is not too much to ask, would you able to provide sample implementation of this or point to any sample references please…?
Reason:
1. We want to implement JWT authorization in our current development, but the project is being developed in asp.net mvc.
2. We want to keep the business logic in web api and remain the UI part in asp.net mvc, this api also will be used in our other applications and some portion will be used by our client application.
3. We are not familiar with Angular JS
Thanks.
Nada
Hi,
I have made a post yesterday but today I see it’s not here, so I will try again. So I am developing an app that is using Role-based authorization and uses JWT to transport the role of the user. I’d like to change to claims-based authorization because roles are not enough for my app, but the question I have is simple: Should I encode all of the claims of the user in the JWT and retrieve those claims from the resource server or should I query the authorization store on every request?
Thanks in advance,
Bruno Oliveira
Hi Bruno,
JWT is self contained token, so all your claims should be included and encoded inside the token it self.
Hope this answers your question.
Hi Taiseer,
Thanks for the reply. I still have some doubts, perhaps it’s better if I explain my scenario a little bit better. So our users might have claims that say something like “CanAccessScreen X”, “CanDoAction Y”, etc… Then there are other kinds of claims like “the user can access these accounts”, and a user can have access to thousands of accounts. What I was thinking was the first kind of claims, I could encode in the JWT, but the second kind of claims I wouldn’t. When the user connected for the first time to our resource server (a signalr endpoint) we would then retrieve the accounts the user have access to from the database and then send it to the client (and keep a cache in the server so we can validate further requests involving accounts authorizations). Given this further explanation, should I encode everything in the JWT or should I follow the way I was thinking about?
Thanks in advance Taiseer,
Bruno.
Hi Taiseer,
Sorry for insisting in this question, but I still can’t figure out the way I should handle the case I specified in my previous answer. Could you give me some hints of where should I go? Thanks!
Where do you feel “Groups” fit within the authentication/authorization space? Let’s say I have User A, B & C. User A & C are in Group 1 and B & C Group 2. Is the group a claim such that User C claims to be in Group 1 & 2? I don’t see these as roles as in certain cases users themselves may be able to setup groups and add/remove users. Any advice here would be appreciated.
I do not see any difference between Groups and Roles here, why you can’t consider Group A as Role A?
Thanks for doing this series, its been a huge help for me. Any idea when the last post will be available?
Hello Taiseer,
First let me congratulate you on the this series i couldn’t find a comprehensive yet simple posts that will help me understand the Identity framework like i did with these posts, so thank you for this.
second now we have created the project and followed through the tutorial how can we host it in Azure without changing it to worker role on Azure?I found a couple of articles that explains how to begin with worker role as a project and then host OWIN inside it but this will require changes to the existing Web API/OWIN startup. do you have some thoughts you might want to share on this?
Thank You again
Great article. Saved me some time.
Do you perhaps have examples on how to implement Claims Based Auth using Owin and Active Directory ?
Hey, it’s a great series, when do you think the last part will be up?
I wish I had more time to do this, it’s half way tho but it’s more complicated than expected 🙁 I will try my best to finish it before mid of May.
As anticipated as we are for the final piece, I want to say that we all appreciate the work you put into these tutorials. Thank you Tasieer for what is yet to come.
I look forward to the next installment, but please don’t feel rushed by those of us asking when it’s going to be released. Your posts (not just this series) have been invaluable resources for me and others, and I’m sure most of us here prefer quality over speed. 🙂
Taiseer Joudeh, congratulations on your blog.
I’m from Brazil and I follow your posts for some time, I really want to see part 6 of this series on
ASP.NET Identity 2.1 with ASP.NET Web API 2.2 and AngularJS
greetings from germany 🙂
i have started to play a bit with programming and this tutorial series helps me a lot to understand what is going on here 🙂
my english is not the best but your explanations are very clear and good to understand. i look forward to part 6 too. do not stress, good things take time 🙂
You are welcome Christian, glad to here that posts are useful. Hopefully the last part will come soon.
Thank you so much for your tutorials.
As everyone I am waiting for the last post, but my question is: can we use your other tutorial to start building the angular app?
Hi, yes sure you can use it as a starting point.
Hello TJ,
Thanks for sharing such a valuable information, is it possible if you can put some reference links of how to use this in MVC app. Also how to integrate FB,google,outlook etc.c
Hello Prashant, FB and Google authentication are covered in previous posts, you can check the archive.
Hi Taiseer,
Thanks for the great posts . Any plan to publish the last article?
Hi
great article. Thanks a lot
can I ask you when you will publish the Sixth post?
It’s been 2 Months -I am doubtful if it is really hard to implement or if this “approach” really works -I guess NOT.. #sorry
Do not be #sorry. I blog when ever I want 🙂
Taiseer, sir. It took you just over two months to get 5 awesome blog posts written. It’s been now 2 months since anything new. I totally understand the fact that this seems to be a “hobby” site for you so I can not really complain too much. But the math does not work out on why you cranked out 5 indepth posts in about 8 weeks and it’s been another 8 weeks for the final post. Saying this with the utmost respect, I may have to create a new hashtag of #BlogTease for you. 🙂 If you come to the states, I’ll buy you a beer or beverage of your choice if that will help.
Thanks Kevin, I was very busy during those 8 weeks..Traveling always, new projects, and family commitment.. I hope that I will find time again to focus and blog frequently, I really feel bad about not blogging as before.
Thanks again for you comment and it makes me feel happy to know there are loyal readers like you!
Are there any plans for publishing the final post of this series?? The previous blog posts were extremely helpful in understanding JSON Web Tokens, OAuth2, and Claims based Authorization.
Thanks for you message, I will do my best but I kept traveling all the time during the previous 2 months, that’s why I was not able to focus and finish the last post.
Hey Taiseer,
I included a simple table “Orders” in database and now I’m trying to establish connection with this project, but without success.
Can you tell me how do it or update your git rep? Thanks. 🙂
You need to configure EF correctly, check my old post which might help.
Hi Taiseer ,
Very good article. I have one problem to create user i get error 404 ” http://localhost:59822/api/accounts/create ” do you have the some problem when you start the service?
thanks a lot and sorry if my question is dumb
Hi Taiseer ,
I try from “Postman” and i get this error 415 now
“message”: “The request entity’s media type ‘text/plain’ is not supported for this resource.”,
“exceptionMessage”: “No MediaTypeFormatter is available to read an object of type ‘CreateUserBindingModel’ from content with media type ‘text/plain’.”,
“exceptionType”: “System.Net.Http.UnsupportedMediaTypeException”,
“stackTrace”: ” at System.Net.Http.HttpContentExtensions.ReadAsAsync[T](HttpContent content, Type type, IEnumerable
1 formatters, IFormatterLogger formatterLogger, CancellationToken cancellationToken)\r\n at System.Net.Http.HttpContentExtensions.ReadAsAsync(HttpContent content, Type type, IEnumerable
1 formatters, IFormatterLogger formatterLogger, CancellationToken cancellationToken)\r\n at System.Web.Http.ModelBinding.FormatterParameterBinding.ReadContentAsync(HttpRequestMessage request, Type type, IEnumerable`1 formatters, IFormatterLogger formatterLogger, CancellationToken cancellationToken)”http://prntscr.com/7fr7cp
Hi, It should be application/json not application/jason
Thanks a lot for your response.
I see my silly error.
Now I have some other mistake
The message again is for media type now is json and the json input is
“Email”,
“FirstName” ,
“LastName”,
“Role Name”,
“Password”,
“ConfirmPassword”
“message”: “The request entity’s media type ‘text/plain’ is not supported for this resource.”,
“exceptionMessage”: “No MediaTypeFormatter is available to read an object of type ‘CreateUserBindingModel’ from content with media type ‘text/plain’.”,
“exceptionType”: “System.Net.Http.UnsupportedMediaTypeException”,
“stackTrace”: ” at System.Net.Http.HttpContentExtensions.ReadAsAsync[T](HttpContent content, Type type, IEnumerable
1 formatters, IFormatterLogger formatterLogger, CancellationToken cancellationToken)\r\n at System.Net.Http.HttpContentExtensions.ReadAsAsync(HttpContent content, Type type, IEnumerable
1 formatters, IFormatterLogger formatterLogger, CancellationToken cancellationToken)\r\n at System.Web.Http.ModelBinding.FormatterParameterBinding.ReadContentAsync(HttpRequestMessage request, Type type, IEnumerable`1 formatters, IFormatterLogger formatterLogger, CancellationToken cancellationToken)”http://prntscr.com/7h3v1b
Thanks for your comments.
Currently I’m not facing 404 when I hit this endpoint, make sure you are using the right http verb and sending the correct model in request body.
Any Idea when the post 6 will be?
Hi great articles!!!
Im waiting the last one, can i used in own project? Any idea when post 6 comes?
Thanks for you comment Tomas, feel free to use it in your project.
Great thanks. Do you think this tutorials can be used for production applications, or its better separates the Authorization Server like other posts you have?
Hi Tomas,
If you are going to build multiple APIs that will share the same authentication and authorization features, then better to separate the AuthZ server from Resource Servers. As well if you are looking for solid AuthZ server then ThinkTecture is great choice.
Great articles! We are building an intranet application with AngularJS front end and WebApi backend. I would like to generate Json Web tokens to secure the web api endpoints. Since it is an intranet application we have windows authentication enabled and a TAM (tivoli access manager) service is used for authorization and Single sign on experience. Do I still need to use ASP.net Identity model with OWIN and OAUTH to generate JWT? I am trying to convert the Resources from TAM serivce to Claims and generate JWT so that I can do Claims based Authorization for WebApi endpoints. Also waiting for your next post to get a clear picture on AngularJS side 🙂
Hi,
Just wondering while the last part “6” of this article its taking tooo long time; to come up.
Nelly
HI,
It‘a wonderful post.
I learn a lot from it
Hi, thank you for all the articles in the series so far. Just wondering when will the part “6” come up?
Thanks for assistance provided us with your implementation.
I have a question
When the admin modifications roles of a user, the token remains active with previous roles. How can we force the termination of the token with the old role;
Hello, thanks for excellent post ! But i have a problem with project, when i build and run project, IIS notice error 403 forbidden ? i think maybe startup.cs class of OWIN is not working. Please help!
You are welcome, thats not an errors it it is default response for Web API project, try start issuing request to the Api and all should work fine.
These tutorials are the absolute best I’ve come across. I LOVE that you start from an empty project and add each bit at a time. It really helps to understand how all the pieces fit together and makes it much easier to extend ASP Identity to fit my needs. Taiseer, you are my hero <3. Cant wait for the next post.
Hi Daniel,
Thanks for your sweet message, happy to hear that posts were clear and complete to learn from.
Let me know if you need further help.
Hi Taiseer,
great work so far and thx for sharing.
Is there any info when we can expect the final part 6?
Regards.
madas
Thank you Taiseer. This is an extremely helpful series for people interested on how JWT (and tokens in generate) work with WebAPI. I look forward to the last section on Angular.
I have two questions about the third method of managing claims above.
1) Do I need to issue a new token to the user for subsequent requests? If not, those claims won’t be part of the token payload.
2) Do the claims added to the AspNetUserClaims table get deleted when the token expires. I guess I’m a bit confused on these claims.
Thanks gamin
Hi Mike, thanks for your message and please find my answers below:
1 – Any change in user claims will not take affect until you generate new access token for the user so those claims will be encoded inside the token.
2 – The expiry of the access token will not affect the claims for you as a user, you can issue an access token for 1 day, and in the next day you need to login again and fetch all your claims for the database.
Taiseer,
We’ve spoken via email on numerous occasions and I am always interested in your posts as they all contain straight forward explanations of this sometimes complex code. Just wanted to say I appreciate the effort you put in. You’ve got some fans up here in Alaska.
Regards,
Austen
Thank you Austen for you sweet comment, comments such this really makes me happy, I need to get back to blogging very soon. Things should be back to normal in August so I’m planning to post more about the ASP.NET 5 🙂
Hi Taisser, can’t wait for those posts, I would also love to see authentication done with Angular 2 (when it comes out).
Kind regards from the UK,
Martin
Thanks Martin, will do my best to finish those soon. I’m at London now, and I fall in love with this beautiful city 🙂
Me too 🙂
Hope can read it tomorrow 😀
Thanks Taiseer!
What is the trust level of your hosting environment? I am trying to run a CustomOAuthProvider in a medium trust level hosted server but I get the following error when executing the userManager.FindAsync method:
Inheritance security rules violated while overriding member: ‘Microsoft.AspNet.Identity.TaskExtensions+CultureAwaiter
1.UnsafeOnCompleted(System.Action)'.
2.FindAsync(String userName, String password) at CustomOAuthProvider.d__4.MoveNext() in CustomOAuthProvider.cs:line 31Security accessibility of the overriding method must match the security accessibility of the method being overriden.
at Microsoft.AspNet.Identity.UserManager
Hi! Sorry for off-topic, but what theme do you use for code samples?I like it very much 🙂
Thank you for this excellent tutorial series! This is the first series that I have completed in a long time where I encountered no unexpected errors. Everything worked all the way through. As someone who is learning this stuff, I greatly appreciate that!
I do have one question: I have another API and I would like to use this Identity API that we built here to authenticate and authorize users to make calls to it. Is that possible without actually building the functionality into the API itself? Can I reference this API in the other one, and then use the attributes as you have shown here? I’m not clear on the best way to do this, but I’m sure there is a proper way of doing this.
I’m anxiously awaiting the next installment of your series! Thanks again for your hard work!
Hi Eappell,
Thanks for your message, it really pleases me knowing that those series f posts were helpful in your learning process.
Back to your question, sure you can do this, what you are looking for is something called “Authorization Server” where this server will be responsible to authenticate users and manage them. If you are looking to build a simple one I recommend you to look at my other posts here and here. But if you are looking to use full fledged Authorization Server then ThinkTecture Identiy Server is the right way to go.
Good luck!
Last year you did a related series on AngularJS Token Authentication using all the same technologies you present in this series of posts. I’m trying to determine how to get the best implementation for my web site by merging features of that series with this one. From where I sit there are a lot of similarities between the series but the one from last year separated the Authorization Server from the Resource Server and showed more about using JWT tokens. I want to use the information in your newer series but also take features from that other series.
I have run through both series of posts and followed your steps closely on each. To accomplish what I stated above, would you recommend I use the second, more current set of postings as my start point then separate the servers and add JWT with Refresh Tokens like you did in the previous post? Or would you recommend we start with the first tutorial and then add features from the second.
Maybe I’m showing how much more I have to learn by asking these questions but your blog has motivated me to try. Am I missing something fundamentally different about the two blog series? Any insight into the differences between the two series, and especially any suggestions on how best to proceed would be appreciated.
Marcus
I think the answer to my questions are inherent in actually doing the work. There is a lot of overlap in both series but the one from last year focused on “token-based authentication” while this one focuses on “Identity”. I started with this series and will use everything I can from it. Once I have it working I will refer to the last series to break up the servers and add Refresh Token support. Taiseer has answered a lot of the questions I might have throughout all of his blogs. I will just have to read them all to get the best implementation for our purposes rather than expect any one blog or blog series to give me the full road map.
I forgot to thank Taiseer for sharing such great blogs with the rest of us! Thanks Taiseer!
You are most welcome, happy to know that posts were useful 🙂
Thanks for a great series of articles. They have been a huge help with understanding the identity model and how to make it work with ASP.net webapi. I was curious if you had done the next article yet where you are using AngularJS with the the Authorization & Authentication.
Thanks again for the great articles!
Thanks for your comment, to be honest not yet, hopefully I will be able to publish it soon.
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.
Thanks Jamie, happy to help 🙂
How about a twist and making a final article with aurelia as an Eid Al-Adha gift ? Thanks
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.
Hi, How about suprise for Eid ul Adha, the six installment with Aurelia. Thanks
🙂 Hopefully I will be able to publish it, thanks for you message Khuzema 🙂
we are waiting last post about angularjs 🙂
Will do my best to finish it, thanks 🙂
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
Hi Tonchi,
Currently i do not have, but you can check my other post which might help
Ok thanks. Its like the merge of both post includes all functionalities.
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
Looking forward to part 6!!
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?? 😀
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?
Unfortunately you need to store the email in userName field to achieve this, I can’t recall that asp.net identity works with emails only without using userName.
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!
You are welcome, glad to help 🙂
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.
If you need full identity server, then my recommendation is to take a look at Think Tecture Identity Server.
Eagerly awaiting the last part of the series.
Excellent stuff yet again Sir Taiseer. Looking forward to the next in the line up. Thanks for your valuable time friend.
Thank you very much for the awesome series! Learnt a lot of stuff. Very eagerly waiting for your next post on angularjs 🙂
You are welcome, thanks for your message.
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!
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 ?
Hi Lucas,
What do you mean by using Roles to mange domains? Can you elaborate more please?
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
Thanks Roland for your message, glad to hear it was useful 🙂
Awesome post.. eagerly waiting for next post.. Please post the next one as early as possible 🙂
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”
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?
Nevermind, did it
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 thecontext.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.
That’s great – it’s the reassurance I needed – Thanks
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.
Hi Taiseer,
Thank you for the well written and easy to follow tutorial. I’m looking forward to reading the last piece.
You are welcome Reka, Thanks for your message
Hi Taisser, any idea when part 6 comes? You have any plan?
Thanks.
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,
Hi Reno, this is dedicated post about this, hope it will help
Hi Taiseer. Thanks for the great articles. Say please when you plan write 6 part?
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
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
Thanks Fredrik for your message, happy to help 🙂
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
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
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.
You can publish it directly to Azure Web Apps, I do not know what you mean by “parameters”?
Hello,
Your blog is great, I can find a lot of great ideas and practical solutions . Therefore I have decided ask you for advice in question of authorization design for business application, that will be available both from intranet and internet. I am planning solution that users logged in domain (intranet) would be authorized automatically in application, while when connecting from internet (out of domain) would be logged in using Two Factor model. Basing on your huge experience could you advise me, suggest, propose any suitable solution?
Thanks in advance
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
Hi Paul,
Mobiles has nothing to do with HTTPs as long the certificate is valid and issued by global trusted issuer such as thawte or verisign. This post by Troy Hunt might help.
Hi Taiseer!
Thanks by this great series of articles. Congratulations!
Do you have any idea when the part 6 comes?
You are welcome, I will do my best to complete it soon
Thank you so much !
You are most welcome:)
Very helpful!!
No part 6 yet?
Not yet 🙁
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 🙂
i have read this whole tutorial … but i cant find how to login my user ? i am looking for the login controller
There is no login controller, there is Oauth/Token end point which logins the user and grants him a token, please read post 1 again.
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 https://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.
Can you share your updated code ?
Hi Taiseer,
We have used your article as a base for our authentication for the past year and it has been running great and we’ve had a moderate throughput of traffic.
Over the past couple of weeks the throughput has increased a lot (which is a good thing :)) and we are starting to see the calls to [URL]/token returning as 400 bad request under load, but the majority of the time it response as expected. Have you experience this issue at all? Is it IIS itself that is blocking the traffic? or even .net? Is there a way to prevent the 400 bad request happening under load or even see why its occurring? Is it OWIN that has a setting that needs increasing?
The strange thing is that all our other Web APIs are serving responses as expected. Its just the call to [URL]/token returning as 400 bad request.
Thank you in advance for you help and time.
Steve.
This guide was very helpful in our small project – I appreciate it! One of our developers has been playing with ASP.NET 5 and asked me if you’ll be providing a revision to your guide for the latest version of .NET now that it’s at the release candidate phase.
Hi Chris,
The authentication/authorization in ASP,NET 5 is really different than this version, until now you can not issue access token, you can just consume them, You need to relay on identity provider for this task. So there is no direct way to upgrade this project to the latest ASP.NET 5 without using external identity provider.
Taiseer, thanks for this great series! I am on my second project where I am applying the information I learned from your blog. On my first implementation I was able to use the same server for both the authentication and the resources. On my second I had to separate the two into separate servers and used your blog from 9/24/2014 to make that easy. Thank you for all the help!
Now I am about to take the training wheels off and am starting to do something a little different. I need to extend the model a little further by making it easy for anyone else at my company to publish a new resource server that can use either the role authorization attribute or the claim authorization attribute. There are two issues I need to resolve in order to accomplish this and thought I would ask if you had any feedback that will make my job easier. Whether or not you reply I promise to publish my findings as a “reply” to this “comment”.
Here is what I am trying to accomplish. Any feedback on the best way to attack these will be greatly appreciated.
1. I would like to create a reusable library that would minimize the work required by a new resource server to use this system. I want to save anyone from having to replicate all of your steps if possible. I know some things must be in each resource server but I want to make that as small as possible. I would also like to move as many of the references and nuget packages to a separate dll wherever possible. Have you had any experience doing this and can share any tips or suggestions?
2. Did you ever separate the “ClaimsAuthorizationAttribute” into a reusable library for a resource server to be able to use? The one you created here only resides in the OAuth server. Or did you simply link the resource server to the oauth server library?
Cheers and thank you very much!
Marcus Cole
I already found out you can’t simply link a resource server to the auth server. Lots of 500 errors. I suspect it was due to the [assembly: OwinStartup(..)] in the auth server causing conflicts with the same call in the resource server.
I was able to create a separate library that has all the nuget packages and it’s own “Startup” class. I was able to remove a lot of the Owin nuget packages from the Resource server, too. However, I could not leave the [assembly: OwinStartup(typeof(mylib.Startup))] attribute on the version of the Startup class that is in the separate library because I need to be able to reuse this library with the Auth server and I don’t want to take the chance it will interfere with the Startup in the Auth server. So I created an empty Startup class in my Resource server project and put the [assembly: blah blah] at the top of the local one (but it references the shared Startup). I would gladly accept suggestions on a better way to do this.
Hi,
I’m not sure if you issue only about having the [assembly: OwinStartup(typeof(mylib.Startup))] on Startup class, but there is many different ways to detect Startup classes, here is a detailed post about this. Hope it will help.
Awesome! If I go with the config file setting approach I can clean up the process. I didn’t like the idea of having to create an empty Startup file but it was a decent placeholder. I can also change the name of the Startup that is in the core library to something more impressive. Thx Taiseer!
The final implementation resulted in a very easy to reuse library that any new resource server simply needs to reference and add two entries to their web.config file and one line to their WebApiConfig.cs file. The new resource server does not need to add any Nuget packages since they are all contained in the separate library (“XYX_OAuth_Library”).
In the web.config file I added this line to the appSettings section. This little tidbit is thanks to the comment above by Taiseer. I was able to move the “Startup” class to the separate library and invoke it through this setting in the resources web.config:
Add this “add” line to the handlers section under system.webServer. Note: you want to keep the “remove” before it. This addition allows for the preflight request the browser will make to your server.
In your WebApiConfig.cs file in the “Register(HttpConfiguration config)” method you will want to add the following line to “EnableCors(..)”.
config.EnableCors(“*”, “*”, “*”);
You will find there is no “EnableCors(..)” method in HttpConfiguration. I cheated by making the following extension method in my new XYZ_OAuth_Library:
public static void EnableCors(this HttpConfiguration config, string origins, string headers, string methods)
{
// by putting this in here we only need to nuget Microsoft.AspNet.WebApi.Cors in XYZ_OAuth_Library and not force it in the resource servers
config.EnableCors(new EnableCorsAttribute(origins, headers, methods));
}
The third class in my separate library (after my Startup.cs and ExtensionMethods.cs classes) was my new Authorization Attribute. Once I followed all the steps above in my new Resource Server I was able to adorn my controllers or actions using my custom Authorization Attribute. Sweet!
Thanks for all your help, Taiseer!
Marcus
I was so excited about sharing my results I forgot to escape my config file entries. Here they are again, in order of above
in appSettings:
add key = “owin:appStartup” value= “XYZ_OAuth_Library.Startup, XYZ_OAuth_Library”
in handlers for system.webServer:
remove name = “OPTIONSVerbHandler”
add name= “OPTIONSVerbHandler” path= “*” verb= “OPTIONS” modules= “ProtocolSupportModule” resourceType= “Unspecified” requireAccess= “None”
Can you share example code?
I’d be happy to. The only new code that I didn’t get from Taiseer’s blogs is the extension method which I have shown above. The Startup.cs code was taken from this blog series as was the code for the custom authorization attribute. What other code would you like?
I would like to thank you for helping other readers and posting a detailed comments about your findings and solutions, appreciate it entilzha 🙂
perhaps you could share by committing the seperared library to a github repo and with barebones resource server…
It’s the least I can do seeing as I have gotten so much from your blogs, Taiseer!
I put the code into a the ReusableOAuthLibrary in GitHub. The library is called “OAuth_Library” (go figure ;o) and I kept a skeleton of one of the resource servers and the auth server. They won’t run after I tore out all of our proprietary stuff but I thought it important to be able to see how the library fit in with them.
I welcome any feedback and constructive criticism!
Marcus
I tracked down your repo – thanks for sharing
https://github.com/kendodragon/ReusableOAuthLibrary
Hi Taiseer,
I am trying to integrate your fantastic oAuth Asp.Net web api Solution with Aurelia-Auth solution (https://github.com/paulvanbladel/aurelia-auth). When I try to test oauth token with Postman its works perfectly and gives me token. But when I try to access it using Aurelia-Auth login it gives me
>>>POST http://localhost:59822/oauth/token 400 (Bad Request)
login.js:20 login failure<<<<
When I debug web-api for Aurelia-Auth following value I get in
CustomOAuthProvider.cs for context.Request object properties are Accepts:"application/json", Content-Type:application/json etc
When I debug web-api for Postman following value I get in
CustomOAuthProvider.cs for context.Request object properties are Accepts:"*/*", Content-Type:"application/x-www-form-urlencoded"etc
Can you advice me where I might look for issue.
There are other solutions but yours is most flexible and has feature for our requirements 🙂
Thanks for your time.
Khuzema
Your request body from Aurelia should be as the below:
POST http://localhost:34347/oauth2/token HTTP/1.1
Host: localhost:34347
Proxy-Connection: keep-alive
Content-Length: 167
Accept: application/json
Cache-Control: no-cache
Origin: chrome-extension://fhbjgbiflinjbdggehcddcbncdddomop
Content-Type: application/json
User-Agent: Mozilla/5.0 (Windows NT 6.3; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/47.0.2526.73 Safari/537.36
Postman-Token: dbf2d878-1012-0f4a-d238-a8441f0d13e1
Accept-Encoding: gzip, deflate
Accept-Language: en-US,en;q=0.8,ar;q=0.6
username=tjoudeh&password=xxx&grant_type=password&client_id=26ac3f5d-9cbe-4771-bd4b-77ac1a8cc3cb&client_secret=ClientSecretValue
Hello Taiseer, I am trying to integrate your fantastic JWT solution with another fantastic framework Aurelia. I am trying to use https://github.com/paulvanbladel/aurelia-auth on client side (SPA). But when I try to send login info the server sends me
Failed to load resource: the server responded with a status of 400 (Bad Request)
login.js:20 login failure
Can you advice where can be issue or where shall I look.
Thanks
Khuzema
Hi,
I need to check out the issue, I didnt find login.js in your Repo. Usually 400 bad request is incorrect clientId or Invalid Username/password.
Hi Taiseer,
Thanks for your time & knowledge on blogs that you spend
Here I’ve a use case, how can I host this Identity as centralized (Authentication & Authorization) service, so that I can call certain end point to make use in different applications??
Thanks
Thanks for you message,
If you are looking for centralized identity server, then my recommendation is to check ThinkTecuture Identity server and not to built your own from scratch. The setup is not that hard, but needs sometime to understand all the loving parts there.
Thanks for your immediate response..:)
Excellent work. Thank you so much. I use to write articles sometimes, I know this is hard work. But those articles are maybe among the best I read so far, even if English is not my mother tongue, this is clear, understandable and well documented.
I followed another serie about same topic, but dating from last year (2014) (Angular JS + Web Api2 + identity), also waiting for the last post part 6, even if I already step forward by adding a personal Angular front using one of your older post.
Greetings from Rennes, France
Yann
Thank you Yann for your sweet comment, I agree with you, writing technical articles is not an easy thing, happy to hear that posts were useful and thanks again 🙂
Hi Taiseer
I’ve followed a number of your tutorials and they are great, It would be great if you could provide a basic web site for part 6 using the API, I’ve tried and failed so far !
I’m learning MVC/API/Angular and there are loads of tutorials which in isolation I understand but then trying to put them together into the basis for a real world project is where I’m getting a bit lost.
Thanks
Richard
Cuando Estara la parte 6?