ASP.NET CORE : Implement JWT Token Authentication in Asp.net Core Web API C# [Simple Guide]

Video Statistics and Information

Video
Captions Word Cloud
Reddit Comments
Captions
welcome to codepedia in this video we learn a basic jwt authentication in dot net core before writing any code let's understand the workflow here you can see we have a client and we have api server and we have a user control which has two action method the first is authenticate and the next is list in the authenticate action method we pass username and password and it's check whether the user is spelled or not if the user is valid then it will generate jbt token and it will give in the response now we have access token in a response we can save it somewhere and next we call the list api and we pass the access token and at the back end it will check whether the token is valid or not it is expired or not if the token is valid then response will get the data else we get the message as unauthorized let's set the coding part from visual studio we create a new project and i'm selecting asp.net codeweb application from the template click on next button will give some project name as basic jwt auth click on create button here i will select dot net core five version as we are working on api so we will select this template as dotted core web api and click on create so this is our default project as you can see here we have some default controller so let's remove this let's also remove this class to implement jwd authentication we need to install some negative packages and those are microsoft hp.net core authentication jwt barrier and the second system.identitymodel.token.w3 if you have selected asp.net core 5 version then this will automatically get installed so only the second one we have to install for that we go to tools nuget package manager as you can see here this is already installed so next we go to browse and type that system by identity model and we install this so now our packages are installed next we go to the app setting dot json file here i will add a section as jwt under it will create three keys the first one is key and the value of this would be a secret key next we add issuer for this i am setting the url of my blog next we have audience so now we have done with the nuget packages installation and app setting configuration next we move to a startup class file and here under the configure services we add some services the first one is we need to add authentication so for that we write services dot add authentication options dot define authenticate sigma equal to jwt barrier default dot we need to import some namespace let's hover it next we add for default challenge scheme same as jwt barrier and now we configure some jwp barrier specific values here for that we will write add real token in that first we get the key value from our app setting file for that we will write variable as key equal to as we need the byte so we will write encoding we need to import the namespace here dot get bytes and now from app setting we get the key value so for that we will check jwt of key so we will write configuration jwt colon okay so this will give us the key value from our f13.json file next we write o dot save token equal to true we'll set this as true and now we write the token radiation parameter which we need equal to new so here we set the value for validate issuer signing key equal to true next we write the valid issuer equal to configuration from there we get the value of and we copy from here and we'll paste here same we do for the valid audience equal to configuration and then we write jwt and copy the value from and paste it here and now we set issuer signing key equal to new symmetric security and here we pass our key value which we have in a variable of key so now we are done with the configuration next we need to add middleware here for that we write app dot use authentication note this this should be always above the authorization so now we are done with the middleware and we are done with the services now we create a folder and it will have our model or entity we can say let's create a new class as user it has two fields for example name and password same we do for the password now we create a new class file for token in this we create two fields as token and refresh token next we create a folder as repository let's add a new folder and name it as repository in this repository folder we create a new interface and name this as i dwt manager repository make it public add token here and then a method name as authenticate and it will send the user we need to import the name space here now we implement this interface so for that we create a new class let's copy this name and we'll add a new class here and let's implement it to make this video simple i am not going to use the database for the user authentication so let's create a dictionary here which will authenticate for the user for that we will create a dictionary of string in that we pass some dummy values for example user1 and the password has password one let's create some more so now we have user record and we'll check from here so first we check whether the user is valid or not so we'll check with this user dictionary if user records dot any x dot key equal equal to user dot name and x dot value equal equal to user.password that is not then we'll return null if the user is valid then we generate token so now we inject the eye configuration from dependency injection and now have you write the code to generate token for that first we create a variable as token handler and this will be equal to new jw security token handler we need to import namespace here next we have our key from our abstract.file for that we will create a token key variable we need to import the system.txt namespace here utf dot getbyte and from configuration we get the value of our key let's copy from app setting now we need our token descriptor so for that we will create a token script equal to new we need to import namespace here now we create a variable as subject equal to new of claim identity and we pass here the array of claim new we need to add the name space here again and here we set an claims so in our case we will add a username so new claim equal to claim type dot name as username user.name you can add multiple claims as you want now we set the expire of this token so for that we will use parameter expire equal to datetime dot utc now dot add as you want a token to expire in five minutes so we'll add five and now this token got expired after five minutes next we set signing credential equal to new signing credential and here we pass the token key and next we set the algorithm dot sma signature now we create a token for that we'll create a variable as token equal to token handler dot create token this will create a token and it will return a security class and here we pass the token descriptor and now in this token variable with get a token but as we want to be in string so for that we will create equal to token handler dot write to token and here we pass our token so this will return a serialized token in string so now we have created the authenticate method let's register this service in our startup class for that we go to the startup class and at the end we can write services dot add singleton and the interface name as i jwt manager repository let's add the name space here so now we have registered our services and now these services will available in a dependency injection container and from our constructor injection we can access this service so let's create a controller first and give it a name as user controller so this is our default user controller and from dependency injection i mean by using constructor injection we can access our services of igw manager repository so for that we will create a constructor here first and then we'll inject that now we create two action method the first one is authenticate and that would be a post request and the second is get request which return or user released so let's create get request first and now return this user list next we create a post method for authentication for that we'll create a action result so public action result authenticate and will pass the parameter as user add the verb as http post and let's give a route name let's authenticate we have injected our services here let's call the method here where token equal to jwt manager repository authenticate and will pass our user data if the token is null then we'll return unauthorized for that we'll add a condition here if equal equal to null then return unauthorized else written ok in response with a token variable so now we have created two method the first is get request and the second authenticate so now to authorize the whole controller we'll decorate it with authorized attribute we need to add the namespace here also so this will authorize at controller level but as we want the authenticated api should be accessed by anyone so we will make it all anonymous so now anyone can access this authenticate action method and for get request we need the access token let's add route name here also as user list so now we have two method the one is get request and the other is post request this will authenticate the user and return token and if the token is valid then only usually will able to access the get method so let's run this application i will copy this url and paste it into the postman api slash users slash user list let's hit this with an access token as you can see here we get the unauthorized message so we need to authenticate user for that we call the authenticate method so let's click here make it a post request and add authenticate now in body we have to pass our username and password and password as password1 let's hit this let's see we get the access token here now we'll copy this token and paste it over here in the get request under the authorized tab we'll select barrier token and we'll add the token here let's let's click the send button okay as i'm calling it from localhost so i need to set valid issue as false so for that we'll stop it and go to the startup class and under this we'll write validate issuer equal to false and also for audience equal to false so for local environment we're making at sports but if you're on production then you have to make it as true also to expire the token after five minutes so we need to add validate token lifetime equal to true so that after five minutes how to get expire now let's run this and now we can access this and here we get the output if we want the source code of this project i have already written an article on my blog i will share the link in the description and so from here you can copy the code i hope you like my video
Info
Channel: Codepedia
Views: 21,672
Rating: undefined out of 5
Keywords: web-development, codepedia, education, JWT, Asp.net core, C#, JSON WEB TOKEN, Authentication, jwt token, aspnet core jwt authentication, aspnetcorewebapi, aspcore, authentication, jwttoken
Id: qtYIpZX-s-k
Channel Id: undefined
Length: 20min 3sec (1203 seconds)
Published: Sat Feb 26 2022
Related Videos
Note
Please note that this website is currently a work in progress! Lots of interesting data and statistics to come.