.NET 6 Web API 🔒 Read JWT Authorization Claims of a User (from a JSON Web Token)

Video Statistics and Information

Video
Captions Word Cloud
Reddit Comments
Captions
hello youtube my name is patrick god yes it really is and welcome to well the third episode in essence a third video regarding authentication with the.net 6 and the web api actually i was really thinking that we were done with the second video check out the info card please but you've been totally right of course i totally forgot to tell you how you can read the claims within your web api within your application maybe you want to check manually if the user is in the admin role maybe you want to read the name or the user id this is something you will do quite often i guess and now in this episode i will show you how to do that there are two options to do this you can use the controller and you can also use or serve this maybe this is a better practice well it definitely is a better practice fat controllers is not really a good practice but anyways you will see both ways here in this video and in essence i don't have to tell you more we can actually start already but first as always please consider at least clicking the like button maybe thank you very much but maybe you even want to subscribe to my channel this really does make a difference thank you so so much and don't forget to hit the bell i can to get a notification when new videos are uploaded additionally maybe you want to subscribe to my news letter with that you get early access and maybe also free access to upcoming online courses also soon ebooks i really want to try ebooks do you want to see an ebook maybe if you have an idea please tell me that in the comments thank you and last not least thank you so much everyone who bought me a coffee or a coffee for all your donations thank you so so much i will love you forever guys maybe you wanna donate as well i really need coffee i forgot my coffee here now as i can see but with a little boy you do not get lots of sleep and with coffee you can fix that a little okay long story short now let's start with the tutorial alright here's the project so first a quick recap again really really quick we've got a user's object we will not store this in a database this is only here in our web api this thing is stateless this means when we restart the application the user we register is gone and with register i already told you what we did here so first we've got a user object with a password hash and the password sort this is important because the user dto has the username and the password in plain text but with that this is a dto meaning a data transfer object so we send the username and the password to the web api and then we create this user object here and we'll store this in memory only because here we've got our auth controller and we've got the register method that takes a user ddo as a request a login also the user dto and so on we check if everything is correct if so we create a token and this is important here we will use this in this episode as well so we write the username and the token and then with the second video in this well now it's a series so in the second video we also added the cl the the role here as a claim which is admin now of course you can change this it's totally up to you and usually you would also add a name identifier claims or something like that maybe yeah and this would be usually the id of the user when you use a database but this just as a side note okay so we create the token recreate password hash and so on please have a look at the videos and the the github repository and that's pretty much it so we register users we log them in we create a json web token with this method here again this is important and in the last uh video so in the second one we also did one more thing here the weather forecast controller we use this example controller because when you create a web api project then you will get this weather forecast controller out of the box and here we added the authorize attribute with the role admin so only not only authenticated users but also authorized users meaning users who got the admin role could access this method here and then last thing for this recap what we did is we added for authentication purposes we added this big thing here this is necessary to read the json web token and for that you also need one key and this key is set in the app settings json again if this is too too fast this is the word i was looking for if this is too fast slow down playback or please have a look at the other two videos and then also here the middleware and app use authentication this was important and now to test everything we used swagger and to make the authentication work or to be able to send a bearer token to the with the authorization header we had to add this code here also install the new get package for this class here for the operations filter okay this for the recap and now as i already said in the intro there are two ways we can check the user claims in essence the first one is here in the controller as soon and this is important as soon as you use the authorize attribute in a method or in the complete controller then you should get an http context and the http context well has a user so let's have a quick look here and this is really dirty kinda well we already created a fat controller here meaning we have a lots of logic in this controller but anyways let's just continue with this you're here to learn something and not to build perfect apps for production if you want to do that maybe have a look at my courses just as a side note or just subscribe to my newsletter and then you will also get lots of information there anyways public and this is not async this time we just return an action result with a string let's just call this get me for instance this is our controller method this is now a get method http gets and we also add the authorized keyword here similar to the weather forecast controller where we also added this keyword or attributes and now also here so only authorized users can access this method and what you want to return is the username for instance get me is simply the username and we can do that with return user it's already there and then i identity and then for instance simply the name so this is a general way and let's let's test that already and we add the question marks here so visual studios i was hoping it is then happy with this oh of course we are returning uh action and action result here so let's change that a little bit so first we say the username is user identity name and then we return okay username and now let's add the question marks here because this could be null of course and this is really new with uh to be honest i don't know what is checking that if it's visual studio or dot net six or c sharp ten i think visual studio please tell me if you know this these null warnings here get these a lot with my code so i really should add some more nut checks anyways so this is our really really small controller methods http get attribute the authorized attribute it's not async it doesn't really matter here and we return an action result with a string and the string should be the user name again double check here in the create token method this is the thing we want to return so we have this claim here with claim types name and then we add the username here we could also return the role for instance we do that in a minute but first here user identity and then name of course there are other ways not only two but i think these are the most important ones but let's check that now you run the application and in a minute you should get access to swagger i think this is already the app of course no that's not what i wanted here now when we try this we should get an un authenticated correct 401 we are not able to use this method now this is because of the authorized attribute so let's register a new user and this time not let's not do string it's spider-man spider-man wants to register with the password string why not and now in our login method we test this one as well we use spider-man here hit execute we get our json web token so this is important now to use here and now we can use this method hit execute and we get spider-man that's it so we get already the username and you can do that with everything in essence with every claim you added in your token to maybe make this a bit more precise let's add a username to and then what we can do is we use the user object and then the method find first value and here you can specifically define or use the claim type so claim type claim types how to pronounce don't know why not names name and let's say we also want to get the role so let's also add the role here we return now an object this is simply a new user name username two and the role for instance something like that and yeah we should now get the same name twice and the role of the user and let's just restart this manually here okay there we are we register okay let's use the boring string name here to make this a bit faster and now we log in again all right we use that token hit authorize bearer close and now off and now try this out execute and we get the object here username string and string and then the role admin all right so this is actually how you do this but it's not best practice and i want to show you now the other method i meant which is using a service because then in the service kind of using the repository pattern here so you have a controller you don't want to use fat controllers you want to use services that you inject into the controllers with dependency injection similar to the configuration here and then there in the service you want to add a method to get the username for instance to be able to do that you need again the http contacts but it is not available in the service by default this is only the case here in the controller so how would you do that first let's create our new service let's add a new folder here call it services then another folder let's say this is the user service and in here now we add an interface interface i user service and also an implementation class of course user interface which implements the i user service interface now to be able to inject this we have to register the service so we go to the program cs and for instance up here we say builder services add scopes and then i user service user service like that real quick i know this is a really crash course here crash course crash course and we go deeper in user oh this is the problem when you want to do things really fast so use a service yes we call this user service and now this should work okay great all right we've got our user service and where's the uh there it is the namespace let's make this global so we don't have to add the reference in the auth controller for instance if you want to use it here we go much deeper in our jumpstart course for instance but um for now i think even if this is pretty fast and it don't explain a lot i think you get the idea and you know how this works and i hope that you can then solve your problems with the with the claims here so anyways we've got the i user interface let's add a method returning a string just for the username get my name for instance and in the user service here we also implement this and now the thing is we already need the http context for that we go again back to the program cs and in here now we can add the http context accessor with add http context accessor and the tooltip says it adds a default implementation for the i http context access service so if you don't want to use the default implementation write something yourself but this in most cases i guess is totally sufficient with that now we have the option to inject the i http context x as a service so let's go back to the user service here create a constructor and now in here we say i http context accessor call this http context accessor for instance and we create and assign the field http context accessor and now here for instance because of the null checks we first say we've got a result which is string empty lowercase and now if the http context access http context is not null then we set the result to http context as access of the http context and then the user object and in here now in essence we get the same stuff we already got in the controller so for instance we say here now find first value we have to add a reference here system security claims and then we can say claim types and then give me the name here please all right and then we return the results all right and with that now that was the wrong shortcut with that now in the auth controller we inject our i user service call this user service and create and assign the field yep this looks okay i guess wait that was the wrong one did not look correct again the user service not the property we want to use the field here this is what i wanted and now let's say here in the get me method we say our username [Music] is user service get my name and then we return okay [Music] okay username all right string and on comment this out or just yeah leave it here because when i check this in then you can have a look again so again let's let's just save this and restart the app manually so we injected the user service here we uh use it here and return the username and let's try this and then we again add a little recap here so you know what we actually did all right so where's swagger there it is let's let's reload this and then register with the new user this time this should be iron man hit execute then we log in with iron man execute that's our token we authorize authorize close and now drum roll we try this out and execute iron man that's the one okay so this worked just fine and now a short recap again i think the the controller stuff you know this now we recommended this out you can use the user object here because the http context is already available i think when we go to the controller base class here is it here oh jesus yeah first the first hit actually okay so here you got the the http context and from that you get the request and here this is this thing i was looking for claims principle user and of course you can go down the rabbit hole here you've got the claims and so on the identity object this is what i wanted to show you so we inherit from the controller base class and this is why the user is available here in our auth controller and then you can access all the user stuff but again really really important this only works with the authorized attribute so only then the user is available and of course the user can only have access to this method so make sure you use the attribute either here or above the controller class and then you can access all the user claims but if you don't want to use a fat controller meaning you want to use a service with the repository pattern with dependency injection and so on then you have to add some more stuff this the first thing actually is you have to add the http context accessor in your program cs now with dotnet 6 in dotnet 5 and below you had to do this in the startup cs file but now it's in the program cs with that you get access to the or you are able to inject the http context accessor and then what we did a better practice than just using fed controllers is we created a services folder with a user service and we had to register this thing as well as a scoped service here and then in here well we got our interface and implemented this method here where we use the injected http context accessor here in the constructor and here now we access the http context and then it's exactly the same as in the controller and that's it let me check this in real quick get user claims with http context accessor is this the right spelling context accessor yep that's correct commit all and push all right nice yep that's it pretty easy right so you've seen both ways the controller and also the service way with a better practice and i really hope you learned something with this little video here if so please consider giving me a thumbs up maybe even subscribe to my channel would really mean a lot to me thank you so so much consider subscribing to my news letter to get free stuff to get early stuff to get ebooks whatever i promise i won't spam you at most i send an email once a week and last not least again thank you so so much for all your coffees your donations maybe you wanna donate as well would really love that and it would really mean the world to me so thank you again very very much for that i need more coffee this is a fact well and now i can only say thank you very much for watching and i hope i see you next time take care [Music] [Music] you
Info
Channel: Patrick God
Views: 36,250
Rating: undefined out of 5
Keywords:
Id: fhWIkbF18lM
Channel Id: undefined
Length: 23min 55sec (1435 seconds)
Published: Tue Dec 21 2021
Related Videos
Note
Please note that this website is currently a work in progress! Lots of interesting data and statistics to come.