Search This Blog

Sunday, July 4, 2021

CSharp: JWT Authentication

Q: How we can do JWT Authentication in case of .net Core application?
------------------------------------------------------------------------------------------------------------------------------------------

Step 1:
Create a Login Controller and on top of that controller give attribute [authorize], this attribute will ensure that all actions inside this controller will be authenticated first. 

Step 2:
Create a action method "authenticate" in above controller and give attribute [AllowAnonymous] to it. This will make sure to bypass the authentication on it. 
>> We have two important input parameters to this method. username and password. 
>> This is the entry point to our application where we will check if entered username and password are correct or not. (usually database we use to check)
>> If username and password are correct we will use it to generate token and return the JWT token value. 
>> UI application can use this JWT token and send it with its further calls

Step 3:
Inside above authenticate method, create another method generateJWTToken(). Call this method on successfull validation of username and password. 

Step4:
>> Inside generateJWTToken method pass a secret key. This secret key can be maintained in config file or in database. 
>> In above method using secret key, algo type and some other thigns generate token. 
>> We might have to install few packages from nuget at thsi stage. 
>> Once the key is generated return it to the main function/ 

Step 5:
Startup.ConfigureService. Add service service.AddAuthentication in startup.ConfigureService method. We have to add few more properties here. 

Step 6:
Add app.UseAuthenticate in Startup.Configure method as a middleware. 

Now when we call any other method authentication logic will be in picture and it will check for jwt token is present in the call or not. if it is present that code will check for its validity. 



No comments:

Post a Comment