.NET 6 Web API 🔒 Role-Based Authorization with JSON Web Tokens (JWT)

Video Statistics and Information

Video
Captions Word Cloud
Reddit Comments
Captions
hello youtube patrick god here and today is all about role-based authorization well you know this already because you read the title and clicked on this video again this was a request by you guys and of course we will implement this in essence this is a part two of a video i already created the json web token video check out the info card please because then you will get the code base you need for this tutorial now but if you already know all that then just continue watching i've also recorded a short recap as i already did the code part and now i'm doing the intro and the outro sometimes this just works better for me anyways role based authorization is the thing we're going to do today and there's not much to tell you actually we can in essence just start with the tutorial already but first maybe you want to subscribe to my youtube channel and click at least the like button and don't forget to also click the bell icon to get a notification as soon as i upload a new video it does make a difference so thank you very very much for that also maybe you want to subscribe to my newsletter in that case you would get informed about videos like this one here and also about new upcoming online courses and i'm also planning to create some ebooks workbooks anyways when you subscribe to the newsletter you get some stuff and i promise i won't spam you at max i write an email once a week and apart from that thank you so much for all the coffee and just a side note i added or created a kofi page if you don't know what kofi is it's in essence similar to patreon or buy me a coffee but there you can again donate with paypal not possible anymore with buy me a coffee that's really really sad but with kofi maybe you want to support me as well i would really appreciate that so thank you again very much and now i stopped talking about that and i would say we start with the tutorial all right a quick recap first here you can get the base project in essence that's the first part where we create a register a registration user registration a login and with a json web token so please if you don't have your own project and you need some base coat and uh don't want to start all over then well just get this project here check it out clone it and then start from there because then i close this now and this is the project here and it's actually really simple what we did here is we have a user object with a username a password hash and password salt also user dto by the way if you already watched this video here again please check out the info card for the first part in essence um if you watch this already then have a look at the time codes and then you can of course just skip this and start with the actual tutorial we have a user model we have a user dto the user dto uses the username and the password in plain text to log in and to register in essence so we use this dto for both and then we've got the auth controller here um please note that we don't save anything here persistently in a database this is really a quick tutorial so when the user registers then we have this static user object here and that we will then set or create with the username password hash password sold and so on and then we've got the login method so if we do do not restart the application then we can log in with the same username and password but if we restart the app then of course this is not working anymore we have to register this user uh any every time just for this example here and what's happening here well maybe you should really look uh or watch this the first video we create the token with some complicated code here it's not that complicated it's just it's the way you do this actually custom json web token authentication with dot net 6 and the web api and maybe one thing i should tell you also here is the secret token and this is also important for this tutorial now uh here it is my top secret key make just make sure that it just has at least 16 characters apart from that it can i think have any character and that's actually everything we did so registration logging in and creating the json web token and in here i think we just used the default code we haven't changed anything here i did maybe i should watch the video again but i did not anyways let's test this real quick and then we will start with the other implementations for the authorization and the role plays a role placed placed doing too much blazer lately maybe the role based authentication okay so this is uh the the first part of the tutorial again we can register here just hit try it out maybe just leave the example here so username password is string string we execute and then when we go to login there it is try this out same username same password then we got our token and the neat thing is now we can already or also check that on the website jwt dot io that one here and we enter it here for instance we get well the information of our code for instance also the expiration date and also the name and again the name was set here in the auth controller when we create the token and this is also important for this tutorial now we will add another claim i can already tell you the role is another claim and we will use that all right so so far the the code base we have for now and now let's start with the role-based authentication well before we can use the roles we have to add some other stuff funny thing is that we can actually use this example here the weather forecast controller because now the app is still running when we have a look at swagger ui we can just call this thing here hit execute and get these random weather forecasts right but now how do we prevent that how can we say that only authenticated users should be able to make this call well it's pretty easy we just use the authorized attribute here and for that i just pressed ctrl period on my keyboard and then we add the using directive microsoft experience core authorization and that's it that's it already you can add it here or you can add it in the controller so add authorized here for instance authorize authory not bad authorize and the other way around would be if you wanna save or secure your complete controller but there is one method where you would say okay now you really don't have to be authenticated or authorized to call this method anyone can do this or see this then just add a low hello allow well it's late again sun is asleep you know you know the drill right so allow anonymous by the way if you don't know the drill i have a little toddler and i i'm creating all these videos when he's asleep and you know it's not much time usually so uh let's do this quick and while doing this some errors happen but i think that's totally normal and maybe also sometimes good to see anyways allow anonymous this is then the other case you know again the controller is secured but you wanna allow this method to will be accessed by anyone but let's uh undo this and also the attribute here above the controller so only this method now is authorized we save this again and to be really sure let's restart the app manually and now when i click try it out and execute i get an error actually so i do not get what you would have expected maybe 401 not authorized we get a response status for uh 500 it's in essence an internal server error but here it says inverted operation exception no authentication scheme was specified and so on so you see we have to do something here we have to add an authentication scheme and also an authentication middleware the one of net itself and the authentication scheme now is necessary to validate the json web token in essence and yeah i would say we just do this i have a script this time well it's not really a script it's just it's just a little cheat sheet in essence because this code cannot remember this so uh i have to look this up okay but this has happening in the program cs and now what we're going to do is we write builder services add and then authentication and then we add our scheme here let's close this first this thing is called jwt bearer defaults because it's about a jwt bearer token and then here we say authentication scheme and we need something here a new package so microsoft asp.net core authentication jwt bearer it is please install this package yep latest version is fine and yes i know we have some errors so we will edit this now okay so this is installed that's nice and with that now we use another method actually this was just wrong we add the method a add jwt bearer and this thing gets some options options all right and now the options please stay with me a bit tedious at times first the token validation parameters these are new token token jesus intellicode can validation i don't know what's happening here token validation parameters i really don't want to use the namespace here i want to edit here so new token validation parameters and this thing now gets also some parameters and this would be at the semicolon first validate issuer signing key right issue signing key that's the one this should be set to true and what is the issuer signing key actually well again the thing from our app settings json file so new symmetric security key and then encoding jesus encoding utf-8 we need the system text namespace here or the reference and utf-8 sorry that was the mic utf-8 and from there we get the bytes of our builder configuration get section app settings token and from that we want to get the value again that's this thing here right this is right this is the the section app settings and from that then the token of course there are other ways to save this there is an option to use a store or you just write the key in here i don't care do it the way you want to do it right but i think that's it's a good practice maybe not the best but it's a good practice to do that or add that in the app settings i mean in that case you can change the key for i don't know a development environment productive environment but again of course there's also the store option anyways just make sure to use a key here for your json web tokens all right and then we've got a validate issuer it can be set to false and also validate audience could also be set to false and this should be our scheme now and additionally we add the authentication middleware so app use authentication enables authentication capabilities so do that please and make sure that this is above the uh use authorization line here okay and then this should work let's save this and restart the app and then i don't know if it has been restarted already but let's test that try this out hit execute and now that's correct response status is four oh one so we are not authorized to make this call or get the result here nice so far so good now the thing is we we have to do something here right and the thing we want to do is why we're using the json web token is um we want to add the token to the authentication header of the call you can see here this is simply creating a get call with this uri or this route and what's missing is the authentication header now when you have any kind of front end already laser web assembly for instance or angular or react whatever then i think you already know how to do this you would just code it you would write your code for the authentication header and angular you're using in inceptor for instance in blazer you're using the authentication state provider and so on other option would be using something like postman to test this call and there you can configure the authentication header but with swagger ui you do not see an option here out of the box to add this authentication header so we have to add something to our code again and well let's do that let's do that again in the program cs this line now is important at swagger and gen and this thing now gets also some options so with these options then we will get a little button where we can set our authorized or authorization it is called authorization i think or we give it a name we give it the actually we give it the name and then we can add the authentication header long story short let's just add the options here so options again the curly braces and then options add security definition [Music] this would be [Music] oauth 2 and this is a new open api security scheme i just updated visual studio and i do not know if this was a good idea oh my gosh okay all right i can please the reference don't like to see this these long name spaces in the code really so um yeah i rather i'd rather use the uh the references on top but anyways and this is uh a different topic all right so we've got the open api security scheme and this now gets a description and just for you guys into some text now this would be for instance the standard arthurization header using the bearer scheme so this would look like that for instance bearer and then wait i have to escape this bearer and then the token all right something like that i guess okay and then the in parameter so where should this thing be set this would be parameter location header and then the name is authorization and then we need a type and this is security scheme type api key okay that's that and then one last thing we add options and then we have to set an operation filter and there is the security requirements [Music] operation filter and to get this we have to add a new get package i don't know if it knows it oh yeah nice already gets it so we have to install the package swashbuckle asp.net core filters and kudos to matt fryer i guess is the correct name freer sorry kudos to met freer that's the name mad freyr please google this guy he created this so [Music] great guy i hope you installed the package now and then no we didn't now we should install it yeah just stop the app jesus and after the installation maybe it now gets it all right oh edit the using directive already nice all right so we've got our [Music] our security definition and the filter here and this should do the whole trick here we should be all set so again let's start the app and fix the error okay there is a comma missing push that was hard but it so let's open chrome and there we are and you already see something here right there is this beautiful little icon and this opens now a little uh dialog that's the correct name you see our description here that's nice right the name and it said in the header and so on but to get the key first we register hit execute and then login try this out hit execute copy this thing and now i'm really excited first let's try it without the header right try it out hit execute doesn't work alright and now we set bearer don't forget the the term here that the text bearer space and then the actual token all right hit authorize and then close we see now the lock is closed we hit execute and we're getting our calls uh weather forecasts we can make the call and we get the weather forecast and here you can see the authorization header i think i said authentication header but that's not the correct term let's have a look at the network tab here execute a and i had a header yeah it's the authorization header sorry about that the authorization header now not the authentication header there we set the token and now we get these things back that's nice right but still there's no role in here and you are here to see the role-based authentication so let's do that now and to do that it's really i think it's almost always with software or web development when you know it it's easy and simple or it's simple but not always easy authorize and then we can set the roles like that so for instance we only want administrators to access this call save this and now restart the app and now you see we have to enter our token again it's still valid of course so let's hit authorize but the problem is now we do not get the weather forecast and you can see here now the response status is 403 forbidden not 401 unauthorized it's now four or three forbidden so this really means we do not have the role and again here's the token and there is no role in here now we can change that here when we create the token so let's just copy this line maybe first let's use the the role that is not allowed to get the weather forecasts i don't know noob maybe so a noob is not allowed to see the weather forecast but an administrator is and with that when we test that now we should see a token where we actually see [Music] this a role now so let's register again hit execute and then we log in we have the role here and we enter this here we have the token here and now we see the role noob and when we try to get our weather forecasts we get an un authorized now that's interesting okay i okay this is really interesting you did not see that before so when you have no role then you get a forbidden but when you have a role but it's not the correct one then you get an authenticated unauthenticated unauthorized sorry okay nice why not it's good to know that but now let's finish this so the user we're creating here gets the admin role again let's double check this is the necessary role here and we just to be really sure restart the application and now we register we try this out hit execute and register the user and now let's login try it out it executes let's check the token you see this role now here admin and now drumroll i know you're really wait a sec ah jesus i forgot to set the token ah i'm so let me let me just i really want to know this so as i said these arrows happen all the time again the noob we restart the app it's restarted it's it's it's fast so please that's okay we login try this out hit execute do this again and now we set the token here authorize and here now we see [Music] 403 that's what i was expecting okay now everything is correct so really with no authorization header set with no token we get the 401 bag and with the token we get the 403 if we do not have the correct role and now we set this to admin and restart the application and now again register execute then we log in hit execute we get the token entered here we have the role we set it here and authorize close and now drumroll what do you expect try it out hit execute and we get our weather forecast yay because we're admins isn't that nice in essence this is everything this is how you would implement role-based authentication and of course i will put this to github let me push this now where's the code here it is again the changes so we can also recap what we actually did an important thing was of course the claim here there it is let's add the claim and the create token method then we've got the weather forecast with just the attribute with the roles and then we added two packages microsoft asp.net core authentication jwt bearer and the swashbuckle asp.net core filters again this is not really necessary if you do not want to use swagger ui so you know just as a side note so actually if you just have a client and you want to use role based authentication with net really don't have to use the swashbuckle package here and in here now now this was of course really important again for swagger the swagger gen options configuration but then to be able to use the token in your controllers you have to specify this scheme and then also add the this line here use authentication okay and this is everything edit row based authorization commit all and push all right yep that's it was really quick actually doesn't take lots of time to create role-based authorization of course we did the first part in another video but still with these two videos then you know in essence everything you need to know to create json web tokens or even register users log them in create json web tokens and then use these json web tokens with a role based authorization and again if you liked the video please consider subscribing to my channel would really appreciate that or at least click the like button maybe thank you very much for that don't forget to click the bell icon to get a notification as soon as i upload then there's also the newsletter again maybe you want to subscribe there for new videos upcoming videos courses and now maybe also ebooks workbooks stuff like that and the last thing again thank you so so so much for all your donations your coffees and coffees check out the new link maybe i really love you guys means a lot to me thank you very very much and now again thank you very much for watching and i see you next time take care [Music] [Music] you
Info
Channel: Patrick God
Views: 81,324
Rating: undefined out of 5
Keywords:
Id: TDY_DtTEkes
Channel Id: undefined
Length: 30min 30sec (1830 seconds)
Published: Tue Dec 14 2021
Related Videos
Note
Please note that this website is currently a work in progress! Lots of interesting data and statistics to come.