Bit of Technology

  • Archive
  • About Me
    • Advertise
    • Disclaimer
  • Speaking
  • Contact

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

March 31, 2015 By Taiseer Joudeh 323 Comments

Be Sociable, Share!

  • Tweet
  • Email
  • WhatsApp

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.

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:

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:

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

  • An Introduction to Claims – MSDN Article
  • Pro ASP.NET MVC 5 book by Adam Freeman – Chapter 15
  • ASP.NET Web Api and Identity 2.0 – Customizing Identity Models by John Atten
  • Featured Image Credit

Be Sociable, Share!

  • Tweet
  • Email
  • WhatsApp

Related Posts

  • Integrate Azure AD B2C with ASP.NET MVC Web App – Part 3
  • Secure ASP.NET Web API 2 using Azure AD B2C – Part 2
  • Azure Active Directory B2C Overview and Policies Management – Part 1
  • ASP.NET Identity 2.1 Roles Based Authorization with ASP.NET Web API – Part 4
  • Implement OAuth JSON Web Tokens Authentication in ASP.NET Web API and Identity 2.1 – Part 3

Filed Under: ASP.NET, ASP.NET Identity, ASP.Net Web API, Uncategorized, Web API Security, Web API Tutorial Tagged With: Autherization Server, Claims, JWT, OAuth, Token Authentication

Comments

  1. ِDamon says

    March 31, 2015 at 4:28 am

    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 ?

    Reply
    • Taiseer Joudeh says

      March 31, 2015 at 4:31 am

      Hi Damon,
      Azure web sites is the simplest way to do it, please follow this link

      Reply
      • Krish_xx says

        August 2, 2015 at 8:30 am

        I have follows all post and waiting for the last. Is it ready yet?

        Reply
  2. Dominick Baier says

    March 31, 2015 at 8:26 am

    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.

    Reply
    • Taiseer Joudeh says

      March 31, 2015 at 6:21 pm

      Hi Dom, so you recommend creating ClaimsAuthorizationAttribute as you have done already in the Identity model using something similar to this attribute?

      Reply
      • Dominick Baier says

        April 2, 2015 at 8:31 am

        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.

        Reply
        • Taiseer Joudeh says

          April 3, 2015 at 7:20 pm

          Thank you Dom for the advice, I agree with you. Will work on the post and update it soon.

          Reply
          • tofutim says

            May 15, 2015 at 1:12 am

            Taiseer, did you ever make any modifications per Dominick’s suggestions?

          • Taiseer Joudeh says

            May 15, 2015 at 11:50 pm

            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.

        • tofutim says

          May 15, 2015 at 1:12 am

          What is DI?

          Reply
        • ☆彡 Bilal™ (@akaMBS) says

          June 8, 2015 at 2:41 pm

          @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?

          Reply
  3. Владимир Землянушкин says

    March 31, 2015 at 10:04 am

    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?

    Reply
  4. Simon says

    March 31, 2015 at 7:31 pm

    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).”

    Reply
    • Taiseer Joudeh says

      April 2, 2015 at 9:32 am

      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.

      Reply
  5. James says

    April 1, 2015 at 12:26 pm

    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

    Reply
    • Taiseer Joudeh says

      April 2, 2015 at 11:06 am

      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.

      Reply
      • sid9992015James says

        April 2, 2015 at 10:45 pm

        That’s great to know. Really looking forward to the final part. Many thanks for such a useful and interesting series.

        Reply
  6. John Atten (@xivSolutions) says

    April 1, 2015 at 2:26 pm

    Always a most valuable resource – You’re on a tear here Taiseer! 🙂

    Reply
    • Taiseer Joudeh says

      April 2, 2015 at 11:08 am

      Thanks John for your comment, but I guess I need to update this post based on Dominick feedback 🙂

      Reply
  7. Nail Tabeyev says

    April 2, 2015 at 12:27 am

    You’re Rock!
    I look forward to continuing

    Reply
    • Taiseer Joudeh says

      April 2, 2015 at 12:29 am

      Glad you like it, thanks for your comment 🙂

      Reply
  8. Marco says

    April 6, 2015 at 4:53 pm

    could you briefly explain how you would take your series and extend it for mulitple applications and single sign on?

    thank you!

    Reply
    • Kevin Grigsby (@kevingrigsby) says

      April 6, 2015 at 8:52 pm

      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.

      Reply
    • Akinsanya Olanrewaju says

      April 7, 2015 at 11:53 am

      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.

      Reply
  9. Brent says

    April 7, 2015 at 12:29 am

    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.

    Reply
    • Taiseer Joudeh says

      April 7, 2015 at 11:40 pm

      Thanks for your comment, most probably next Tuesday, will do my best to finish it!

      Reply
  10. Tony says

    April 7, 2015 at 6:46 pm

    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…

    Reply
    • Taiseer Joudeh says

      April 7, 2015 at 11:37 pm

      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 🙂

      Reply
      • rolando lázcares valenciano says

        April 8, 2015 at 7:21 pm

        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.

        Reply
        • Taiseer Joudeh says

          April 11, 2015 at 1:21 am

          You are welcome Rolando, happy to hear that I have readers from Costa Rica 🙂 will do my best to post it this Tuesday.

          Reply
          • Srini says

            April 24, 2015 at 7:19 am

            I’m eagerly waiting for the Part 6. Your posts are great! Taiseer

  11. nbl says

    April 13, 2015 at 7:28 pm

    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.

    Reply
    • nbl says

      April 13, 2015 at 7:31 pm

      looks like web.config content in my comment above was removed by this forum application 🙂

      Reply
  12. Jason Krause says

    April 14, 2015 at 1:08 am

    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

    Reply
    • Taiseer Joudeh says

      April 14, 2015 at 2:29 pm

      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?

      Reply
      • Jason Krause says

        April 15, 2015 at 7:22 am

        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

        Reply
  13. Nail says

    April 16, 2015 at 11:13 am

    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

    Reply
    • Taiseer Joudeh says

      April 18, 2015 at 2:19 am

      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.

      Reply
  14. Akinsanya Olanrewaju says

    April 19, 2015 at 8:59 am

    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.

    Reply
  15. Hanna says

    April 21, 2015 at 11:48 am

    Hi Taiseer,
    I was just wondering when the last part will be posted?

    Thanks.

    Reply
    • Kevin Grigsby says

      April 21, 2015 at 8:15 pm

      Looking forward to this last post as well.

      Reply
  16. Bruno says

    April 22, 2015 at 5:05 pm

    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

    Reply
  17. nadarajan.rajappen says

    April 23, 2015 at 1:59 pm

    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

    Reply
  18. Bruno says

    April 23, 2015 at 3:46 pm

    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

    Reply
    • Taiseer Joudeh says

      April 24, 2015 at 12:08 am

      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.

      Reply
      • Bruno says

        April 24, 2015 at 10:48 am

        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.

        Reply
        • Bruno says

          May 4, 2015 at 11:56 am

          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!

          Reply
  19. Dillorscroft (@dillorscroft) says

    April 28, 2015 at 6:01 pm

    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.

    Reply
    • Taiseer Joudeh says

      April 29, 2015 at 6:32 pm

      I do not see any difference between Groups and Roles here, why you can’t consider Group A as Role A?

      Reply
  20. Cordney Ervin says

    April 29, 2015 at 8:10 pm

    Thanks for doing this series, its been a huge help for me. Any idea when the last post will be available?

    Reply
  21. Tamer says

    April 29, 2015 at 10:53 pm

    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

    Reply
  22. Luyolo Mgodi says

    April 30, 2015 at 4:07 pm

    Great article. Saved me some time.
    Do you perhaps have examples on how to implement Claims Based Auth using Owin and Active Directory ?

    Reply
  23. Alectra says

    May 1, 2015 at 2:13 am

    Hey, it’s a great series, when do you think the last part will be up?

    Reply
    • Taiseer Joudeh says

      May 1, 2015 at 3:12 pm

      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.

      Reply
      • Brent says

        May 1, 2015 at 11:08 pm

        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.

        Reply
      • Alectra says

        May 1, 2015 at 11:50 pm

        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. 🙂

        Reply
  24. Amilton Costa says

    May 4, 2015 at 10:22 pm

    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

    Reply
  25. Christian says

    May 5, 2015 at 9:44 pm

    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 🙂

    Reply
    • Taiseer Joudeh says

      May 9, 2015 at 12:47 am

      You are welcome Christian, glad to here that posts are useful. Hopefully the last part will come soon.

      Reply
  26. Domenico “Pippo” Pirozzi says

    May 7, 2015 at 10:22 pm

    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?

    Reply
    • Taiseer Joudeh says

      May 9, 2015 at 12:38 am

      Hi, yes sure you can use it as a starting point.

      Reply
  27. Prashant RautPRR says

    May 12, 2015 at 3:58 pm

    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

    Reply
    • Taiseer Joudeh says

      May 16, 2015 at 12:00 am

      Hello Prashant, FB and Google authentication are covered in previous posts, you can check the archive.

      Reply
  28. ِDamon says

    May 21, 2015 at 2:22 am

    Hi Taiseer,
    Thanks for the great posts . Any plan to publish the last article?

    Reply
  29. Hamed says

    May 24, 2015 at 8:57 am

    Hi
    great article. Thanks a lot
    can I ask you when you will publish the Sixth post?

    Reply
  30. Kurai says

    June 1, 2015 at 2:20 pm

    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

    Reply
    • Taiseer Joudeh says

      June 3, 2015 at 2:11 am

      Do not be #sorry. I blog when ever I want 🙂

      Reply
  31. Kevin Grigsby says

    June 3, 2015 at 9:56 pm

    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.

    Reply
    • Taiseer Joudeh says

      June 8, 2015 at 12:30 am

      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!

      Reply
  32. jaredmahan says

    June 4, 2015 at 8:55 pm

    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.

    Reply
    • Taiseer Joudeh says

      June 5, 2015 at 1:45 am

      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.

      Reply
  33. Hugo says

    June 5, 2015 at 6:53 pm

    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. 🙂

    Reply
    • Taiseer Joudeh says

      June 8, 2015 at 12:22 am

      You need to configure EF correctly, check my old post which might help.

      Reply
  34. zefiros1821 says

    June 10, 2015 at 7:29 pm

    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

    Reply
    • zefiros1821 says

      June 11, 2015 at 5:59 pm

      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

      Reply
      • Taiseer Joudeh says

        June 13, 2015 at 2:37 am

        Hi, It should be application/json not application/jason

        Reply
        • zefiros1821 says

          June 15, 2015 at 9:09 am

          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

          Reply
    • Taiseer Joudeh says

      June 13, 2015 at 2:43 am

      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.

      Reply
  35. Tomas says

    June 10, 2015 at 9:20 pm

    Any Idea when the post 6 will be?

    Reply
  36. Tomas says

    June 11, 2015 at 5:52 pm

    Hi great articles!!!

    Im waiting the last one, can i used in own project? Any idea when post 6 comes?

    Reply
    • Taiseer Joudeh says

      June 13, 2015 at 2:37 am

      Thanks for you comment Tomas, feel free to use it in your project.

      Reply
      • Tomas says

        June 17, 2015 at 2:50 pm

        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?

        Reply
        • Taiseer Joudeh says

          June 18, 2015 at 2:08 am

          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.

          Reply
  37. Sunny says

    June 20, 2015 at 1:02 am

    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 🙂

    Reply
  38. nelly says

    June 23, 2015 at 12:09 pm

    Hi,

    Just wondering while the last part “6” of this article its taking tooo long time; to come up.

    Nelly

    Reply
  39. kevin shen says

    June 26, 2015 at 10:05 am

    HI,
    It‘a wonderful post.
    I learn a lot from it

    Reply
  40. therenhoxhsiow says

    June 30, 2015 at 1:17 pm

    Hi, thank you for all the articles in the series so far. Just wondering when will the part “6” come up?

    Reply
  41. zefiros1821 says

    June 30, 2015 at 3:10 pm

    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;

    Reply
  42. lamlantomatoes says

    July 10, 2015 at 7:02 pm

    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!

    Reply
    • Taiseer Joudeh says

      July 11, 2015 at 2:38 am

      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.

      Reply
  43. Daniel van Niekerk says

    July 14, 2015 at 11:39 pm

    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.

    Reply
    • Taiseer Joudeh says

      July 15, 2015 at 12:49 am

      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.

      Reply
  44. madas says

    July 15, 2015 at 10:56 am

    Hi Taiseer,

    great work so far and thx for sharing.
    Is there any info when we can expect the final part 6?

    Regards.

    madas

    Reply
  45. Mike Sullivan says

    July 19, 2015 at 8:15 am

    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

    Reply
    • Taiseer Joudeh says

      July 21, 2015 at 10:18 am

      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.

      Reply
  46. Austen DeWolf says

    July 19, 2015 at 12:36 pm

    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

    Reply
    • Taiseer Joudeh says

      July 21, 2015 at 10:15 am

      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 🙂

      Reply
      • Martin (@piehouserat) says

        July 25, 2015 at 5:05 am

        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

        Reply
        • Taiseer Joudeh says

          July 27, 2015 at 4:26 am

          Thanks Martin, will do my best to finish those soon. I’m at London now, and I fall in love with this beautiful city 🙂

          Reply
        • vnik says

          August 5, 2015 at 5:55 pm

          Me too 🙂
          Hope can read it tomorrow 😀
          Thanks Taiseer!

          Reply
  47. Paul says

    July 22, 2015 at 6:39 pm

    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)’.
    Security accessibility of the overriding method must match the security accessibility of the method being overriden.
    at Microsoft.AspNet.Identity.UserManager`2.FindAsync(String userName, String password) at CustomOAuthProvider.d__4.MoveNext() in CustomOAuthProvider.cs:line 31

    Reply
  48. Oleksandr says

    August 4, 2015 at 11:44 pm

    Hi! Sorry for off-topic, but what theme do you use for code samples?I like it very much 🙂

    Reply
  49. eappell says

    August 14, 2015 at 6:15 pm

    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!

    Reply
    • Taiseer Joudeh says

      August 15, 2015 at 1:04 am

      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!

      Reply
  50. entilzha says

    August 16, 2015 at 6:06 pm

    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

    Reply
    • entilzha says

      August 22, 2015 at 12:35 am

      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.

      Reply
      • entilzha says

        August 22, 2015 at 12:36 am

        I forgot to thank Taiseer for sharing such great blogs with the rest of us! Thanks Taiseer!

        Reply
        • Taiseer Joudeh says

          August 24, 2015 at 11:00 pm

          You are most welcome, happy to know that posts were useful 🙂

          Reply
  51. dynamicarray says

    August 18, 2015 at 7:57 pm

    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!

    Reply
    • Taiseer Joudeh says

      August 18, 2015 at 11:22 pm

      Thanks for your comment, to be honest not yet, hopefully I will be able to publish it soon.

      Reply
  52. Jamie says

    August 19, 2015 at 3:26 pm

    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.

    Reply
    • Taiseer Joudeh says

      August 24, 2015 at 11:49 pm

      Thanks Jamie, happy to help 🙂

      Reply
  53. Khuzema says

    August 27, 2015 at 1:39 pm

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

    Reply
  54. Arjun Krishna says

    August 27, 2015 at 10:24 pm

    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.

    Reply
  55. Khuzema says

    August 30, 2015 at 11:30 pm

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

    Reply
    • Taiseer Joudeh says

      September 7, 2015 at 6:49 am

      🙂 Hopefully I will be able to publish it, thanks for you message Khuzema 🙂

      Reply
  56. serkanunal says

    September 1, 2015 at 11:19 pm

    we are waiting last post about angularjs 🙂

    Reply
    • Taiseer Joudeh says

      September 5, 2015 at 10:22 pm

      Will do my best to finish it, thanks 🙂

      Reply
  57. Tonchi says

    September 4, 2015 at 2:10 pm

    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

    Reply
    • Taiseer Joudeh says

      September 7, 2015 at 6:44 am

      Hi Tonchi,
      Currently i do not have, but you can check my other post which might help

      Reply
      • Tonchi says

        September 9, 2015 at 6:51 pm

        Ok thanks. Its like the merge of both post includes all functionalities.

        Reply
  58. Paul Wade says

    September 4, 2015 at 4:11 pm

    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

    Reply
  59. Vivian says

    September 6, 2015 at 3:52 am

    Looking forward to part 6!!

    Reply
  60. 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?? 😀

    Reply
  61. 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?

    Reply
    • Taiseer Joudeh says

      September 10, 2015 at 12:11 pm

      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.

      Reply
  62. FabioG says

    September 9, 2015 at 5:52 pm

    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!

    Reply
    • Taiseer Joudeh says

      September 10, 2015 at 12:10 pm

      You are welcome, glad to help 🙂

      Reply
  63. Tim says

    September 11, 2015 at 4:56 am

    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.

    Reply
    • Taiseer Joudeh says

      September 18, 2015 at 2:59 pm

      If you need full identity server, then my recommendation is to take a look at Think Tecture Identity Server.

      Reply
  64. Shyamal Parikh (@Shyamal890) says

    September 12, 2015 at 10:01 am

    Eagerly awaiting the last part of the series.

    Reply
  65. Houdini Sutherland says

    September 14, 2015 at 12:03 am

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

    Reply
  66. krishh86 says

    September 17, 2015 at 5:25 am

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

    Reply
    • Taiseer Joudeh says

      September 18, 2015 at 2:39 pm

      You are welcome, thanks for your message.

      Reply
  67. 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!

    Reply
  68. Lucas Freitas says

    September 24, 2015 at 11:04 pm

    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 ?

    Reply
    • Taiseer Joudeh says

      October 3, 2015 at 6:06 pm

      Hi Lucas,
      What do you mean by using Roles to mange domains? Can you elaborate more please?

      Reply
  69. Roland says

    September 25, 2015 at 5:54 pm

    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

    Reply
    • Taiseer Joudeh says

      October 3, 2015 at 6:03 pm

      Thanks Roland for your message, glad to hear it was useful 🙂

      Reply
  70. krish says

    September 28, 2015 at 8:55 am

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

    Reply
  71. Alexander says

    September 28, 2015 at 2:10 pm

    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”

    Reply
  72. FabioG says

    October 2, 2015 at 4:21 pm

    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?

    Reply
    • FabioG says

      October 2, 2015 at 7:24 pm

      Nevermind, did it

      Reply
  73. Chris Moutray says

    October 6, 2015 at 4:07 pm

    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

    Reply
    • Taiseer Joudeh says

      October 12, 2015 at 10:57 am

      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?

      Reply
      • Chris Moutray says

        October 14, 2015 at 12:52 am

        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.

        Reply
      • Chris Moutray says

        October 15, 2015 at 11:57 am

        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.

        Reply
        • Taiseer Joudeh says

          October 21, 2015 at 11:59 am

          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.

          Reply
          • Chris Moutray says

            October 23, 2015 at 8:07 am

            That’s great – it’s the reassurance I needed – Thanks

  74. CNCM (@tantanix) says

    October 8, 2015 at 8:33 am

    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.

    Reply
  75. Reka says

    October 8, 2015 at 7:10 pm

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

    Reply
    • Taiseer Joudeh says

      October 12, 2015 at 10:25 am

      You are welcome Reka, Thanks for your message

      Reply
  76. Tonchi says

    October 10, 2015 at 12:39 am

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

    Thanks.

    Reply
  77. Reno Natallino says

    October 12, 2015 at 9:25 pm

    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,

    Reply
    • Taiseer Joudeh says

      October 21, 2015 at 10:55 am

      Hi Reno, this is dedicated post about this, hope it will help

      Reply
  78. Alexandr says

    October 13, 2015 at 9:18 am

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

    Reply
  79. Rodrigo says

    October 16, 2015 at 4:42 pm

    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

    Reply
  80. 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

    Reply
    • Taiseer Joudeh says

      October 21, 2015 at 11:15 am

      Thanks Fredrik for your message, happy to help 🙂

      Reply
  81. Pras says

    October 21, 2015 at 12:07 pm

    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

    Reply
  82. 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

    Reply
  83. Suresh says

    October 27, 2015 at 12:26 am

    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.

    Reply
    • Taiseer Joudeh says

      October 31, 2015 at 2:46 am

      You can publish it directly to Azure Web Apps, I do not know what you mean by “parameters”?

      Reply
  84. Marcin says

    October 30, 2015 at 5:42 pm

    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

    Reply
  85. Paul says

    November 4, 2015 at 5:33 pm

    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.

    Reply
    • Taiseer Joudeh says

      November 6, 2015 at 3:46 am

      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.

      Reply
      • Paul Wade says

        November 6, 2015 at 2:22 pm

        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

        Reply
        • Taiseer Joudeh says

          November 11, 2015 at 7:01 pm

          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.

          Reply
  86. 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?

    Reply
    • Taiseer Joudeh says

      November 6, 2015 at 3:44 am

      You are welcome, I will do my best to complete it soon

      Reply
  87. malick says

    November 5, 2015 at 1:43 am

    Thank you so much !

    Reply
    • Taiseer Joudeh says

      November 6, 2015 at 3:40 am

      You are most welcome:)

      Reply
  88. ycaraballo says

    November 5, 2015 at 10:28 pm

    Very helpful!!
    No part 6 yet?

    Reply
    • Taiseer Joudeh says

      November 6, 2015 at 3:37 am

      Not yet 🙁

      Reply
  89. Gayan says

    November 6, 2015 at 7:59 am

    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.

    Reply
    • Taiseer Joudeh says

      November 11, 2015 at 7:05 pm

      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 🙂

      Reply
  90. sunando94 says

    November 10, 2015 at 4:10 pm

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

    Reply
    • Taiseer Joudeh says

      November 11, 2015 at 6:46 pm

      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.

      Reply
  91. Paul Wade says

    November 13, 2015 at 2:28 am

    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

    Reply
    • Paul Wade says

      November 16, 2015 at 2:28 am

      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

      Reply
      • Taiseer Joudeh says

        November 16, 2015 at 7:23 pm

        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?

        Reply
        • Paul Wade says

          November 16, 2015 at 8:53 pm

          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

          Reply
        • Paul Wade says

          November 16, 2015 at 9:45 pm

          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.

          Reply
          • amit bashan says

            November 18, 2015 at 11:36 am

            Can you share your updated code ?

  92. Steve says

    November 24, 2015 at 11:48 am

    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.

    Reply
  93. Christopher McCrum says

    November 28, 2015 at 7:14 am

    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.

    Reply
    • Taiseer Joudeh says

      December 2, 2015 at 12:21 pm

      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.

      Reply
  94. entilzha says

    December 2, 2015 at 11:25 pm

    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

    Reply
    • entilzha says

      December 2, 2015 at 11:44 pm

      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.

      Reply
    • entilzha says

      December 8, 2015 at 5:21 pm

      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.

      Reply
      • Taiseer Joudeh says

        December 9, 2015 at 11:18 am

        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.

        Reply
        • entilzha says

          December 9, 2015 at 4:59 pm

          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!

          Reply
    • entilzha says

      December 10, 2015 at 11:24 pm

      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

      Reply
      • entilzha says

        December 10, 2015 at 11:36 pm

        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”

        Reply
        • Tonchi says

          December 10, 2015 at 11:42 pm

          Can you share example code?

          Reply
          • entilzha says

            December 11, 2015 at 12:02 am

            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?

          • Taiseer Joudeh says

            December 11, 2015 at 9:24 pm

            I would like to thank you for helping other readers and posting a detailed comments about your findings and solutions, appreciate it entilzha 🙂

        • Chris Moutray says

          December 11, 2015 at 7:03 pm

          perhaps you could share by committing the seperared library to a github repo and with barebones resource server…

          Reply
          • entilzha says

            December 14, 2015 at 11:48 pm

            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

          • Chris Moutray says

            December 15, 2015 at 12:10 pm

            I tracked down your repo – thanks for sharing
            https://github.com/kendodragon/ReusableOAuthLibrary

  95. Khuzema says

    December 3, 2015 at 6:08 pm

    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

    Reply
    • Taiseer Joudeh says

      December 9, 2015 at 11:35 am

      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

      Reply
  96. Khuzema says

    December 6, 2015 at 3:39 pm

    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

    Reply
    • Taiseer Joudeh says

      December 9, 2015 at 11:30 am

      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.

      Reply
  97. dotnetshadow says

    December 7, 2015 at 9:09 am

    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

    Reply
    • Taiseer Joudeh says

      December 7, 2015 at 11:14 am

      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.

      Reply
      • dotnetshadow says

        December 7, 2015 at 1:42 pm

        Thanks for your immediate response..:)

        Reply
  98. Yann says

    December 7, 2015 at 6:59 pm

    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

    Reply
    • Taiseer Joudeh says

      December 9, 2015 at 11:28 am

      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 🙂

      Reply
  99. Richard Butler says

    December 14, 2015 at 4:33 pm

    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

    Reply
  100. David Canche says

    December 16, 2015 at 9:35 am

    Cuando Estara la parte 6?

    Reply
Newer Comments »

Leave a Reply Cancel reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.

About Taiseer

Husband, Father, Consultant @ MSFT, Life Time Learner... Read More…

Buy me a coffeeBuy me a coffee

Recent Posts

  • Integrate Azure AD B2C with ASP.NET MVC Web App – Part 3
  • Secure ASP.NET Web API 2 using Azure AD B2C – Part 2
  • Azure Active Directory B2C Overview and Policies Management – Part 1
  • ASP.NET Web API Claims Authorization with ASP.NET Identity 2.1 – Part 5
  • ASP.NET Identity 2.1 Roles Based Authorization with ASP.NET Web API – Part 4

Blog Archives

Recent Posts

  • Integrate Azure AD B2C with ASP.NET MVC Web App – Part 3
  • Secure ASP.NET Web API 2 using Azure AD B2C – Part 2
  • Azure Active Directory B2C Overview and Policies Management – Part 1
  • ASP.NET Web API Claims Authorization with ASP.NET Identity 2.1 – Part 5
  • ASP.NET Identity 2.1 Roles Based Authorization with ASP.NET Web API – Part 4

Tags

AJAX AngularJS API API Versioning ASP.NET Authentication Autherization Server Azure Active Directory B2C Azure AD B2C basic authentication C# CacheCow Client Side Templating Code First Dependency Injection Entity Framework ETag Foursquare API HTTP Caching HTTP Verbs IMDB API IoC Javascript jQuery JSON JSON Web Tokens JWT Model Factory Ninject OAuth OData Pagination Resources Association Resource Server REST RESTful Single Page Applications SPA Token Authentication Tutorial Web API Web API 2 Web API Security Web Service wordpress.com

Search

Copyright © 2021 · eleven40 Pro Theme on Genesis Framework · WordPress · Log in

loading Cancel
Post was not sent - check your email addresses!
Email check failed, please try again
Sorry, your blog cannot share posts by email.