Search code examples
asp.net-web-apiauthorizationjwtowin-middleware

How are users authenticated and retrieved?


Having worked my way through this tutorial:

http://bitoftech.net/2015/02/16/implement-oauth-json-web-tokens-authentication-in-asp-net-web-api-and-identity-2/

I now have the solution standing upright and I can issue JWT tokens (what I think of as 'login') and authenticate requests by passing in those tokens during subsequent calls.

What I'm not clear on is how the [Authorize] attribute is:

  1. Recognising a user as authenticated
  2. Retrieving a user from the database
  3. Making that user available to my code
  4. How I would add to the authentication process if I wanted to (perhaps including extra authentication logic after the exiting logic)

[EDIT] I understand that JWT tokens are being used to identify the user but I don't understand 'how' this is taking place. I also understand the middleware is doing it, but the workings of this are not clear.


Solution

    1. with the [Authorize] attribute an AuthorizationFilter will added to the filter chain before the controller is called. This article illustrates that. With the call to ConfigureOAuthTokenConsumption (Step 6 in the tutorial) you give the middleware the information it needs to validate and process tokens.

    2. the authentication, i.e. check username and password, happens only before the token is issued in

      public override async Task 
      GrantResourceOwnerCredentials(OAuthGrantResourceOwnerCredentialsContext context) {
      ...
          ApplicationUser user = await userManager.FindAsync(context.UserName, context.Password);
      ...
      }
      

      the AuthorizationFilter will only see the token and rely on the information in the token itself

    3. this blog post gives you an example how you can access the username:

      var currentPrincipal = ClaimsPrincipal.Current;
      string userName = "Anonymous";
      if (currentPrincipal.Identity.IsAuthenticated)
      {
          userName = currentPrincipal.Identity.Name;
      }
      

      the middleware gets the information from the token

    4. you can add you own logic either before the token is issued in GrantResourceOwnerCredentials or add your own AuthorizationFilter if you need additonal logic when you receive the token. The blog post linked under 3. shows an example for that.