Microsoft > .Net Core >> Ocelot API Gateway Views : 4267
JWT Token Auth
Rate This Article :

Custom Jwt Token authentication


AIM:

To create a micro service based application with JWT token authentication, where the authentication is handled by gateway api and with some custom tweaks in handling token below are the details covered.

  •  Handle token validation within ocelot gateway
  •  Extend token expiry time on each request from user
  • Invalidate the current token when new token is issued for same user
  • Throw custom error for invalid token instead of default 401 error

Micro-services List

1.       ocelot gateway

2.      Authentication api to handle authentication requests, generate and save token details

3.      User api to register new user and for validating user

4.      Data serving Api which will be allowed for authenticated users alone

 

High level steps to handle Authentication in Ocelot gateway

  •    Token generation and saving the details in authentication api
  •   Configure ocelot.json with AuthenticationOptions
  •   Add the JWT validation code to startup.cs
  •   Add custom middleware code in PreAuthenticationMiddleware and PreQueryStringBuilderMiddleware

 

Detailed steps

 

For complete code download the sample code

 

1.      Token Generation and save the data

In this section we will see the details of how JWT token is generated and saved to database.

Auth service api is a .net core web application with web api template. We have a controller to handle the authentication requests.

For the User login method, we send the login model which has username and password, which validates a user exists in DB and matches the password and calls a method to generate JWT token




AuthenticateUser

 

The first step it fetches the user information from userapi from a http call, then after validating the user details GetTokenInfo method is called to generate token. Then the details are updated to token information object and saved to table



SaveTokenInfo

In this method we check if the user exists in token table and the validity time is set 10 minutes from now and then saved to DB




GenerateKey

 

In this method we generate the JWT token with a secret key and we set the validity to 12 hours,as we are going to set the validity based on our requirement, here its 10 minutes. But the token will be invalid post 12 hours even though we extend from code post that.



Table Details


2.      Create gateway project in the solution

Add a new core web application with web api template





3.      Install Ocelot

Install ocelot from NuGet package manager, version to be used - 14.1.3



4.      Create and configure Ocelot.JSon

Add a json file to the project and name it as ocelot.json and configure the downstream and upstream routes in the json file . The content starts with ReRoutes




Specify AuthenticationOptions for the routes requiring authentication



5.      Add Configuration values

 

Add the JWT & Other api URLs to appsettings.json


 

6.      Configuring JWT validation

 In the startup.cs file we will write the JWT validation code to validate the token. This section is to check if we are sending a valid JWT token.

 Inside ConfigureServices method add the below code, we will be using same secret key,Issuer,audience which we used to create the JWT token



  var jwtconfig = Configuration.GetSection("JwtConfig");

            var signingKey = jwtconfig["Secret"];

            services.AddAuthentication(options =>

            {

                options.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme;

                options.DefaultChallengeScheme = JwtBearerDefaults.AuthenticationScheme;

                options.DefaultScheme = JwtBearerDefaults.AuthenticationScheme;

            })

            .AddJwtBearer(options =>

            {

                options.SaveToken = true;

                options.RequireHttpsMetadata = false;

options.TokenValidationParameters = new  Microsoft.IdentityModel.Tokens.TokenValidationParameters()

                {

                    ValidateIssuer = true,

                    ValidateAudience = true,

                    ValidAudience = jwtconfig["Iss"],

                    ValidIssuer = jwtconfig["Aud"],

                    IssuerSigningKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(signingKey))

                };

                                options.Events = new JwtBearerEvents()

                {

                    OnAuthenticationFailed = context =>

                    {

                        context.Response.StatusCode = StatusCodes.Status401Unauthorized;

                        context.Response.ContentType = "application/json; charset=utf-8";

                        var message = "Token Not provided for authentication or is Invalid";

                        var result = JsonConvert.SerializeObject(new { message });

                        return context.Response.WriteAsync(result);

                    }

                };

               

            });

The last section beginning with options.Events = new JwtBearerEvents() in that code block is to create a custom validation message when authentication Fails.


7.       Middleware code for handing our custom requirements

To handle empty request without token for authentication required routes we inject middleware code in PreAuthenticationMiddleware

Create a new OcelotPipelineConfiguration with PreAuthenticationMiddleware and check if it’s an authentication required route and if the token is empty generate an un-authorized error message. Note by default we get 401 error without any message




Next section we will validate if the token is current token (newly generated) and extend the expiry time with 10 minutes. We will inject middleware code in PreQueryStringBuilderMiddleware


The helper. ExtendToken method will call the method in authserver api to fetch the token information from table where the fresh token is saved and extend the time by 10 minutes. If the token information is not found it returns false and we can generate error message.


Below are the detailed methods inside authentication server API


Service method


Repository method

Here the validity is extended to 10 minutes from now.



Using the sample APP

Run the scripts from scripts folder and update connection string ,
Set all web projects as startup and use below urls 

1.       Register new user

https://localhost:44393/RegisterUser

 

Request body

{

 

  "username": "admin4",

  "password": "admin4",

  "roleId": 1

}

 

2.      User login

https://localhost:44393/UserLogin

 

Request body

{

  "username": "admin4",

  "password": "admin4"

}

Get the token from this and use for the next request to get data

3.      Get all hospital list

https://localhost:44393/GetAllHospitals

 

for every valid request of Get all hospitals you can see the token validity gets extended




About Author
ezhilarasan.j
Total Posts 3
-
Comment this article
Name*
Email Address* (Will not be shown on this website.)
Comments*
Enter Image Text*
   
View All Comments
Comments not posted yet!! Please post your comments on this article.
  Privacy   Terms Of Use   Contact Us
© 2016 Developerin.Net. All rights reserved.
Trademarks and Article Images mentioned in this site may belongs to Microsoft and other respective trademark owners.
Articles, Tutorials and all other content offered here is for educational purpose only and its author copyrights.