Part-1 A Demo On JWT Access Token And Refresh Token Authentication In .NET6 Web API

Video Statistics and Information

Video
Captions Word Cloud
Reddit Comments
Captions
hi everyone today video is on jwt access token and refresh token authentication in dot net 6 web api okay particularly in this video we are going to create the jwt access token and in the next video we are going to use the refresh token okay so what is jwt token jwt token is nothing but json web token okay it it is categorized into three parts header payload signature and header contains like algorithm like hs256 and type it what is the token type that is jwt and payload contains claims like username issuer audience email okay and so on and signature contains digital signature that means it is an encoded of header and payload with secret value okay so these are the three main building blocks of json web token so if you have a json web token that means that user is authenticated and he is authorized to access based on his clients instead of the payload okay so let's understand the jwt access token flow so when the user sends username and password if they to the api if the username and password are valid then api creates a jwt access token and written that token as response to the client okay then client stores that access token either in browser session okay are in some state it uses that jwt token as a header for each and every request to the api means if we add jwt token as a header to the particular request if the if that request need authorization then this token will be the entry pass or authentic user authentication pass to consume the particular end point so that's why on every request after successful login on every record client application either a angular react rujs javascript applications can send the jwt token as a header value okay so that is how a jw token will be used for authentication okay now let's create a dotnet six application web ap application and try to implement a small sample so here is a sample user table that i have created that i am going to use in my web ap application so the user table contains columns like first name last name email password and phone number and you can add a number of your required user values as a table for this demo these are the columns i created okay so to follow along with me please create a table almost like this okay and here i want to mention one more point here carefully observe password i directly saved raw password which is a very very bad implementation because of this is a small demo and that mainly targets jwt token generation i am not hashing the password okay if you want to implement the process for your production application or your real-time application make sure to ask the password hashing means one way the password cannot be seen by within naked eye okay it should be encrypted this encryption is one way this cannot be decrypted that encryption is called hashing that kind of hashing must be used to save the password okay and you can find lot of core snippets how to encrypt hash the password customly you can check them okay so here i am using dotnet cli to create a dot net 6 web api project so comment is like dotnet space new space web api space hyphen space name of your project so let's create the api project project created successfully let's open the project okay here you can observe target framework that is dotnet 6.0 and here is our project okay now first let's try to configure the database context and table classes so we just implement the code first with the existing database okay so first let's install install the required empty framework packages okay so the first package i will install that is microsoft dot nt framework core so visual studio 2022 user please copy the command from package manager or you can use the ui interface provided by the visual studio as well and since i am using dotnet cli i am going to copy from here copy command install the package the second command we have to install that is microsoft dot nt framework core dot sql server copy command install the package now we have user table right let's create a entity for user table and entity contains property names that match with the table column names because we are using the code first with existing database approach okay so here let's add a folder like data and a subfolder like entities instead of entities let's add class like user.cs so let's add properties to the user class so finally our user class look like this now let's create the database context class for that in the data folder directly create a class like your database context class i will name it like my earth context okay here is our earth context class to make it database context it must inherit db context that slows from microsoft dot nt framework core and let's add the constructor like and to the constructor we can create db context options okay we should pass the context to the base class nothing but a b context class and here we must register our table class using eb set so public db set define the type as user which is nothing but our class okay user and import the namespace okay like this our context class looks like and now okay let's add the connection string go to app settings.development.json here let's defend connection string okay my earth context now here add your database constraint okay after adding consisting let's register our our context in program.cs5 so here folder services add pb context and define my earth context okay options options dot use sql server and here we need to pass the connection string so to load the connection string builder dot configurations dot and get connection string and inside of it let's define the name of the connection string what is our constraint string name it is like my earth context copy that and pass it over here okay now let's install system dot identity model dot tokens.jwt you get package into our application okay system.identitymodel.token.jw token the required package that we install now copy command let's install the package now we have to prepare few settings for our jwt access token for that go to app settings.json let's create a settings like token settings okay and we need settings like secret key okay this secret key will be any random string can be any random string and this secret key will be used by the jw token for generating the digital signature and the same secret key will be used at jwt service while validating the incoming jwt token okay so for the demo i will give like my secret key secret secret something that you can give any random key and you can generate from any online tool to get a random string okay and next i want settings like issuer okay and audience okay so issuer means nothing but the which issues the jwt token in our case our api is only issuer so here we can give our domain name as issuer okay so for that go to properties and launch settings and from here copy this hostname okay as an it is sure so audience audience is nothing but the client that uses this token like any angular application react or js any js application in our case i simply use the postman to test our api rate so what i will do i will simply give api itself as my audience okay so this issuer and audience are nothing to validate the incoming jw token when the authentication is successful and the request header contains jw token in general to validate the jw token because all these issuer and audiences are automatically added as one of the clients into the token so while reading them with along with the request we can use them for validation like a additional security that that token is trusted and we can confirm that token is a trusted one and validated successfully okay so these three things we required as a token settings and now let's create a class for this settings so that we can directly access them through through the entity for that let's create a folder like settings in that settings add a class like token settings and it should contain properties that exactly match with our json object property names okay so let's create properties for this class okay now let's register our token settings and json token settings at the program.cs5 so that they can be injected using eye option into the into the constructor okay so go to program.cs file builder services dot configuration configure so type is like token settings okay and here builder dot configuration section and name of the object nothing but token setting this name copy that okay that is the required registration to implement our logic for user authentication and generating the token first let's create the services so let's create the concrete and implementation files for the services i will name them like a account services okay so let's clear all and create a new folder like services okay and add a contract file like i account service okay this is our interface that contains all the method definitions of our account service that we are going to create now okay let's create account service okay here is our account service let's inherit i account service okay and now let's inject our context class as well as our token settings here into the constructor so private read-only my earth context okay same way we are going to inject token settings as well okay and to inject the token settings we are going to use i options okay that loads from microsoft extension start options and we have to define type as our token settings and let's assign them token settings.value because we are using i options right we call like value okay now let's create two dtos tt was nothing but data transfer objects one is for user payload means like username password object okay and another is like token detail so it is like a response object that contains access token access token nothing but jwt token let's create one more folder like dtos and add a class like login dto okay this is our login detail which is nothing but a user payload so it contains property like email and password let's add them now let's create another dto like token return okay dto dot cs okay here is our token d2 and it contains property like access token which is nothing but jwt token in our account service let's create a method definition for generating the jwt token okay that is like task and it should return token response okay get author token and its input parameter is like login dto okay now let's implement this method into our account service let's implement it so here so first we have to fix the user data based on the email and the password user equal to my earth context dot user dot where email i forgot to add email in user class so let's add that property sorry for that okay now go to our contest class for not context account service and email dot tool over equal to equal to login email dot to lower and compare password as well password equal to equal to login password here i am mentioning again here i am comparing graph password directly because i saved a password directly which is not correct okay but demo purpose to make it simple by directly comparing the ra password and directly save their password into the database in real time you must hash the password while saving into the database and while comparing also the user sent password should be encrypted okay then that encrypted characters must be compared against the hashed password in the database okay so please make sure to do that so finally first or default async okay if at all user exist then we have to generate a access token and written as a response okay if no token is if you do not exist we simply written null that and i'll respond okay now we have to generate the uh user access token right for that let's create a private method for generating the access token okay private shipping create awt token and to this method we must pass our user information okay first thing is we have to generate the metric security key okay this symmetric security key instance will be used by the sign in credential okay so using that sign-in credentials it's going to generate in the digital signature okay if you recall our jwt token image token signature right so to create the signature we first need to initialize the symmetric security key then that will be consumed by the signing credentials uh object to generate the digital signature okay so let's create symmetric security key equal to new metric security e that loads from microsoft to modus dot token okay import the namespace and it will expect some byte array of key so we have already uh added one security key key right in app settings.development.json so this key must be converted as bytes of error and pass it into the symmetric security key so to convert into the bytes of array we can use encoding dot utf-8 dot get bytes simply pass over the string so here we already injected the token settings right so from the token settings we can get the secret key so generated the symmetric security key next we need to generate the sign-in credentials for generating the signing credential okay it's going to take metric security and algorithm to generate the signing credential so i am going to use security algorithm dot s m s j j 256 okay and then so we have created the credentials now let's prepare the claims to store into the token so where user claims equal to you climb array okay new climb equal to i want a email address as a claim so user dot email and also phone number as a claim so or number dot prime okay here i want to mention one more thing that in real time example you will have separate tables for the user roles and claims so you can load all those roles and claims and add it into the token okay i have prepared claims as well now let's create the jwt security token instance for that where kwt token equal to new jwt security token okay that loads from system dot identity model dot token stock jwt the package we have just installed right that one okay it takes several input parameters like issuer be sure we have our token settings right sure and expiry date this is the expiration date of my uh token so token always it should be good to give just 20 minutes okay you can give one day two days three days also but it is ideal to give 20 minutes because we are going to use the refresh token concept right that leaves around one week that is why token should be short and refreshed token should be in long term because research tokens don't contains any secured data like claims like something like that is it just random string okay but whereas jw token contains some security data right so we must expire it as soon as possible okay sign-in credentials credentials we have just created right pass them and claims lines we have just created right past them okay and audience we can pass audience as well that is from the token settings dot audience and from the jwt security token instance let's generate the actual token for string token equal to new data ability security handler dot it is instance write token okay to that pass the jw token object so this is going to write the stringify token so let's return that token okay now let's consume this method here so written new token dto and access token equal to create jsw token and pass the user okay so that's it that is our logic for generating the authenticated jwt user token now let's register our account service and icon service into the program.cs file so builder services dot add hope i will use ie account service and account service okay and next thing let's create a endpoint authentication endpoint okay and let's add the action method for getting the access token okay for that let's go to controllers folder and let's add a controller like account controller okay in this account controller first let's inject our i account services okay and now let's create an endpoint for generating the access okay so public casing task i action result get login token okay and it's contained login dto input okay login and it should be decorated with http post and it should be add some route like login token okay and let's call our service result equal to await account service get out the token and pass the login payload if result equal to null means invalid user credentials at that time we are returning right null then user not phone return validation problem method here we can pass exception like invalid credential okay if everything good results is not empty then simply return them okay so that's it we are able to generate the access token for a valid user let's run the application and test whether we are able to generate the access token or not okay so here is our endpoint login iphone token let's try to get the access token so i have already added a sample record in the table right i am going to use this credential now execute sorry gmail.com see i got invalid credentials error message because i have given wrong email now i corrected it click again see i got access to can see the encrypted string so to see what is inside of this token let's copy this and go to jwt io and go to jwt dot io and here in the encoded area replace with our access token and see here it is decoded into header payload and signature algorithm it's 256 we have used right while generating the signature same algorithm will be shown here and you can see all my claims email and phone number i manually added but issuer expiration audience all these claims are automatically added while generating the password right they are added and here is the digital signature format this is nothing but header and payload plus with the encryption okay so this is how jw token is framed and this is how we can take our generated jwt token okay now we are able to generate the token but whenever we pass that jwt token as a header to consume an endpoint we should validate right for that we have to register the aw2 jwt barrier service in the program.cs5 for that we have to install one new get package okay let's install it okay then you get we have to install that is microsoft dot asp.net core dot authentication dot a w t barrier okay so copy that install the package okay after installing package let's go to program.cs5 and here we have to define our jwt barrier service where we will write instructions or rules for validating the kw token when it is attached to the request header okay builder dot services dot add authentication type we are using jwt barrier authentication right so jwt error defaults okay dot authentication scheme and then add jwt barrier okay and here options where can settings equal to first let's load these tokens that is from the json because we are using them here for validation as well we have resist we have a token settings right we have to load them here for that what we can do builder dot configuration dot get section so like this only almost but dot get and i can define the type that is token setting so it will load all the settings into this variable and then next options dot token validation parameters so here we have to define the token validation parameters okay so let's short the namespace and import the namespace okay so our token contains validator issuer claim right so let's uh specify here need to validate the issuer as well for that we have to specify the valid issuer means the value of the issuer that we can get from token settings dot issuer and we have to make a rule you should validate the issuer for that validate issuer we have to say boolean true value okay so here we are assigned value and here we are imposing the rule to validate it mandatory okay next same way we can do for audience as well okay so valid audience will be the value token settings dot audience and to make it compulsory to validate the audience validate audience equal to true okay equal to true and we have to and here we have to assign the signing key value also for that issuer signing key equal to here we simply pass the metric e is enough for validating okay and it should contains encoding data right so what we will do account service copy this code line okay and here i want to show one more thing that is clock skew by default this clock skew if you hover it it's a default value or if you inspect it its default value is 300 seconds that means in spite of our token expand after five minutes also the token is treated as a valid okay to make it exact expiration we have to specify the time spans to zero we are overriding the five minutes times point to zero okay so those are the settings we required for validation okay what we did we have defined the authentication type that is dwt barrier token authentication and added the creatability barrier service and added the validation rules like issuer must be validated audience must be validated sign-in key must be validated those rules are applied here okay now let's add authentication middleware just above the authorization okay authentication now let's create one secured endpoint okay that contains audrey authorized header that means only authenticated user only can consume that endpoint okay let's create it simple endpoint in the account controller okay public i sorry i action result get some test endpoint okay return okay i will simply written a string only only for authenticated users okay so http get request and add route like test auth okay and also main attribute that is authorized otherwise okay now let's try to access this endpoint first without having authorized sorry without having access token okay first let's run the application okay here two endpoints were created for testing here i am going to use the post one because uh to enable the authorization header values all the everything in swagger we have to do additional steps so to skip it i am going to use the postman so here is my get endpoint let's try to access it see here for not one that is unauthorized means that is a protected resource we should have token uh to access that end point for that let's go to our swagger and try to get the access token again okay so to get the access token let's give our valid credential so i got the token copy the token and go to postman and select header section and here add a key like otherwise okay and here value directly we cannot send a uh generality token it should be prefixed with barrier because dwt token convention is that okay so barrier b e a r e r and space and then your token okay now try to request the end point see now i got the result only for authenticated users that means our authentication is successful jwt authentication okay so that's all about small demo of generating jwt token in dot net 6 web api in the next video we are going to create refresh token so i hope this video has delivered some useful information to you all if you like my video please support me by subscribing to my channel soon we are going to meet with new videos until then signing off
Info
Channel: Naveen Bommidi Tech Seeker
Views: 1,536
Rating: undefined out of 5
Keywords:
Id: WmVUw1fXyFA
Channel Id: undefined
Length: 44min 50sec (2690 seconds)
Published: Sun Jun 05 2022
Related Videos
Note
Please note that this website is currently a work in progress! Lots of interesting data and statistics to come.