.NET Core 6.0 API Authentication using JWT

Video Statistics and Information

Video
Captions Word Cloud
Reddit Comments
Captions
hello everybody it's kevin here again and this week we're going to be going over some api authentication so just to put it simply apis are secure by nature that's that's just what they that's one of their biggest advantages are so with well while knowing that we might have data that that api might return that we don't want anybody to access or everybody to access so what we can do is we can add some sort of authentication now we can do something simple like if the user enters a password for example then grant them access but there is a more secure way that uses hashing and it's it's more industry standard do it this way so that's the way that i'm going to be demonstrating today so to start off i'm just going to create a blank project here an api here so asp.net core web api i'm just going to call this off lecture 6.0 preview so to start off we're going to want to open up nuget the new get package manager so nuget here and we're going to need to install some packages here so first just got to ensure that asp.net core is installed and then there's a cut there's two other packages that uh that we have to install so i'm gonna pull those up here on another project that i have them open on give me a second i will pull it up here so we will install the following packages here it will be microsoft.asp.net core and here it shows up asp.netcore.authentication so first this one here we're going to install that one accept all license agreements and then we're going to install the jwt bearer package so these will enable authentication in our project and we'll have to do a little bit of configuration in our program.cs file but it's relatively straightforward so what we have to do first is we have to create a class we're going to call this class jwt [Music] authentication manager so i'm going to add a class here once that class is added i'm going to add some some stuff here to it so it's it's pretty much a template so you can you can modify this as as you wish now i will go and i have it pulled up on the other side but i'll go through what some of the stuff that's going on here so to begin we're gonna declare a key so just read only key and then we're going to need a dictionary of type string string and i'm going to name this users and i'm going to add some stuff to this dictionary so i'm going to add a username of test and then a password of password and then i'm going to add another username of test1 and another password of pwd once that is done we're gonna end that there now i have something [Music] a little messed up here there we go next we're going to create a constructor so public jwt authentication manager that's going to take in the key this will be important for our initial setup in the program.cs file now we're gonna have to create a function here called authenticate so that's just gonna return a string it's gonna take in a string username and a string password and i'm just going to return null for now so first we have to check if um we have to do a user check so if users dot any so we're just going to do a little bit of link here next we're going to create a jwt security token handler and once we start making a couple calls to some of the jwt stuff we're going to need to add a couple uh imports on the top so i'm just going to copy these imports i'm going to paste them up here make note of them they will also be available in the lecture notes suggest authentication or authorization tokens system.txt for some byte handling and uh security claims then identity model.tokens so first i'm going to create a jwt security token handler i'm just going to call that token handler after that i'm going to create a token key it's a variable token key we're just going to use ascii encoding we're going to pass in the key to the get bytes function then we're going to have to create a security token descriptor i'm going to call this token descriptor and we're going to do some operations in here so first we need a subject here we need to define the subject after that we have to set the x the duration of the token so that's just set by the expires variable here or expires property and it's just gonna expire in one hour we have to define the signing credentials i have to define the the algorithm so it's just going to be hmac sha 256 signature once that's done we have to define a token variable passing the token descriptor into that and finally we're going to return the token so it's just token handler dot right token and then it's going to take in the token once this is done got to make sure that it looks good no errors that does look good so far so we can do now is we got to go to our program.cs file we gotta add a couple gotta add a couple imports here so some of these are the same as the ones that we used over here but we will also need to add the name space so using athletic auth lecture this will be dependent on what you named your project if you don't add this you'll run into a problem when you're creating a singleton so what we have to do is right after add swagger gen just add some you don't want that there we go just so we know what our little space is here so first we have to define a key and this key has to be um it's got to be greater than i believe eight characters in length it may be more so i'm just gonna name this key lecture test and i'm going to add some some numbers to this so one two three four after this we had we have to add the authentication builder service so builder dot services dot add authentication and it's just gonna be a lambda so first x dot which is what we defined here x dot default authentication scheme we're going to have to define that that's just going to be gwt bearer default then the challenge scheme is going to be set to the same as up here after that we gotta add a little bit more stuff here so add today add the gwt bear once again another lambda here lambda or anonymous function depends on what uh programming language you're familiar with anonymous function might be what you called it in javascript or in typescript uh lambda might be from java it's uh it all refers to the same thing mostly there's probably going to be some purists down in the comments or something saying no so x dot request https metadata and we're going to assign false to that boolean we're just basically just configuring the authentication here so if you have any issues or if it's not acting right just look at your settings here you're manually setting it here and you might be able to fix it that way uh one other thing to note is ensure that you use the same encoding as used in your jwt authentication manager i'm just gonna double check that i'm still recording yep looks good we want to validate our issuer of course or i'm sorry for this example we don't want to validate our issuer that uh delves into this authentication stuff a little deeper we're just going to cover the basics here you can try it and that might be a little bit problematic now i may yes i think i am missing some stuff there we go so now we need to add the singleton so builder dot services dot add singleton it's going to be a single 10 of type gwt authentication manager passing the key so this is the constructor that we defined earlier then we're going to have our app.build we have to do one more thing here so right where it says app.use authorization we need to do before that app.use authentication what am i missing there you go and we have one error here see here oh it curated over so this is good so far and we're gonna just try to build a project right now looks good it built so we're going to try running it now this isn't going to authenticate anything currently because we haven't we haven't told it what to authenticate and what to allow to make calls without authentication so this should just work so if you have a get user info routing your database or in your api that makes a call to the database and you don't have any authentication that api is exposed anybody will be able to access that so that's of course an issue what we can do to fix that though so you can go to our controller and we gotta make a couple imports here so we have our asp.net core dot mvc we're also going to need the authorization and that'll just be for the routes for defining the routes and we're going to have we're gonna have two routes here so the first route is gonna be this one here this one we're already familiar with and then the second route is going to be an authorized route which we have to allow anonymous so first i'm going to say that this here route needs authorization so we're just going to enter authorize here after that we're going to create another route which is going to allow any user to make a call to it then it's just going to be http post it's going to return an iaction result and i haven't defined the user class here so or the model so we have to do that here first what we need to do is we need to create a token and before we even do this we need to add another constructor up here so what i'm going to do is i'm going to get rid of this here constructor i'm going to define a read-only jwt authentication manager instance and then i'm going to define a constructor it's going to take in an instance of gwt authentication manager i wonder if no that's spelled right i want to pause quickly just to clean this up i think i misspelled it but that is fixed now and what we're going to do is i'm just going to get rid of that start this here oh and i didn't finish i didn't finish this your stuff so we're going to go back to our authorize authorized function so to find our token jwt authentication manager dot authenticate we're gonna pass in the user uh the username and the password and if the token is null we're going to return an unauthorized status code if not we're just going to return okay with the token so if we try starting this we're going to try to make a call to just to get weather forecast 401 unauthorized that looks good now if we send a request to this here the authorized portion well first i'm just going to i'm going to try something that's wrong it's 401 unauthorized and i got to make sure that that's the password that i set test password and it looks like we may have had an issue here i'm just gonna pause and get that rectified okay so if you if you run into this issue uh like i said earlier uh the key has to be a certain length and my key was actually not long enough so i just added three dollar signs to this and it works fine now so i'm going to pull up that once again and it did return a key so once again if you try user it's not going to work because user is not set but if we do test we'll get a key so how do we make a call to the weather forecast controller here or to this uh to this get this get rid of this controller that's gonna be a little bit it's gonna be kind of difficult within swagger ui so i'm just gonna use postman so you can open up postman we need the port so 7203 and this is just weather forecast slash authorized okay i don't see any api reference there so i'm going to get rid of that i'm going to pass in some data here so the username is going to be user password it's going to be password so if i recall correctly this should not work especially if it's not the rate type of road okay i'm going to set the right stuff up here and then i'll be right back and here's a little trick if you don't know the exact exact route exact link you can just go on under the uh where the curl the curl call is defined so you could actually paste this into your cmd or terminal whatever you're using it'll actually execute this request so of course this did not work 401 unauthorized but if i pass and test we'll get a key so i'm going to copy that key going to go back to weather forecast and this is just to get i'm gonna get rid of all this form data so let me get rid of this token as well we try to send that request 401 unauthorized so you can go to authorization and we're just going to select bear token paste in the token and there's our data 200 okay if this token is modified we're going to run into an issue so we can write a script here we can write a script where uh once especially here this would be the better example once we are authorized we can write a script in pre-request script and define a variable so we define a global up here of ty just a string global and just name that key for example or token and then in our pre-request script we could set that variable when we call this authorized route and when we go to make a call to our we will make a call to this here i know or this authorized route like the route that requires authorization that token if you set it under authorization here so instead of doing that if you were to just do token and you've defined it then it'll it'll always be updated that's a pretty cool trick and one more thing if we make this call once again we do have access to that call here similar to swagger so if i open up get bash i paste this in shift insert okay we're running into an http issue but or an ssl certificate issue i should say but if you have all that configured you can just make calls within your terminal so that's pretty convenient sometimes depending on if you have this stuff installed or not so that just about wraps it up just remember if you want something to be authorized just add this add this authorize portion up here if you want any individual to call this just add allow anonymous but that's the basics so thank you for watching and if you run into into any issues just reach out to me see you all take care
Info
Channel: Kevin Gutierrez
Views: 29,980
Rating: undefined out of 5
Keywords:
Id: bRtCifC6JsQ
Channel Id: undefined
Length: 28min 32sec (1712 seconds)
Published: Sat Apr 02 2022
Related Videos
Note
Please note that this website is currently a work in progress! Lots of interesting data and statistics to come.