Token Based Authentication using Core Web Api

Using  Token Based Authentication, clients are not dependent on a specific authentication mechanism. A token is generated by the server  if the user is authenticated and send it back to the user.

So to acces  a specific ressource, the client must include the generated token in the header of subsequent requests and the Web API Server have some APIs to understand, validate the token and perform the autorization

This approach provides Loose Coupling between client and the Web API.

In my previous tutorial   Angular JS Token-based Authentication using Identity and web API   I have build an  authentication server using an oAuth Bearer Token.

In this tutorial, I will use JSON Web Token (JWT) , for more information about JWT please take a look at

JWT enable us to securely transfer data between server and client .

A JWT Token is composed of 3 parts base64 encoded separated by a dot(.) : a header, a payload and a signature :  header.payload.signature

  • Header : contains a Typ (should be JWT) and  a Hashing algorithm HS256, RS512, ES356, etc…

  • Payload  contains the information witch we need to transfer to client such as Claims  related to the token

  • Signature    A Hash of Header and Payload using a secret Key


JWT therefore allows to exchange content for an authenticated user due to the secret key used in the signature. The signature also ensures the integrity of the content.

Even if every one can  holds the token, he cannot tempored the payload due to the signature with the Secret Key.

SSL helps prevent against to MitM  (man-in-the-middle) attacks.


Securing our web application consists of two scenarios  Authentication and Authorisation

  1. Authentication identifies the user. so the user must be registered before, using login and password or third party logins like Facebook, Twitter,
  2. Authorisation  talks about  Permission for authenticated users
    – what is the user (authenticated) allowed to do ?
    – What ressources can the user access ?

I’m going to  build a Token-based Authentication  Server using ASP.Net Core Identity , ASP.Net Core Web API and Entity Framework Core

So lets create a new ASP.NET Core Web Application Project




install this packages

install-package Microsoft.AspNetCore.Identity

install-package Microsoft.AspNetCore.Identity.EntityFrameworkCore

install-package Microsoft.EntityFrameworkCore.SqlServer

install-package Microsoft.EntityFrameworkCore.Tools

Setup Indentity database

Create a User model that inherits from IdentityUser and extend it with additional properties such as JoinDate, JobTitle and Contract.


Create a Role model that inherits from IdentityRole and extend it with additional properties such as Role Description


Create an IndentityContext that inherits from IdentityDbContext<MyUser>


Create an AppSettings.json file and add a ConnectionString:  SecurityConnection


Open StartUp.cs class , locate  ConfigureServices method :  ConfigureServices(IServiceCollection services)  and add the following to configure our SecurityContext to point to SecurityConnection witch point to sql database configured in AppSettings.json file

Configure Asp.Net Core Indentity to use our custom user and role ( MyUser and MyRole)


Locate Configure method and add  app.UseIdentity  in middleware


Open Package Manager Console.

Initialise migration  :    add-migration init

Upadate or Create the Database  : update-database

The generated database looks like this


Register User


  Test Register user

I use a google extensions Postman to test api




Get Ressources

Here , I log the user , if the user is authenticated with its credentials (email and password), I get the user claims , add additionnal claims related to JWT, Create Security Token and return it


Locate Configure method and app.UseJwtBearerAuthentication  in middleware  to validate the token


The protected ressource  look like this


Test API With Postman

get token   (localhost:58834/api/auth/token)


Send Query to get ressource by including valid token in the header (localhost:58834/api/values)


Send Query to get ressource by including invalid token in the header (localhost:58834/api/values)


The entire scenario

Code source is available on my Github repository (

Best regards


I'm a microsoft most valuable professional (MVP) .NET Architect and Technical Expert skills located in Paris (FRANCE). The purpose of this blog is mainly to post general .NET tips and tricks, Gora LEYE

  • Pingback: Asp.Net Web Api Core Integration testing using InMemory EntityFrameworkCore Sqlite or LocalDB and XUnit2 |

  • Pingback: Angular2 Token Based Authentication using Core Web API and JSON Web Token |

  • Carlos Andres Sanchez Garcia

    How can I create a role based on this code sample, since the entity MyRole is not included in the model for the context?

    • LogCorner

      you do this :
      var userClaims = await _userManager.GetClaimsAsync(user); returns the role if the user has a role stored on tables userclaims.

      you can also add it ilke :
      var claims = new[]
      new Claim(ClaimTypes.Role, “admin”),
      new Claim(JwtRegisteredClaimNames.Sub, user.UserName),
      new Claim(JwtRegisteredClaimNames.Jti, Guid.NewGuid().ToString()),
      new Claim(JwtRegisteredClaimNames.Email, user.Email)

      if you want to manage roles from roles tables you can use :
      var user = await _userManager.FindByNameAsync(model.Email);
      var roles = _userManager.GetRolesAsync(user);
      var isInRole = _userManager.IsInRoleAsync(user, “admin”);

      • Carlos Andres Sanchez Garcia

        I found you must replace the following line in order to include the role in the context, please let me know if I’m wrong:

        public class SecurityContext : IdentityDbContext

        • Not mandatory
          in startup.cs file we found a line that include the role :
          services.AddIdentity(cfg =>

          MyUser also inherits from IdentityUser witch inherits from IdentityUser<TKey, IdentityUserClaim, IdentityUserRole, IdentityUserLogin>

          so we can access role and claims from IdentityUser

          in AuthController, we have also a property :
          private readonly RoleManager _roleManager;
          so we can also manager role like this :
          var role = _roleManager.RoleExistsAsync(“admin”);

  • Mansur Haider

    Thanks Gora, for sharing excellent article.

  • itemplate

    Nice article, however when I try the code from GitHub, I hit an exception when executing the “api/auth/token”. It is line 81 “var userClaims = await _userManager.GetClaimsAsync(user);” and the exception is:

    The type initializer for ‘Microsoft.EntityFrameworkCore.Query.ExpressionTranslators.Internal.SqlServerStringReplaceTranslator’ threw an exception.

    Sequence contains more than one matching element

    There are no apparent duplicate Id’s or anything.
    Quite new to EF so it might be obvious – do you know why?


    • Hi , I cannot reproduce your error. this is related to EF. So I suggest you to see logs
      Open launchSettings.json and comment IIS related informations like this :
      //”iisSettings”: {
      // “windowsAuthentication”: false,
      // “anonymousAuthentication”: true,
      // “iisExpress”: {
      // “applicationUrl”: “http://localhost:58834/”,
      // “sslPort”: 0
      // }
      “profiles”: {
      //”IIS Express”: {
      // “commandName”: “IISExpress”,
      // “launchBrowser”: true,
      // “launchUrl”: “api/values”,
      // “environmentVariables”: {
      // “ASPNETCORE_ENVIRONMENT”: “Development”
      // }
      “TokenAuthWebApiCore.Server”: {
      “commandName”: “Project”,
      “launchBrowser”: true,
      “launchUrl”: “api/values”,
      “environmentVariables”: {
      “ASPNETCORE_ENVIRONMENT”: “Development”
      “applicationUrl”: “http://localhost:58834”

      output looks like

      SELECT TOP(1) [u].[Id], [u].[AccessFailedCount], [u].[ConcurrencyStamp], [u].[Contract], [u].[Email], [u].[EmailConfirmed], [u].[JobTitle], [u].[JoinDate], [u].[LockoutEnabled], [u].[LockoutEnd], [u].[NormalizedEmail], [u].[NormalizedUserName], [u].[PasswordHash], [u].[PhoneNumber], [u].[PhoneNumberConfirmed], [u].[SecurityStamp], [u].[TwoFactorEnabled], [u].[UserName]
      FROM [AspNetUsers] AS [u]
      WHERE [u].[NormalizedUserName] = @__normalizedUserName_0
      info: Microsoft.EntityFrameworkCore.Storage.IRelationalCommandBuilderFactory[1]
      Executed DbCommand (7ms) [Parameters=[@__user_Id_0=’?’ (Size = 450)], CommandType=’Text’, CommandTimeout=’30’]
      SELECT [uc].[Id], [uc].[ClaimType], [uc].[ClaimValue], [uc].[UserId]
      FROM [AspNetUserClaims] AS [uc]
      WHERE [uc].[UserId] = @__user_Id_0
      info: Microsoft.AspNetCore.Mvc.Internal.ObjectResultExecutor[1]
      Executing ObjectResult, writing value Microsoft.AspNetCore.Mvc.ControllerContext.
      info: Microsoft.AspNetCore.Mvc.Internal.ControllerActionInvoker[2]
      Executed action TokenAuthWebApiCore.Server.Controllers.Web.AuthController.CreateToken (TokenAuthWebApiCore.Server) in 5463.9294ms
      info: Microsoft.AspNetCore.Hosting.Internal.WebHost[2]
      Request finished in 6036.3007ms 200 application/json; charset=utf-8

  • sejong shon

    Nice post. Any plant to implement api access based on a role using Identity? Ex: Admin or User. I think I can share this github repo if interested:

  • Chathuranganie Pathirage

    I tried to follow your example to implement authentication on my ASP.NET Core Web API using identity. My problem is that database connection doesn’t get created. at Login, when I inspect the _userManager, the database connection is not set to my database. Note that I’m doing this against an existing database which has all the identity tables already created. The error i get is ‘Login failed for ‘ I get this when I try to run your sample as well. I’m trying to connect to my DB using the sa account

    • Hi, I think you have an authorization problem, you can verify your database security.

  • dsalkanovic

    how do you protect from XSRF ?

  • Bob Yuan

    I just follow the blog to generate a token, which has been verified through, it is valid. But when I use Postman to test it as shown here, I still got 401 error. What did I do wrong>

    • Hi bob, if you include the token on the header in must work :
      key = Authorization
      value = bearer your_token_here
      Let me know if it is not resolved

      • Bob Yuan

        Hi Gora, That was exactly what I did. it still returns 401. Thanks.

        • Hi, see my answer to @Azom Valentine , I tried it and it work fine
          Best regards

      • Joel

        Same Issue with me, I don’t know if it’s supposed to create a token in the database but if that’s the case it doesn’t.

        • Hi, see my answer to @azomvalentine:disqus , I tried it and it work fine
          Best regards

  • Zhiwei Yan


  • Azom Valentine

    Hi Gora,

    Thanks for the nice article. I can generate token but when i request for resources using the token obtained i still get 401 unauthorized.

    Key value
    Authorization bearer {token}

    in the headers of my Get request. Also using web api core 2.0.

    • Hi, have you a database on your computer ? locate appSettings (
      Then update the connectionString if necessary. you must first create a user before getting token back

      localhost:58834/api/auth/Register :
      request body
      “Password” :”WebApiCore1#”,

      http://localhost:58834/api/auth/token :
      request body
      “Password” :”WebApiCore1#”

      request header :
      key = Authorization , value = bearer your_token_here

      I pull the code here
      And I tried and it works fine

  • Евгений Домнич

    Hi! Thank you for tutorial. Can you explain me, how make refresh token?