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

Video Statistics and Information

Video
Captions Word Cloud
Reddit Comments
Captions
to create a Json web token with the.net 7 web API we first write a register method where we use vcrypt to Hash the password of the user then we write a login method to well verify the password and only if the credentials are correct then we create the Json web token and return it so let's start with a web API project we use old school controllers not a minimal API and then the first thing we add is actually a user model and also a user dto a data transfer object that we will use to register a user and lock the user in so let's just create a models folder here and put both into this folder here so the first thing we add a new class and this is a user class and with that you might probably already see the difference here to the dto then because this user here has got a username which is a string of course by default let's set this to string empty so we get no warning here and then not a password what we want to store is a password hash value but this is also a string because we will use bcrypt.net for that and bcrypt will create this hash for us but more about that in a minute now let's also create the dto this thing will look really similar and uh yep let's call it user detail we could also call this user request or response dto if you want to get something or a user as a response back but let's just call it user dto for this quick and dirty example and here we also have a username which is again a string and this time we can actually say this is required so we get no warning this is new to C sharp 11 by the way and also required uh password right and this is the plain text password because we will only use this to send the data to the server to the web API meaning for registering and logging in a user all right so dto and the user model and by the way we won't store the user in the database in this tutorial here and that's why we don't have an ID for instance as a property just the username and the password hash and we will then create this user only for the current instance of the web API I think this is totally sufficient for this learning purpose here all right so we've got our user and now let's already create our controller here we've got the weather forecast the example example control already but now let's also add another one and this shall be an empty API controller no read write actions no generated code nothing at all I think the empty one is the best for Learning and also actually sometimes for well most of the time in my case I like it when the stuff is empty and I can start from scratch all right this is now the auth controller let's call it that way and in here now well first we need a user right so let's just add a static user use uh that's the one this is also a user and this is by default a new user and we need the model's namespace here of course and now we start with our register method for that we have to again use or we want to use I want to use bcrip but we have to install the nuget package for bcrypt if you're following me for some time you may already know that in my courses and in other tutorials I used the cryptography algorithm here from.net but bcrypt is just state of the art so let's use this thing becrypt.net is what we're looking for and the package is bcrypt.net Dash next alright and let's just install this thing there we are and now it shall it should be available here and now register this will be a post method so HTTP post I just assume that you already are a little bit familiar with the request methods and the attributes here so this will be a post call and since we are actually not using anything asynchronous let's just uh return an action results and maybe just return the user here so we see the actual result then we want to use the user dto which is our request let me get some space here all right so I can breathe a little more and now we need the password hash all right so for that string password hash and this now is bcrypt.net then bcrypts and then simply the method hash password and here it'll be request password that's totally correct intelli code we want to Hash this thing and as you can see Hash a password using the open bsdb Crypt screen and a salt generated by B Crypt and this is already interesting because with that salt we make sure that the hash value is not always the same even though the plain text password is the same right so if I have the password I don't know remember for instance and several users use this password and we would just use a hashing algorithm like md5 which you really shouldn't use because you can do it the other way around and then from the hash value you get the plantex password so please do not use md5 this is lots of time ago but now with B Crypt for instance bcrypt already generates a salt value and puts the salt value and the plain text password into its algorithm and then every time it hashes the password another hash is the result although again the plain text password is actually the same and where is the salt in this case well it is put into the final hashed password value right so in this string then password hash there you will also find the salt there are other ways to do that for instance you would generate a salt first and store this in the database so you really have to know which salt you did use which is also just a random string in essence and then if you want to verify the password you would use the plain text password and the salt then from the database long story short with bcrypt this is not necessary and it is state of the art so maybe also the most secure way okay and with that out of the way we can just create the user with the username request username and the user password hash then is the password hash and for this example we just return the user all right so this is an important step for our JWT generation in essence because I want to display a good flow here we first register user then lock the user in and again only if logging in was successful then we generate the Json web token so here we've got our method in swega string strings perfect we hit execute and you see this is now our password hash and pay attention now when we do this again just look at the endings because here in front it could look the same right but you see every time the the hash value is different although we are using string as a password every single time all right this is registering and now let's log in the user and for that actually let me just copy paste this now it's time for copy paste errors so again it's a post method but this time we call this login and here also a login the same dto and now let's just say we first want to check if the user is actually there so we check if we've got the username all right so if user username our case usually when the user would be in the database then well of course you would find or you would look for the user in the database but here now I think this is also sufficient for this tutorial and in that case I just want to test our API here in essence we return a bet request with user not found all right then verify so now again we use bcrypt here and what we do now is bcrypt.net bcrypts and here we can call the method verify verifies that the hash of the given text matches the provided hash all right and in here now we only put our request password and then also the password hash value we generated earlier and now if this is not true so again verify it returns a Boolean value here then again we return a bet request telling us wrong password and just as a side note in production maybe you wouldn't do it like that because with that an attacker would know all right the user does not exist but then when it's telling the user that password is wrong an attacker would know all right this user does exist so now I can Brute Force maybe the the password or find it by Brute Force so maybe you could test both or use the same error message like username or password is wrong something like that for a production for a professional application then all right and with that if everything is correct we again just return the user Alright and then the next step would be creating the Json web token but let's test this first real quick hope you're there yet there we are so we register user string string nice name nice password and now what we can do now we've got our user right it is now available in this instance of the web API we try this out and first wrong name user not found awesome wrong password execute wrong password works so decrypt at its best and execute we get again the string with the user password hash same thing as above right I guess looks pretty similar okay and now finally creating a Json web token real quick the net Web Academy is now open for enrollment but only for two weeks and spots are limited so if you want to join this four to six week program where you pretty much learn everything you need to land a job in the.net web development World speaking of web apis Entity framework covers migration SQL Server Blazer webassembly gits Azure what not then please check out the link in the video description below because with that link you get a huge discount on this program and you get also Early Access as soon as a new chapter has been uploaded and you get also access to the community of the.net Web Academy so please check out the link thank you very much for considering and now back to the tutorial so what do we have to do here well in essence we would call a method a private method that creates this token alright so let's write this method first private string call this create token user user so in here we've got the username for instance and now the beauty of a Json web token is that we can store so-called claims in this token meaning it is a string of crazy characters but still you can read for instance the user ID the name the role the email address whatever from this token so let's just create one list of claims here for this token and only put the name into this token and then we will see if we can actually find the name then when when we get this token so first again a list of claims and claim is in the namespace use system security claims and we call this claims this is a new list of claims and we use the object initializer here to store again the username for that we call claim types name and here you see it already right it's not only name name identifies the ID then we've got also roll and you can also put custom stuff in there but let's just do it with the name here and this is our user user name all right now down here it is getting interesting this is a bit more complex but this is how you would create a Json web token manually here in a web API with.net7 first we need a symmetric security key all right so VAR key is a new symmetric security key and for that we need a reference and this shall be Microsoft identity model token so let's find and install the latest version in the USB stop the application so now we've got this thing here and now in here comes the string and from that string we wanna just get the bytes all right so this thing takes as you can see here a byte array now this is a key that is used to create the Json web token and also verify the Json web token whenever the user makes a call or the application makes a call with that web talk with the Json web token so we make sure that this is really a token that came from our application now we could just enter the string in here or we can do at least it's a bit better than just putting the the the key hard coded in here we can put it here in the app settings and then just access the app settings here so for instance what you can also see in lots of tutorials is that you can call this JWT or app settings that's the way I do it for for tutorials like this one here so we've got our app settings here with the token for instance or the key and this key is a random string top secret key for instance make sure that it at least has 16 characters maybe you want you want to use a long string of 50 I don't know something like that that cannot be stolen of course and uh also there are other ways to do this for instance if you publish this thing to Azure there are other ways to use a secure store for these kind of things anyways this is how we can do it right now and to access now the app settings we need a Constructor here so first controller and we access the eye configuration call this eye configuration we create this field here at the underscore and now what we can do is actually we have to again encode this so encoding and then eutf 8. and then get bytes and in here now we access the configuration say get section we want the app settings section and then the token so that's how this is done and from that we want the value and this is definitely not now right so this is how we can access this thing one parenthesis here and this should work with that we get our key after that we need signing credentials so while creds for instance new signing credentials in here we put our key and then also an algorithm we want to use for our Json web token and this thing can be security algorithms and then for instance hmx R let's just use 512 signature here I think this is this is a good algorithm for that all right and next we actually generate our token so our token is now JWT security token for that we need system identity model tokens JWT find and install this thing and this gets some options now so in here what we can do is first put our claims all right the claims we created earlier on top so claims would be claims then an expiration date so expires and in here well you could use any date you want for instance just tomorrow you can do that with daytime now and then we only add one a day so this Json web token is valid then for one day and the last thing are the signing credentials this is what we need credentials almost with a lowercase s and in here now these are our threats credentials let's also add the new keyboard here so now the error is gone this is our token and now the last step is to write the token and for that we save our JWT is a new JWT security token Handler and from this thing we use the right token method with our token and with that we get a beautiful string here now we return our Json web token so let me just remove this and again create token with the user object we need the user object to set the username as a claim to our token then we grab the key from our app settings credentials are needed with the key and then the signature the signing credentials at the signature algorithm here hmx r512 then we need the token don't forget the new keyword JWT security token with the claims then an expiration date and also signing credentials and finally we write the token with the help of the JWT security token Handler here and return the Json web token and now up here we just say string token is create token with our user and here we return the token Let's test that there we are now let's try register again maybe this time with a different name and different passwords it executes all right you've got our hash value Here and Now logging in try this out Joel and Ellie drumroll there's our token and now let's have a look if the name is really in there for that we go to jwtio and here in the debugger we can just paste this thing and here you can already see it the claims name is indeed Joel all right and this is how to create our Json web token now the next step is of course to read the token in our application use this token to make a call and then check if the user is really authenticated and also authorized with certain roles for instance and if you want to know how to do that just click on the video on the screen
Info
Channel: Patrick God
Views: 27,138
Rating: undefined out of 5
Keywords:
Id: UwruwHl3BlU
Channel Id: undefined
Length: 21min 26sec (1286 seconds)
Published: Tue Jan 24 2023
Related Videos
Note
Please note that this website is currently a work in progress! Lots of interesting data and statistics to come.