.NET 7 Web API πŸ”’ Role-Based Authorization with JSON Web Tokens (JWT) & the dotnet user-jwts CLI

Video Statistics and Information

Video
Captions Word Cloud
Reddit Comments
Captions
so you've got your Json web token and now you want to use it to authorize a user so how would you do that and how would you actually use roles with the help of Json web tokens in a web API let me show you how this works in this tutorial alright so I've got a default web API project here with Visual Studio 2022 and a.net 7 web API and I did this in the tutorial before links in the video description but this is not very important for this tutorial really here we create a Json web token but we can also use the new user JWT or user dots CLI offer.net7 later on in this little tutorial here to create Json web tokens and test them then important for now is let's just secure this default example weather forecast controller shall we because when we run this application this is from the last tutorial here register and login a user but here now where the forecast we try this it execute we get some data here now what if I wanted to secure this method here well in essence this is really really simple we can just add another attribute here which is called authorize and as you can see now this reference was added authorization now this means see it here it specifies that the class or method that is that this attribute is applied to requires the specified authorization so this also means that we can actually put this thing up here for instance just add it here in these brackets or as a new attribute here on top and then when we for instance secure this complete class we can also say now this specific method is available to everyone should not be authorized in essence and then we can say allow Anonymous and that's that and now for the roles let me already tell you if we add the authorize attribute here then we can add some parameters or properties as well so you see it here there are also authentication schemes we can add a policy for policy based authorization also very interesting and even roles so this means something like rolls and then for instance only an admin can do that this is already everything you have to do and then this method is secured and and you have to be an admin to be able to access this method all right now this is just about securing this thing but if you do that it is still not really working we have to use the Json web token and tell our API how to work with this Json web token now the great thing again with.net7 is that this whole thing is a bit simplified not that much really they wanted to tell you that but let me just show you this step by step first we have to add an authentication scheme and how would we do that well we say Builder Services we register a new service and in this case that would be authentication and then here for a default JWT or dot authentication not sure about this turn shot I I rather like JWT actually then we can add air at W J WT Orchard and Bearer no Visual Studio is not knowing what's going on here so we have actually to on my case I had to install another nuget package I don't know what about you but we can use a little trick here JWT better defaults and then we get the suggestion to install this package that we really need Microsoft asp.core authentication JWT Bearer we find and install the latest one and that's that and why why am I using this trick well if you want to look at my.net 6 tutorial about the same thing here then we had to specify this manually so we had to choose the JWT better default authentication scheme and now this is done with this line here at JWT Bearer and that's that all right this is in essence everything before also what we had to do too is we had to add another middleware here use authorization is still here actually this is also not necessary for instance if you want to use minimal apis then you would I think you would not see this line anymore and again in.net6 we had to add use authentication not user use authentic application that's the one see here as the Microsoft authentication middleware but this is not again not necessary anymore so this is everything you need actually you would think that Bots this is a big but in my opinion this works when you only use the new CLI for instance the user judge CLI let me let me show you what I mean by that see it here I tested this already a little so we can actually use a.net user and then jwts and then create and with that we create a new Json web token and we can actually just copy this thing paste it everything's working hopefully let's just have a look with a.net uh user JWT print then the ID and also let's add show all hope that yeah that's the right command here and with that you can also see what this thing is actually doing right it's the name the scheme default scheme Bearer ads audiences an expiry date no roles that's a lot of stuff and also interesting really is I don't know what's happening here maybe you have to rebuild this thing what's interesting is that here now in the app settings development Json this command already the creation of the JWT of the token I created also this section here all right so this now as you can see it here valid israel.net user dots is now I use the term myself this this is for development purposes this is fun fun and simple and it works really fast but the issue I have with that and this is just the current state of my knowledge here maybe you know something else I'm pretty sure you know more than me when I have a look at my create token method here again from the other tutorial I am using the symmetric security key here and assigning an issue assigning key and here now I know this is not the most secure way for production maybe you wanted to use the Azure Vault for stuff like that and here I added the in these app settings Json file in this file I added the token my top secret key again not that secure I'm I'm aware of that but with that I make sure that I am adding an issue assigning key and then here in the program CS we also have to tell our application to verify the the Json web token with the signing key I don't know why but this did not work in my case when I used these Json web tokens here and this is really strange because it actually uses a signing key as you can see here when you enter.net user dots and then key this is the signing key and when I enter.net user secrets and then list there you see it as well so what I actually can do is I can copy this thing and then enter it here right this would work and then it uses this specific key to create the token and then when we tell what we'll do in a minute so that it took so long but I think this is really important when we then tell our application that it should really use this specific key to verify the issue signing key then this will also work but it does not work when I'm only using this this token here what's sad because I I was hoping that I didn't have to specify anything here and it would just work out of the box we've got the proper signing key here and so on I hope you get the idea now this is this is really unfortunate but anyways let me just show you what is going on now in our application when we just add the authorized attribute but let me close this thing first and maybe rebuilt this solution here and hopefully we can fix that um nope nope okay just a sec again okay the package is gone again all right [Music] and defaults that was our little trick here and start it again I don't know what I did I'm sure you know but I somehow uninstalled the nuget piggage all right funny thing is that I don't need the reference here anymore and it still works all right anyways let's just run this thing there it is and now console is open again let's just reload and when I try this out now it's telling me 401 unauthorized all right so this is not working now but again we can fix this the thing is we have to provide a token now in the authorization header now how would we do that well we could use simply something like Postman for instance or insomnia any rest client testing tool to do that here for Swagger UI we have to configure this thing a little bit so how would you do that well in Ed's Burger gen we add some options all right so here now we write give me a sec I have to look this up options and then add security definition let's call this o auth2 for instance and then new open API securities him not almost let me just add the reference I don't like these long names here we have to also add something here as well so first brackets or the braces curly braces and here now yeah I wanted to add the using all right so first this and now here we can add a description if we want to but important is where we want to use this new parameter so the parameter location is the header then the name this authorization and we need to type which is security scheme type API key and now one more thing we have to add an options filter operation filter this thing and this thing is called security requirements operation filter and we can also install this new kit package here swashbuckle aspin core filters find and install the latest one and with that now we can actually enter a Json web token see that this is a new button it wasn't there before and we also see this little lock icon so now we see that uh this thing is secured right it execute nothing's happening and here it is opening in essence the same thing as here so what we have to do now is we have to provide a better token so Bearer and then the actual Json web token so now let's go back and here now what you can do let me just grab this token here all right hit authorize and with that then when we execute this thing we get see it here we set the token to the authorization header and we actually get some data right isn't this just crazy already works again issuer signing key is not verified all right so not that important for now maybe I wanted to show you something about roles so how would you do that real quick the.net web academy starts soon it's an online program where we cover all things.net web development with blazer git Azure and more pretty much everything you need to know if you want to land a job in the.net web development world and also the exclusive.net Web Academy Community for all your questions and if you want to be the first to know when it opens and if you want to get a discount then make sure to subscribe to my newsletter or check out the link below to get a spot on the waiting list thank you very much and now back to the tutorial again we can go back to the weather forecast controller and now here we add a rolls and then for instance admin save this restart the application there it is restarting again we add a token the one we just used hit authorize close and now we try this again with result execute and 403 Forbidden we do not have the the role isn't that sad right and now again if you want to test this with the new user dots CLI what we can do is we create a new um in your token and now I actually I'm not sure if it was a roll or rolls so help me roll all right so now we just say roll and then admin then we've got a new token it's telling us that no it has the role admin in it and now drum roll Para new token we hit execute and we get the data isn't that crazy all right so this is really really nice and this is already how you would do that and you can actually add several roles if you want to use them um here to secure something just by adding a comma and then add the user role for instance right so now if we save this again restart the application and here now I just want to use the user Row for instance can copy this thing and then at Sear authorize close to try this out and execute still box nice huh so that's that and if you just wanted to know how you would do that then you can stop watching but please keep watching because now this is really important in my opinion again I know I'm repeating myself but we have to verify this signing key and how would you do that well again we have to add something here and in this specific case what I want to do is I wanna validate the issue assigning key we set the issue signing key here in the options and also we have to set the the the Boolean value for validate issuer and validate audience all right so this is just something to take into account and how would you do that well it is well there are some options we have to set and in here now we say options token validation parameters and these are new token valid almost validation parameters like that and we use this reference here and now validation is not very very dates issues any key set to true let's say validates audience is false again just for this tutorial learning purposes validate the issue also false and now our signing key is a new symmetric wait can I just copy this actually um a new yep that's the one so back to the programs yes uh almost here it's the uh Builder Builder come on configuration Builder configuration and wait a sec nope this was necessary yeah and the semicolon so now what we're doing is we're telling our API again we want to validate the issue assigning key not the audience not the issue why did I do this that way because I didn't set it here so that's that but if you I don't know want to use the again the user juts for instance and you want to use these audiences in this issuer then you can set this to true if you want to just play around a little with that really recommend that best way to learn actually and now here regarding the issue assigning key again we are using the app settings token and also here app settings token and again this thing can be found here source code available in the video description on GitHub so let's save this now and restart the app manually if you're wondering why it didn't uh set hot reload on file save or I did not activate this well it simply crashes lately a lot so I don't know what's going on there maybe the new visual studio version I have no idea why it is anyways we well no I have to copy this token again I think yeah I do and then back to our application where's there it is we uh just just reload this thing and now here again we say Bearer and this is again this is not the user jots generates its token and I'll run this telling me the following the signature key was not found what the heck right so this means that in this token in this Json web token there is no key but again strange don't know what's going on here actually when we go to jwtio we can test this token and here you can also see some stuff right and um here we can actually add a key and again if I'm doing complete BS here please send me that in the comments I just think this is this is this is interesting and complicated here's my key so let's just copy this say okay this is basically for encoded I paste this thing and now we have to paste the token again because uh jwtio changes the token here when I change anything here see that ah now it's gone again oh come on so I think that that was the right one right T secret no wait a sec uh just a sec here again we copy this paste it here yep that's correct and now again give me the latest token that's the one and we paste this thing again yeah and now you see it was pretty much the same and it tells me signatures are verified so somehow the key must be there but uh so this means maybe it's not the the CLI tool here user charts but maybe something in the application I have no idea what is going on there but what I do know is when I'm using this method to to create a token and then I try to verify it here again with this yeah I call it token maybe I should call it token it's just it's the signing key then this works so let me just show you this by restarting the application one more time and then we just register a user try this out and because there's a Series going on currently or running that I really love I'm using this username and this password and now we created this new user now I can say log me in with jowl and Ellie it executes now I get this thing here maybe we can just copy this and what happens now when I enter this here Vera authorize all right drum roll you know it won't work right because we don't have the role but it doesn't tell us that the key is not there anymore so what we have to do now is we want the user to have and either the admin or the user role or both and we can do that real quick in the auth controller by setting a new claim so here you just say roll admin and why not uh roll I'll use the right thing Jesus this is the string here all right our admin and it's just everything so now also user and we save this one more time restart the application there it is again try this out troll Ellie and execute and now here we log in again control Ellie execute we get the token bigger now you can double check on jwtio actually all right so we paste this thing here and we see both roles all right that's great and now here weather forecast oh wait we have to use the token here bearer all right authorize close and now execute and we get the data isn't that great and now the next step actually is how would you read all this data in your Json web or from your Json web token in your API in your web API or any.net 7 application well if you want to know that just click on the video here on the screen
Info
Channel: Patrick God
Views: 15,471
Rating: undefined out of 5
Keywords:
Id: 6sMPvucWNRE
Channel Id: undefined
Length: 25min 50sec (1550 seconds)
Published: Tue Feb 14 2023
Related Videos
Note
Please note that this website is currently a work in progress! Lots of interesting data and statistics to come.