.NET 6 Web API 🔒 Create JSON Web Tokens (JWT) - User Registration / Login / Authentication

Video Statistics and Information

Video
Captions Word Cloud
Reddit Comments
Captions
hello youtube this is patrick god yes this is really my last name i would never use the lord's name in vain why the hell would you think that why the hell yeah thanks for the feedback i guess anyways today we are going to implement json web token authentication in.net 6 in the net 6 web api but not only this we will also create user models to well register a user log the user in and if the password is correct after logging in then we will create this token and return it so i think this is a good start for json web token authentication and the custom authentication with net 6 and web api and i would say before we jump right in please if you like this video and learn something i would really appreciate it if you click the like button and maybe even subscribe to my channel it does make a difference thank you very much apart from that maybe you want to subscribe to my newsletter that would be really nice and you would get early access and free access to youtube tutorials online courses and so on and i promise i won't spam you maybe once a month or sometimes once a week i will send you an email and apart from that okay gotta admit i forgot my coffee but still thank you so much for buying me a coffee i love you guys this really means a lot to me and helps me making all these videos and now i would say let's start a new project so we see visual studio 2022 here and we create a new project and when my machine wants to it doesn't take lots of time so asp.net core web api this is the thing we need here i've got it here in the reset recent project templates and i am having a little cold so i hope my voice is okay and it doesn't bother you too much but anyways uh here's also the uh the template in the well in the certain not in the suggestions here of the recent project templates but you know what i mean um additionally of course you can always search for this thing so asp.net core web app it's not a web app it's web api in this case here but of course i don't know maybe you want to create a blazer web assembly app you can totally do that as well use asp.net core hosted and then you got a web api as well and then well create a json web token authentication now let's give this thing a name let's call it i don't know jwt web api tutorial so json web token web api tutorial click next dotnet 6 is the framework we want to use no authentication here now we will use the custom authentication we configure this for https that's okay we use controllers and also enable open api support so we get a swagger ui thingy here that we can use to well test our implementations all right we are here already and taking some time today i don't know what what's going on it's sunday so maybe my machine thinks well what the heck is going on patrick not on sunday man really needs some coffee first but anyways let's see so we've got our program cs here if you're not familiar with.net 6 already we do not have a startup cs uh file anymore so um if you wanna get started with uh six web api in general please check out the info card i made a complete tutorial with the.net six web api and entity framework core and a sql server express database so maybe you want to watch that first and then you get back here so i won't go into deep in here now what i want to do is we create three models two of them would be data transfer objects in essence meaning we would just use this data to transfer well in essence the username or an email address and the password to the to the controller to the web api and the other thing is the user model the actual user model which will then store a password we will use a password hash here with the password solved so i think this is again a good start for this stuff here so let's just create three classes uh right click the project and then add class and then we call the first thing user register and let's let's think about that i got no scripts i think i have to mention that so i would just think my boy is sleeping and i thought okay i've got maybe half an hour or an hour so let's do this tutorial really quick um or let's let's call this user dto thinking about what to use here because in for instance the the e-commerce course or the blazer web assembly bootcamp there we would use a user register dto where we would say well we create a property for the username for instance so this is the username of course this is a string and the dotnet six let's set this to string empty first and in and then in the bootcamp or the other courses we would use a password that's correct oh i lost intellicode intellicode is really great but also a confirm password property for instance so this is just for the registration then where we use a form and use validation where you can see hey this uh confirmed password is not the same as the password value so please let's fix that but for for this case now i think this is totally sufficient we will use this dto for the registration and also for logging in so user ddo user data transfer object for the username with the username and the password and i think this is totally fine then and now the actual user model this is something you would also store in the database but we won't do that here again in the courses of course we do that but since this should really be a quick tutorial what we do here also use the username you would also add an id when you want to store the user in the database but again we won't do that here and now we won't store the password in plain text of course what we need here is a byte array with a password hash actually so password password hash and also a byte array with a password sort and this is the first thing we're going to do we will create a password hash and a password sort and then we will store this well first in the controller here so when we when we restart the web api or the whole application then we won't have the user here anymore of course but anyways i think we can we can totally do it like that so we've got our user dto we've got our user model with the password hash and the password salt and now in the controllers let's create a new one and this is an api controller which is empty and we call this thing off controller all right and now the very first thing here we can do is create a method to register a user now that'll be a post method so maybe add our attribute here http post with a route already let's call this register and this then is a public async task action results and this will return let's see maybe just or maybe the user why not we can return the the finished user then and also let's store the user here of course so public async user is a new user and we will reset this thing this is not async what the heck am i doing here it's a static user and give this a name of course all right so this is our user now great and we create the register method here with a user dto let's call that request maybe and now with that what we are going to do is we again create a password hash for that we need a new method in the course again i have to well mention the course sometimes because we dive a lot deeper into into the whole authentication part here for instance uh we won't use the controller here for all the logic this would then be a fat controller we actually actually use the repository pattern with an authentication service with dependency injection and so on but again for this quick tutorial to give you a little jumpstart here let's do it real quick and dirty maybe but in production maybe you want to change that anyways the first thing we need is a create password hash method and this thing uses an algorithmic cryptography algorithm to create the password sort and the password hash and then store that in the user object and then when the user is trying to log in we will again create the the password hash with the stored salt and just compare these two and if they are correct then we will create the json web token so you see the json web token part is comes a bit later but i think this is a good again good first start and a good a good way to learn this the the procedure i guess all right so our create password hash method first so private void this time it doesn't return anything we will use out parameters here so we can kind of return two values here create password hash which which gets the the password as a string this is the plain password and then it returns the first byte array which is the password hash and also not returned sorry but i think you mean what i you know what i mean so and then the password sorts all right okay and now with that and again with that we use a cryptography algorithm call this hmac and this thing is the hmac sha 512 algorithm we create an instance of this thing and we need the system security cryptography reference here so what i did if you don't know it ctrl period and then you get this quick fix menu here you could also use the light bulb works the same all right and now with that this instance of the hmix 512 class does already create a salt so we could simply say hmac key is our salt here and then to get the password hash we say hmac and now compute hash and with that we say get bytes from our password like that and we need another reference here okay we have to specify this bit more precise so system encoding utf 8 that's the one i think system encoding system text text is missing system text encoding utf-8 get bytes password and this would then be our password hash with the compute hash method here and this thing also uses the key which is in essence now the salt all right and with that we get our values and now we can go to our register method we call our create password hash method so create password hash with the request password and again all parameters of course so alt password hash and then out bytes and password like that and with that now we set our user password hash to password hash user password solid this password salt and we can [Music] wait a sec also what we have to do is of course user username is the request username like that and then we return our user all right that's that's it for registration let's test that already i guess build this thing okay there we are we've got our models here that's nice we've got the register method let's try this string string why not execute and there we are we've got our username string we've got the password hash and the password sort isn't that great let's try it with another user maybe tony tony stark tony stark's great password all right works as well okay great so our user now is tony stark and now let's create the login method so let's go down here and let's also make a post method out of that but we call this thing now login public async task action results and let's say this thing returns just a boolean no it does return a string of course but this because this then will be our token actually so public a saying task action result string that's correct uh login would be the name and also again we use our dto here and now first let's check if the user exists maybe all right so we just check if the the username is here already so if the user username equals and i know you can do this way better with equals and the ordinal case and ignore the case or to lower and so on but again let's make this quick and dirty so if the username and we only got one user right so we do not have to search for the user actually but we just check if the username is correct here and if the username is actually not the request username then we return a bad request like that and maybe add a message here user not found like that and else first we return okay my crazy token for now let's test that real quick okay app has been restarted i guess so we have no user uh let's see we tried the registration this worked and now when we try to log in also with string i hit execute you get my crazy token what about string one execute user not found okay perfect this is exactly what we want this works and now we have to verify the password of course so for that we need another function uh which is returning a bool so private pool verify verify password hash with the string password and now also a byte password hash and a byte password sort all right and now in here again we create an instance of the hmx 512 cryptography algorithm but we'll give this thing our password sort from the user so using var almost var hmac is a new hmg512 and now this would be our user password sort that and in here now again we create our password hash with hmac compute hash and here we will use again system text encoding [Music] utf-8 get bytes and here now we will use the password and we don't have to pass this so we got our password the user is entered on logging in and we return now come nah not comp let's call this computed otherwise this might be a bit confusing so the computed hash value and we will compare this byte by byte with the password hash and we can do that with this cute little function here sequence equal password hash and this then will return true or false right so we put in the password here that the user has entered with uh with the login method here and then we will use the password hash and the password salt of our stored user and actually yeah we could do it like that but let's do it with the parameter actually so it's really used and yeah and with this new instance then we create a new computed hash value with the login password and the salt here and if the resulting password hash then is the same as the stored password hash then this means the user has entered the correct username and the correct password okay i hope this is clear now so let's check another thing here if now the username is not correct then we will return a bad request with user not found now if the verify password mess password hash method with the request pass word and then the user password hash and the user password salt does not return true then we return bad requests wrong password all right okay i'll save that and rebuild the app hopefully all right let's see again we register the user string string execute all right this worked and now let's log in try it out execute my crazy token everything is correct what about string one execute user not found and what about string one for the password execute wrong password all right so this works just fine and now finally the json web token all right so back to our login method and we will create the token here with a new method of course called create token and this method gets the user here method is not there yet but it will be in a couple of minutes and this will be a bit complicated so first it'll return a token and this is a string so private string creates token with the user like that all right and in the end it's also already returned string empty so the error is gone and now first the claims now what are the claims maybe you know this already when well when you're looking for a tutorial about json web tokens well claims are in essence just well properties in essence that are that are describing the user that is authenticated for instance the user id could be stored in the token or the username email anything you want and this is again then in the token and we can read that with a corresponding client application for instance a place a web assembly client app again we'll do that in the basic bootcamp e-commerce course and so on and these are claims so let's let's put some claims there or just one claim usually i would add the user id as name identifier and also the email address for the name or the username for the name let's just add this step by step and then you will see what i mean by that so first we need a list of claims and this is a new list of claims and we can already create this list here and we add system security claims as a reference here and now we add a new claim with claim types and now you can see this here these are some things that are already suggested name identifier country name rsa windows account name and so on of course there are also some functions like equals gender lots of stuff you could use postal codes role very interesting of course when we use authorization with an administration back and for instance yeah lots of stuff and we let's just say we use claim types name here and for that of course we use the username and that's it already so with that we've got our claims and the next thing we need is a key a system a symmetric security key so our key is a new symmetric security key i need another reference system identity model tokens all right wait a sec uh i think that's not the ra the the correct one actually need microsoft's identity model tokens i think that's the one find and install the latest version yeah we edit this and now this thing gets something interesting again we need system text encoding utf-8 get bytes and then we need a key a top secret key that we wanna put in the app settings usually so what we can do or let's just do it that way so we've got our login section here a load host and so on and we will add another section uh again you can put this here you can put this in a secret store or you just type it into your controller this would maybe not be the best way but still let's do it here so i think maybe you get a bit more value out of this and not just type it into the controller because when we're doing it here we have to access the configuration with that we need a constructor in the controller to inject the configuration actually and yeah again maybe you learned something new if so don't forget to click the like button would really appreciate that thank you so much so in our app settings file we add a new section let's just call this app settings maybe you can see it here connection strings or something you would also put here do that in the web api tutorial and in here we just call this token and this can be anything for instance my top secret key for creating the json web token just make sure that it has at least 16 characters and with that we go to our controller add a new constructor here cdor hit tab twice and then we need the i configuration we call this configuration and we create and assign this field here and now in here we can actually access our configuration get section app settings token and from that we want to get the value and with that we've got our key okay as i said a bit more complicated but this is how you create a json web token after that we need signing credentials so var creds and new assigning [Music] credentials with this key we just created and also again the security algorithm which would be the hmec sha 512 signature algorithm all right and then we define the properties or well let's say the payload in essence of the json web token with var token is a new jwt security token and this is getting again some arguments and we have to install system identity model tokens jwt so let's do that and when this is done we can set some stuff for instance the claims are our claims now then we can set an expiration date so expires let's say date time now at days one so that's really so this this token would then be valid for one a day don't know what the problem here is but let's see and then the signing credentials again which are our credits here and this should be it semicolon here yeah and not here okay so this should be our token then and then finally the string we want so our json web token this new json web token security token handler and from this thing we use the write token method with our token and this then will be returned so jwt okay so please rewind the video i don't know how much time i've got left because my boy is maybe waking up waking up any minute and um we are using this method here and returning it all right i would say we test this okay let's see we've got our register method let me try this and what do we get multiple constructors except an organ should only be one applicable constructor well i thought there is only one constructor what the hell uh let's let's stop the app let's stop this restart it and let's have another look register try this out execute and now it worked jesus christ this is really something about visual studio 2022 i think maybe also.net 6 i don't know but sometimes now it's no it should be visual studio of course sometimes it's i don't know get it you get some errors and you think what the heck is going on but actually you just have to stop the application restart it and then everything works anyways registration worked and now drumroll hit execute and there's our token great but let's use another name maybe so again user name bruce wayne execute and then logging in with and also the correct password hit execute that's our sweet token and now we can go to the website jwt io there we are and now let's just enter this here and what do we get the name bruce wayne and the expiration dates monday november 29th all right so this is everything let me just push this to github real quick so you really got the code create git repository json web token api tutorial this is public yeah create and push did i enter a message i'm not sure but i think this is this is a default message uh let's see yeah at project fight okay all right that's it okay so i hope you learned something with that you can now create a user registration logging in a user and returning a json web token again of course this is not everything the next step would be to use the json wrap token and put it in the authorization or authentication header of your http requests and this is actually why we do this because otherwise you would have to well with every request sent the username and the password of the user yeah with every request you have to to send this thing now you can just use the reject web token and i think this is much better a lot more secure and you cannot read the password of course and well to use this then you would use the authorized attribute for instance so that only authorized users can access a certain method in the web api and so on now please give me some feedback if you want to see that here on youtube you can already see that in my courses but of course i can make videos here on youtube just for you guys i hope you learned something would really appreciate it if again you click the like button subscribe to my channel maybe subscribe to the newsletter and coffee thank you so so much for all the coffee i really really need that again mentioning my boy quite often well you know lately he's not sleeping very well but i guess this is the thing with toddlers in essence and yeah but lots of fun anyways okay so again thank you very much for watching and i see you next time take care you
Info
Channel: Patrick God
Views: 227,821
Rating: undefined out of 5
Keywords:
Id: v7q3pEK1EA0
Channel Id: undefined
Length: 32min 55sec (1975 seconds)
Published: Tue Nov 30 2021
Related Videos
Note
Please note that this website is currently a work in progress! Lots of interesting data and statistics to come.