Angular 14 & .NET 6 🔒 Authorization with JSON Web Tokens (JWT)

Video Statistics and Information

Video
Captions Word Cloud
Reddit Comments
Captions
hey friends it's me patrick god thank you so much for tuning in and today you already read the title we are covering authorization and authentication with angular14and.net 6. now if you're already thinking well authentication and authorization with dotnet 6 this is something that i'm really interested in well i've got good news for you check out the link in the video description or the pinned comment because with that you get access to my authentication and authorization with net 6 course on skillshare for free yes that's true just click on the link and then you get one month free of skillshare and then you can also check out my course and all the other stuff that is available on skillshare because what a coincidence this video is sponsored by skillshare and i am pretty sure you already know what it is but if not skillshare is an online learning community with thousands of inspiring classes for anyone who loves learning and wants to explore their creativity and learn new skills like programming for instance invest in yourself and your personal growth if you have a specific skill you're trying to learn skillshare is the perfect place to start from not only programming or web development but also photography and illustration to graphic design freelancing productivity and more you can find classes that will match your goals and interests like the ones from marcus brownlee regarding youtube for instance because i'm doing that stuff here i like this course very much or the productivity classes of ali abdal and thomas frank again i just love that and of course again you can also get my course on skillshare about authentication and authorization with net six here we cover json web tokens roles and refresh tokens so maybe you want to have a look and the best thing is the first thousand people to use the link in the video description get one month free of skillshare so what are you waiting for just head down to the video description and grab your free month done all right thanks for that and now regarding this tutorial we will actually focus on the angular part because the net six part i did this already in another tutorial check out the info card or again the link in the video description because there we will create this backend project the web api with the function to log in to register and again to create a json web token and return this thing and then we will also have a function that can only be accessed by authorized users right so we have to provide this json web token then and then the web api will check if this user can actually access this method and now we do or use this backhand and write an angular 14 client application for that a teeny tiny application of course so again we will focus on the angular part here but regarding the back ends we will start with the actual github repository and then i will talk about that back end so what we are actually doing there so please bear with me i rarely do this with code you just have to copy or download on git this time this tutorial would be exactly the same so i thought well we did this already together and you can just grab the code around the application we changed one little thing there sorry that i'm talking that much today in the introduction but actually that's really important so we changed one thing there the back ends was just used with the swagger ui meaning we just tested all the web service calls and the authentication part and it worked but if you now want to use an angular application then we get a course issue there so we have to actually add this to the backend well i did this while recording that so when you now grab the github repository it is already pushed so actually you don't have to do anything there you just grab it start it and then it should work but if you want to learn something then i guess would be nice if you watch that too so this is the backend part and then again in the angular part we well we implement a really pretty form a tiny form with the username and the password and then three buttons to register to log in and then to use another method where we then call another function where the user has to be authorized again he or she has to provide the bearer token and for that we use an http interceptor and maybe this is the most important thing and if you just want to know how to build this interceptor then check out the time codes there you will find that all right that's it for the introduction if you liked this video and learned something i would really appreciate it if you click the like button maybe you subscribe to my channel and for more.net stuff in your inbox and upcoming courses then maybe the newsletter might be something for you i'm pretty sure it is so head down to the video description and subscribe to my newsletter thank you so much and now enjoy the tutorial all right now let's start with the dot net part here because this actually already exists you can see it here on github and if you're only interested in the dot-net part of this tutorial please have a look at the link in the video description because there you will find the actual tutorial for json web token authentication created or done in dot net six and this is the github repository for that i rarely do this in my tutorials usually i really create all projects from scratch and we will do that with the client application with the angular client application here but regarding.net i think i already did this and it's exactly the same thing so i think it it makes sense to either have a look at the tutorial or you just get the code here from github start the application and then we focus on the actual client implement implementation and the client application with angular 14 and there we will create our login method register method and also use an interceptor to send the the actual json web token with every request so this is the goal now here you can see it this is the link you will also find the github link in the video description so please get the net code and when you have it and you start the application there it is or not the application the solution here with visual studio 2022 totally free so don't worry about that this is the community edition let me just explain this a little bit so what we see here is first we've got a user dto we will use for our login method and our register method and then we also have a user entity with the username a password hash password sort and so on even a refresh token now what we do with that stuff is we'll have a look at the auth controller now i know this is a fat controller but i don't care in this case it makes sense for this learning tutorial here and the very first method we implement is the register method and in this method we create a password hash with also a password sort this means this password salt is just a random sequence as you can see down here all right so we're using an algorithm and i won't go into deep here again if you want to see that please go to the other tutorial but we will use a cryptography algorithm here to create a password salt and the password hash and with that to create a password yeah a password and a password hashed so the salt mixed up with the password given by the user results in a password hash and why do we need assault well the thing is if we would use the same algorithm over and over again without assault then the same plain text password would result in the same password hash every single time and well that's not very secure because it already happened that uh clever people can get the plaintext password from the actual hash value but with the password solved and mix it up with the password this hash value is different even if the plain text password would be the same so we store this salt usually then in the database together with the password hash and then we can get to the plaintext password and so on or not really to the plaintext password but we can then check if a user tries to log in with the given password here and then we grab this password and the salt then from the database run the algorithm again and we get a new computed hash and then we just compare the password hash and the computation if this is equal then the user used the proper password i hope this was not too fast again please have a look at the other tutorial otherwise so we have this register method and with this register method we use our user dto you already have seen here we only need a username and a password for that and then set the username password hash password sold and more stuff actually later to this user entity but this again the user entity is not really important for us and we will use in our angular application only the user dto for the registration and logging in and regarding logging in this is how this looks we uh get again a user dto provided by the the user who tries to log in with the username and password i know you shouldn't do that in production meaning tell the the user or potential attacker that the user was not found or that the password is wrong please in production just use one error message in essence one one message that tells the user that either the username or the password is wrong because otherwise uh potential attacker would know that oh this user here exists so only the password is wrong and then we he could start he or she could start a brute force attack for instance to get the proper password all right now with that then we've got the login method but here comes now the jwt the json web token magic we also have a function called create token won't cover refresh tokens here in this tutorial we only cover the the json web token part here and this again is explained in detail in the other tutorial and also the skillshare course of course so if you want to have a look there please check out the link in the video description as well or in the pinned comment to get your free month of skillshare and then watch my course totally free for you in that case isn't that nice so here in this function we create so-called claims and with these claims they can be a name a role the id and so on and important for us in this tutorial is the user name because this is what we want to see later when the user has logged in successfully has authenticated successfully is logged in you know what i mean and then we just want to return the username by the help of the actual token because the username will be stored in the in the token and then we will again grab the username from that token and return it so this is the whole magic again won't explain this stuff the token is valid for or yeah available for one day only and then we return the json web token and then in the end we've got one more method i already spoiled that a little bit we will use this method here got this magic keyword authorized and this means that to get access to that method the user has to be authorized meaning we have to send a valid json web token a bearer token in the authorization header of the request and then we access the get my name method of the user service and again what i already told you we grab the name of the the user of the http context access and the http context and this whole magic works thanks to the json web token that is added to the authorization header all right so this is the net magic again uh might be real quick a real quick recap here but uh to get a better understanding there's the other tutorial or the skillshare course the only thing i want to show you here now is we can start this grab the url and then use this url in in our angular app but there's still one thing we have to add actually and this is done here in the program cs because the problem is now that we get a course error so a cross-origin resource sharing error meaning that our angular application will run on localhost port 4200 and this runs on localhost localhost and any other port we will see the port in a minute so we have to enable course and i would say let's do that now real real quick and we add this down here similar to the other services we write builder services and then add course let's get some options and this looks like that we add a policy so add policy give this thing a name so the name in our case might be ng origins all right it's a great name for our angular origins in essence and then here we say regarding the actual policy we add policy with origins so these are then the origins we accept in our case this will be http colon forward slash forward slash and then a local host and then for 1200 or 4200 for our angular app and we allow any methods and also allow any header all right okay i hope that that's it this should be it and one more thing is necessary then a bit further down we write app use course and then here we add our name so the ng origins it is all right so this is the only thing we have to add here in the dot net project this is our change so well please do that and then we can just leave the net stuff here in essence we can just run the app have a quick look at the swagger ui where we can test that already and then i would say we move on with angular okay there it is already see here our off method is secure that's why we see this little lock icon here but we can totally use the register method here for instance username and password can be string let's execute this and here now we see the url see that it's port 7272 all right and this is then what we will use for our angular app so please keep that running and open and then um we can yeah grab the url and see that this stuff works and now here we can test this as well it executes and we get our json web token this is how this stuff looks nice right all right okay so angular it is next and i've got a folder open here this is called ng.net auth tutorial isn't that a great name and in here now we just open visual studio code this time that's what i use for client javascript or typescript apps like angular apps for instance now please make sure that angular is installed if you don't know how to do that please have a look at the crutch operation uh yeah the crutch tutorial angular14and.net6 also on my channel i hope i won't forget to add the info card and maybe the link in the video description as well because there we cover all the card operations well as the name may already imply and we also install angular there but i think when you're looking for authorization with angular 1.6 you already have some kind of app running so it might be already installed and you got your first steps with the application so what we do now here is we just create our new angular application with ng new and we call this ng.net auth dot ui all right i think that's a good name yes we can use angular routing why not and we use css and this now takes a while and when this is done you already see the new folder here i will fast forward the video and then open virtual studio code again in this folder all right here we are this is now our angular application we've got our source folder the app folder and we will change these files here of course and additionally let's already create a models folder and also a services folder so new folder models and another one for our one and only auth servers and then later also the interceptor now the first model and the only model is our user so let's create our user ts and in here now we export the class user and you've already seen that we only need the username it was the user dto in the netapp let me have a quick look again there it is right this is the user dto so we will use the username and the password here and this is actually an empty string [Music] and also the password empty string save that beautiful okay now this this is the model and now i would i would like to start at the end actually and with the end i mean the the service because the user would usually start with the form maybe where the user enters the username and the password then tries to register login and so on then we will use a function of the of the actual component where the form is and then we would call the service but here now i would like to start with the service first for that since we try to make web service calls there so http calls we need the http client module and we add this one in the app modules file so appmodule.tsts it is and here in the imports we add our http client module and we have to import this manually so it is import and then http client module from or does it know where it is nope sometimes it just not works and but sometimes it does well let's see how it works with the forms module then angular common http all right so this is the module we need and now we can create our service and let's use the command line interface here it's not an app it's source then app and then services and in here now we say ng generate service off and please skip the tests the tests or tests i think it's tests so let's try that looks good all right so now our off service so there it is and now let's already inject our http client here http client and that's the one and now in here we need the register method the login method and then the method that should be secured or only accessible by authorized users so first maybe register all right so public register user of our user type and it returns an observable with type any i use any here because the wait let me just add the import here because the dot net method of the controller here it returns an actual user object all right and i am too lazy to add this object here and that's pretty much the reason why i use any i know it's not you shouldn't do that maybe in typescript please bear with me here so we return anything and in here now let's just say return this http post again any and then the url in a second and we use the user object here for our post methods and again that's pretty much it so let's have a quick look at vegar ui we've already tested this let's just execute it one more time and this is now our url and by the way maybe maybe i should explain this a little now how does this work well we've got our controller here and you see it this is the route for the controller api and controller and brackets this means the name of the controller and after that then we have this attribute here http post and then this is just short form for http post and then also the route attribute so http post and the route attribute are combined here so that this is just the route and in our where is it the launch settings json file you see the base url or the application url localhost 7272 in case you use https right and here the http variant all right so that's that and now back here paste this form of this maybe a little bit and we're done with our register method and since we're already here let's also add the login method i would say so let's just copy that since i am a lazy coder i already told you that right so login you also use the user object here then we get a string actually no wait that is yeah we get a string we get a string here for the uh for the json web token but this does not work here and i will tell you why now we use the user object but the method the login method here this thing returns no object it returns a string and the default object that is expected here with these method the post method to get method and so on of the http client is is uh is an object in json form right so it tries to to cast the object into a json or expects a json and then well wants to build an object out of that but in this case we only get a string just a plain string no object whatsoever so we have to also change the return type or the response type here and we do that by adding the options you see it here we've got the url as a string the body any and then the options and the way down here we see response type so now here we say response type is simply text all right and with that then you see it here somehow does not work but when we remove the the the type casting then it works all of a sudden all right so this is why we have to change that and now let's also add one more method and then we are already done with the service here and this is now the method for the authorized user here in net we called it or i called it get me and maybe i should have called it get my name because this is actually the name and this is actually what this method does so but maybe you want to add more so i don't know maybe also your age or your address whatever it is or your avatar maybe this would make more sense you've got i don't know some kind of web application with users and images of the users and then you want to know more than just the username in that case get me would make sense maybe i leave that up to you but this is the method get me so let's add another method here get me and this now has no argument whatsoever it returns though again a string and this time it's a gets with a string now we don't have to change the response type also not no object here and this is simply the controller name all right because it's a default get method as you can see here no route whatsoever we can just use this url and that's it this is our service now all right and from that let's jump to the app component ts so in the app component ts we also add the methods actually this is everything we need and also the user object so let's start with our user which is a new user all right and now again we add the register the login and the get me methods which just yeah which just call the the auth service so we also need a constructor and in this constructor we inject our off service that's the one of course brackets are missing all right and here now the methods again register with our user all right and in here now this auth service register user and we subscribe and again just copy paste it for the login and here we call the login methods and we do some more stuff here since we get the the the token back i want to store the token in the local storage and then at the end of this tutorial we will add the interceptor the authentication receptor that then grabs this token from the local storage and sends it with every request and puts it to the or in the authorization header of every request all right i think it will make sense when we get there but for now let's just add this thing to the local storage so local storage it is set item uh you can call give it any name so auth token for instance and token so this is our login method now and the last one get me in here now we say this off service get me subscribe and maybe we can just lock that so name as a string is what we get back and in here now we just say console.log name all right and this is now our app component actually and now the last step or the not the very last step again we need the interceptor then but i think the last step before the first test maybe is now the changes in the app component we just remove everything from here and now we add a diff really not that pretty form actually so input type is text so that's the default one placeholder here is the name and we will use uh the ng model here so ng model we need the form module for that so we will add this in a minute user user name that's the one for the name then we add the password so this would look something like that yep password maybe we can also yeah use the type password so we won't see it password all right that's that and then we need buttons to register login and maybe also called the get me function so button it is i call this a register and in here now on click we call our register methods and with the user of course all right actually not really necessary right thanks to the data binding but still let's just use it like that now login log in and the last one [Music] get me no user here get me all right and now the forms module of course i think maybe well that that that is known okay this this phones this works so let's have a look again yep that's correct all right i would say it has that now so let's open the console and then we just run this with ng surf dash dash open and here is our beautiful application let me open the console and let me check if there's something here yep from doing that earlier i have a token here but now what do you want to do we want to have a look at the network tab here and we can of course make this a bit bigger oh this looks nice so let's add a name and a password and then we click register and this seems to work we have our payload here tony was the username password was stark in the preview we get this any object here this is the complete user object and also here of course in the response so this seems to work already that's nice now let's try to log in with the exact same credentials say login and it's calling the register method okay now this was the first error nice and login log in yeah copy paste ever right nice okay let's try that again tony stark login [Music] that's the payload and this is now our json web token isn't that nice this already works and we can have a look at jwtio and there it is and here we accept everything and then we just paste this token and you see there's the name so this is one claim we edit and also the role is another claim let's have a look at the dotnet app maybe and this is well there it is so here we added the username and also the role admin so this now you can also see in the token and we see the expiration date august 2nd and so on all right so this works already and now the last step again the interceptor because when i now try to call the get me method it returns a 401 not authorized this is what this means so let's change that and add an interceptor all right back to the angular application where is it there it is and i'd say in our services folder we create this new file auth interceptor dot ts that's the one and now let's just start with export class call this auth interceptor this implements now the http interceptor all right and we also set this as injectable like that all right and here now uh we have to add a function actually and we can do it here of course like that implement interface so ctrl period and then implement interface http interceptor and now we've got our intercept method with with the request objects then the http handler called next so this is for the the middleware pipeline in essence and then also returning an http event so what we now want to do here it's actually pretty simple first let's grab the token so cons token it is local storage get item and then off token okay just formatted formatted this and after that now we just say if we have a token then in that case we just say the request that we got here and we intercept we just clone this with a rec clone or request clone and then here we can say set headers and in here now this gets another object and here we want to set the authorization header and set this to us string interpolation here at least try to that works better because this is a bearer token and then add the token all right so this is what we do here in that case and in the end we just return next handle and then the requests and that's everything now of course we add the parentheses here and now that's it and the very last step is to also add this interceptor as a provider in the app module file so down here we open a new object and then say provide is http interceptors then use class so this is then our class the auth interceptor all right and then we can set multi or multi to true this simply means that we can use multiple interceptors here all right let's save everything and then i would say we test that already should be rebuilt and reloaded there it is and now we have a look again at the application here we've got our token so when we now simply call the get me function it should work let's have a look at the console as well and you know let's call get me we get a 200 back means okay and the response is the name and this is also well i was ho i was hoping we can also see that here but it says unexpected token and this is actually what i wanted to to change here let me just have a quick look response type is actually text so why does this not work yeah let's try to remove the typecasting here as well and then set the response type here also to text and try that one more time get me and now it works all right okay so this is what i forgot here of course when we return a string here in the post method then and also here in the get method then we should remove the type casting and then set the response type to text and now this works all right and tony here as well nice that's it yeah that's it i pushed everything to github so you get the back end there you get the front end now also there the angular 14 client if you have any questions or more requests regarding net or angular please head down to the comment section and write it down there thank you very much for watching already if you learned something then again i'd appreciate it if you click the like button and subscribe to my channel also the newsletter might be something for you for more.net 6 stuff and then.net 7 stuff and the upcoming.net web development bootcamp you will be the first to know when this stuff is available and you will get early access actually to that web development bootcamp and when you subscribe to the newsletter so subscribe to the newsletter that's it's awesome thank you very much and now if you want to watch more videos check out the videos here on the side just hang out a little learn more.nets and then we become best friends so thank you again very much for watching thank you so much for your time and i hope i see you next time take care
Info
Channel: Patrick God
Views: 20,958
Rating: undefined out of 5
Keywords:
Id: _pqNp-YSK8Y
Channel Id: undefined
Length: 39min 58sec (2398 seconds)
Published: Tue Aug 09 2022
Related Videos
Note
Please note that this website is currently a work in progress! Lots of interesting data and statistics to come.