🔒 Identity with a .NET 6 Web API & Blazor WebAssembly

Video Statistics and Information

Video
Captions Word Cloud
Reddit Comments
Captions
hey friends welcome to my channel my name is patrick god thank you so much for dropping by i mainly create web development tutorials here on this channel and as you already know today we are going to have a look at the identity framework so the plan is we will create a blazer web assembly ace peanut core hosted project why asp.net core hosted because with that we get a web api project as well and in this server project in the web api project there's all the identity stuff and still i want to use blazer to make a call where we get some user information and also related data of this user so in essence we've got the user then we will also add a new model uh superhero surprise surprise if you already are subscribed and watch some of my tutorials you know that i like superheroes i hope you do too and so we've got this relationship and this is what i wanna wanna do then what i wanna implement then but there are certain steps you have to do up front really so i think at the beginning identity might be really overwhelming it was for me too because you got lots of tables you have to update the database or create a database with a migration again lots of tables then there you've got data context already you've got the application user model and if this is completely new to you all this stuff the authentication stuff authorization stuff and so on then this is simply too much i think and with this tutorial now i hope that i can help you walk the steps do the steps take the first steps with identity and hopefully this then will be a lot easier for you if it is and if you liked this tutorial and really learned something then i would really appreciate it if you click the like button maybe even subscribe to my channel really appreciate it it does make a difference thank you so much don't forget to hit the bell icon if you want to get a notification as soon as a new video is online also really interesting maybe for you is the newsletter if you subscribe there you get these videos here earlier in your inbox and you also get early access to upcoming online courses like the dot net developer boot camp where we will cover the back end side of dot net six or seven let's see application of the front end with blazer and also now since you guys like angular maybe we will also add a chapter with angular and also git and devops so lots of stuff coming there if you're interested maybe the newsletter is something for you and one more new thing i created or i'm still creating a course regarding youtube tutorials and online courses in general so i get lots of feedback from you guys that you want to know how i create these tutorials how i create my online courses and now i'm doing i'm creating a specific course for that so i'm not really programming related not development related but if you're interested it's called the online course lab and i'm doing this together with my wife who's also creating online courses so if this is something for you check out the link in the video description and also if you want to subscribe to the newsletter because then you will also get information there but not much main part is still of course web development and programming so don't worry you won't get lots of emails about the online course lab this is just a side project here and the last thing got some tea today thank you so much for all your support guys really appreciate it i love you forever for supporting me doesn't matter if it's coffee or tea or water orange juice hot chocolate whatever it is i love you guys thank you so so much maybe you know the drill boy is asleep and now i'm creating this tutorial this is the the baby phone here it is silent but it wasn't silent when i recorded the the tutorial the actual tutorial so maybe you'll notice but now long story short enjoy the tutorial all right here we are visual studio 2022 we create a new project and we use a blazer web assembly application this template here because i want to show you the blazer client the web api server project where we will see then all the identity stuff and then also the shared project well that's not that important but still we've got it and we will use it for a model that we will use for a relationship with the actual application user the user from the identity api then in this case so we call this project maybe blazer identity tutorial great name next and we use dot net six as the target framework of course we configured this for https asp.net core hosted because as i already said it i want also the server project and the shared project with the client project of blazer and now authentication type this is important now i've got lots of tutorials and in my courses i don't use any authentication type here i just or we together we implement a custom json web token authentication and authorization system this works fine but now we use not the microsoft identity platform we will use individual accounts and with that we will make use of the identity api or the identity framework you name it don't confuse that with identity server identity server use this asp.core identity but here now we are just using the identity framework to well get a a complete login and register system where users can um well manage their accounts and where you with your application can manage different accounts and there's lots of code generated then for us and files generated for us as you will see in a couple of minutes so this is i think this is the reason why many many many people are overwhelmed by identity at first me included to be honest um but uh let's do this together here and then i think i can help you to walk the steps and make this a little bit easier and simpler for you all right so we've got our project here we've got the blazer identity tutorial client project so this is typical blazer stuff now i have to tell you this is not for beginners here really i won't go deep into the generated files the code here i hope you already have a little bit experience with blazer and also with net 6 web api or net web api in general because i won't tell you what our controllers for instance or what's the model here what's the data stuff i've got tutorials about in essence everything that is that is covered here so for instance here you see already a db context right so a database called a data context database context really where we use entity or where we can use entity framework to access our user data and all the other data so we do not have to create a data context here by ourselves it is already here for us and you also see a migration here and this is important in a minute we also see the user model this is the application user and then we've got a car we've got controllers we've got areas so this is new if you know the web api standard template in general this is now part of identity here good pages here all right and the default program cs with the app settings json and so on now before we go deep into the or a bit deeper into the code let's just run the application and then see what happens all right so you see the starting project is the server project and in a couple of seconds we should hopefully see our blazer web assembly application there it is on my other screen and you see something is happening here now this is the default theme of a blazer represent the application right but now we see register and login for instance and when we go there you see we're somewhere else this is not the blazer webassembly application anymore you see it here in the address bar we've got identity account register what the heck is this and when you have a look here in your in your solution explorer you don't see these files where are they well we'll get to that but first i have to tell you and explain that this is it set but this is not blazer anymore these are razer pages or an npc application that is running on the server and that's why you won't see this stuff here actually it is somewhere here in this api in this library of identity so when we try to register now an account or maybe we try to log in an account it won't work and you also can see this here when i try to log in here getting an error what the heck right so this is not working but let me let me try this here now when we try to register for account with tony at stark.com for instance and a top secret password all right whoops an error database operation failed while processing the request so what is going on here already telling you that we have to apply migrations so we have to build our database first and now again when you already know this meaning you had a look at entity framework core with code first migrations maybe also relationships by the way check out my videos on the channel i think i will display some info cards here so maybe there's something for you and if you know this stuff you also know that we need a connection string for entity framework and in this connection string we then see the actual database right and let's just have a look again you see this thing here can it open database asp.net laser identity tutorial server and so on what a crazy name for database well here is the same name right so this is the connection string that is used and when we have a look at the program cs file here you already see or you also see this is the connection string right so by builder configuration get connection string then default connection this is exactly the name we see here and we can also see that then this um db context the application db context is registered here and uses sql server with this connection string all right so this is how the database is in essence connected to the application it's using a local db but in my case i want to use a sql server express database let me show you one more thing this is the sql server management studio again did this already on my channel and my courses but if you also want to use sql server i just want to use it because i think it's it's easier to see that stuff um so meaning the the database and the tables and so on you can change change the things and well i just like it so maybe you want to use it too if so then please google for sql server express maybe we can do this together so secret server it is and uh the first sit here sql server downloads just real quick and then here you see express so you can download this thing here and then there's one more thing sql server management studio that's the one and download secret server management studio and with that then you get this application here you can connect to this stuff and then here you see the databases this is a database of my jumpsuit course maybe you want to have a look sorry for the little commercial here but this is something else what we will do now is we will change the connection string so we can connect to our local sql server express database and then we will run the migrations for that we also have to install the dotnet tools but don't worry we will do this together so first the connection string as soon as you got sql server express installed on your local machine looks like that localhost backslash backslash and then sql express now the database name i'd like to change that so let's just call this weight let's just call this identity db maybe for identity database trusted connection true multiple active result sets don't need that so let's remove this so now this is the database localhost sql express identitydb is the database and trust connection true so this is our connection string now and that's pretty much it now we could use entity framework but we also have to install the dotnet tools for entity framework and we do this with the package manager console here it is if it's not open in your case i think you get it here view other windows and then package manager console or you've got your shortcut whatever it is then we are here but for installing the net tools we don't need to be in a specific folder we have to be in a certain place when we want to update the database around the migrations but to install this thing we just enter.net tool install global and then net dash ef in my case it's telling me that it's already installed so what i can do is either uninstall it or i can also say please update this update this thing and with that i get the latest version 6.0. 6.0.6 and now to double check with dotnet ef i see that this thing is installed great so this should also be the case for you and now you see it here there are three commands available database db context and migrations now to add a migration we will do this as well in this tutorial here we need the migrations command and then we only need database for creating and updating the database so for now we've got the migration file already right so there is already a migration edit here create identity schema this year the the zeros here are actually the or when you create your own migration then it's the date and the time you created this migration and then you see here in the up method what is actually going to happen and you see lots of tables will be created asp.net roles asp.net users device codes and so on so lots and lots of stuff and this is what i what i meant earlier when i said that it's kind of overwhelming so much stuff is going on here and maybe you don't want to to deal with all that because it's simply too much and when you for instance just want to know how authentication works in general then maybe just have a look at my json web token tutorial here on my channel and in there it's just one table right so it's just one user table and not many properties it's just an i think an id a name maybe an email address and then a password hash and a password sold and this is everything we need and here well lots and lots of stuff for instance when we have a look at the application user inherits from identity user and when we go to this definition here and then to this definition you already see here as well we've got phone number confirmed the phone number security stamp email confirmed and so on so lots and lots of stuff but still this is great stuff this is used in production in in many many applications companies and so on so of course this is great stuff i just wanted to show you what you actually get with identity here all right so this is the up method creating lots of tables and the down methods will drop all these tables meaning when you want to remove the migration roll it back then this would happen in your database but now we wanna run this migration all right so how to do that first make sure to change the directory to your project and then you see the client server and chat folder in my case here so now we also want to get to the server folder and now we type net eff database updates and don't get confused by the update term here this also means that the database will be created if it's not there already so build started and in a couple of seconds hopefully we get our database let me take a zip of my t today all right build failed nice this is not what i expected to be honest was that build failed use dot net build to see the errors dot net built and it is telling me can access the f oh yeah sure application is running so make sure that your app is not running and then without idf database updates this should actually work nice build succeeded and you see lots and lots and lots of sql commands see here values are inserted create table and so on so lots of stuff and now we can have a look at the management studio we refresh our server here and voila there's the identity db and we get lots of tables right so as i said much stuff but the most important one for us really and for this little tutorial because i want to make this easy for you guys right click the asp.net users table and yeah either select up to top 200 rows to see what's actually going on here or at the top 200 so select 1000 top you know what i mean select top 1000 rows or edit top 200 rows and with that you see um yeah all our fields here and now i would say we run the app again and try to register a user so back to visual studio there we are and let's do this one more time there we are oh it reloaded this already okay so well you did not skip the chapters right you watched the tutorial from start to now this certain point here and then you will continue to to the end right so you know that i try to register with tony at stock.com and when i now right click this table execute sql there is our user right so we can do this again actually let's go to register and then maybe peter parker.com wait all right okay now it worked see and this is important of course this app does not currently have a real email sender registered cd stocks for how to configure real email sender normally this would be emailed and now we have to click here to confirm your account because when we have a look at the database here we see these two users but email confirmed is now false and for instance i can click here thank you for confirming your email now it's true oops this is the baby phone hear that little guy just moving around a little i love him um yeah this is not true and when we try to log in now for instance first with tony stark start.com password invalid login attempt because this is not confirmed but when we set this to true this will now work all right so we are now authorized as hopefully tony stark takes some time okay now it works great so this is now how you well start with identity get things going and you only need well maybe 50 minutes to do that so this is already nice but as i already told you when i log out for instance and i have a look at the register page now this is something different here and the question is where do we find this so let me go back to visual studio and the solution explorer maybe let's just close this i already told you that this is somewhere here on the server project now if you want to change the the the pages here registration logging in and i don't know change the password and so on there's lots and lots of stuff you can actually do here then you would have to use scaffolding right so this is the magic keyboard here and i assume if you want to use something like that in production then you should probably change that and change the look of this thing so how to get there well we right click the server project and then hit add and then new scaffolded item and then we see this entry here identity identity and then we click add and then we get a bunch of files listed and then we can even select do we want to overwrite all the files get all files and um change them then or just the registration form and so on but let me cancel this cancel this first because this stuff is a little bit tricky the generated code well leads to problems and then you cannot start your application anymore and to really see the differences and see why it's not working anymore then let me first cancel this and add this project already to source control meaning i will create a new github repository it's public for you guys and i will add the link in the video description of course so blazer identity tutorial is nice and yeah this is my github account create and push that's great and now we will add um one file or all the files let's see okay it's pushed now right click the server project again hit add and then new scaffolded item identity identity add see here a package is installed real quick and then we get the option to add some files but first really quick let's close the terminal to stop the app and uh now after retrieving yeah there it is already as i already told you lots and lots of files here available for us status message confirm email change and so on so we can either choose to override all the files or for this little tutorial here let's just use this page here account register all right and additionally you need a data context class but we already got one so as you can see here in the drop down we can just choose application db context and that's it no user class is necessary here just click ads and then you will see that not only one file is generated there are actually a couple of files generated for us and these files as mentioned before will lead to some trouble there you see it 32 changes jesus christ that's a lot right so this is what we get here now we've got the pages and the account folder with the register cs html file so no blazer here no razer component but the eraser and yeah lots of other stuff and then you see also the ww root folder with a css file lots of javascript bootstrap and so on and also a fav icon and this is creating a problem and then also the programs yes also creating some problems because when we now try to run the application the build is failed nice right a local variable or function named connection string is already defined in the scope huh what the heck well we have a look here at our program cs and you see here there's the connection string variable and there it is again why is that well let's have a look at the changes again here now in the program cs you see that this is now the generated code that was added for us but it's not really necessary so let's just remove it all right and then this problem is solved now let's try this one more time still failing what the hell well conflicting assets with the same target path fav icon dot ico now what this means is simply that when you have a look again at the solution explorer we've got our www root folder in the client project with a fav icon right and now we also have this thing here also with a fav icon now the easiest solution is to just remove this file and we're done and here now you see the register page so let's try this one more time build succeeded all of a sudden that's nice and now we can go to the register page and let's try to change this thing so let's open the register cshtml and in here now for instance create a new account do it now it's amazing save that i think it's rebuilding yes we want to rebuild and apply the changes and do it now it's amazing isn't that nice so now you know how to get access to that page and you can in essence change everything you want to change with razer right so this is what you need here but well maybe you can just use html and a little bit of css i think you don't really have to know a lot about razer pages because the actual logic you can you can leave the logic here but maybe just change the design a little i don't know whatever you want to do you can do it here okay so this is just a register page and again if you also want to change the login and all the the other pages then just add other scaffolded items i think the the really important thing here is that you have to deal with these strange errors that some code is generated in the program cs that we won't need and the actual theft icon is leading to some trouble all right so let me let me just push this already committed at least scaffolding register page all right and now the last thing i want to show you in this quick tutorial about the identity you know the first step if you want more please as always guys feedback write it down in the comments and then i will do my best to i don't know give you a crud tutorial for instance or use um oauth for google authentication twitter authentication and so on together with identity i think this is pretty interesting stuff so maybe we can do this in another video but now the last thing actually what i want to do is adding a relationship meaning we've got our users here the application db context and the application user here this is what i wanted to show you and maybe if you are a loyal subscriber to my channel and watched lots of other videos on my channel you did right then you know that i like superheroes so in my other tutorials i just use something like you've got the the user and the user can have a list of super heroes so we've got a one-to-many relationship here and to realize this well we need another model so in our shared folder now let's add another class and we call this class super hero it's a public class and this simply gets some properties here like an id also a name which is empty by default let me just copy this real quick for us the first name the last name and the place maybe so first name last name and the place all right and now we add this superhero here to our application user let me close this first because we have to run a migration then anyways so now here the application user gets a list so prop list super hero and we call the super heroes and by default this is a new list of superheroes and of course we add the reference here to the shared projects and now the last step is to also add a db set in our context here so in here now we say public db set superhero at the reference again we call the super heroes so this would be the name of our table and we can already set this or give this a set of super hero so we won't get the warning that this is notable or anything save that and now we can run another migration or add another migration and we do that with dot net ef migrations at let's say super hero my duration all right and now we should get a new migration file there it is super hero migration and as you can see here now it gets or it will create a new table with also an application user id and here you can now see the actual relationship this is the foreign key the user id was also added to our super heroes table all right so let's update the database again dot net ef database update perfect so now back to sql server manager studio refresh the database and now here in our tables we see the new superheroes table with these fields here nice and i would say let's already add one so in our users table we grab this id here of tony stark and now here let's just say tony stark because iron man is a superhero i think that fits and um yeah first name again tony stark malibu and this is now the id of tony and maybe since we're already here spider-man peter parker new york city all right so now we've got at least one hero for every user here tony stark gets iron man peter parker gets spider-man and now the next step is to create a get method where we can then get this data of the authenticated user all right so for that we first have to create a controller and this is done here so in the server project again we see the example controller for instance the weather forecast controller right click the controllers folder and go at controller this time and here we choose an api controller and this would be an empty one so no generated code nothing like that i just want to use an empty controller here and this thing is called then superhero controller and the first thing now is a constructor because we need access to our application db a context so ctor it is and in here now we write application db context contexts we need the reference of course and here now ctrl period and then we create and design the field context and i like to add the underscore here and there and now we can write our actual method it is indeed intelli code the http get method public async task and we return an action result with a list of super heroes call this get super heroes maybe this is the one and also at the reference here again i mean i could use a global reference actually because we are here with c sharp 10 right but still let's just continue and now why am i doing this well there are certain ways to do to actually implement this with identity and well also a certain way to do this without identity and first i want to show you the one without identity so what we're going to do now is we will access the contacts directly and from the context then directly the users table and then get the the currently authenticated user and from that user then the superheroes and then the other way is that i want to show you after that is to use the user manager of identity but first start with well the old way let's say to get the user we again access the context with awaits context users and then here let's say first or default async we need entry from a core here and we need the actual user where the user id is the now current http context user so this is something we get out of the box in the controller i see it here this is a claims principle so in essence this is the currently authenticated user with some data and in here now we can use a method called find first value need another reference here system security claims and here now almost here now we actually want the id of the user and we can get that with claim types name identifier now again if you never if you've never seen the stuff the claim types and what actually is a claim and so on then this might be too much but in essence this just means that a user that is authenticated and that is well doing a request to the web api has some claims meaning the id the name the email address and so on also roles so regarding authorization this is then interesting and to actually be able to get this user we have to add one more thing and this is the authorized attribute here so authorized authorize and also at the reference microsoft asp.net core authorization and with that then we make sure that this can this controller can actually only be called by authenticated and authorized users and uh yeah then we get this user object here now let's try that first we check if the user is null then we return not found and if we have a user yeah this is exactly what we need return okay user super heroes and now to be able to call this we also have to add some code to the client and now this is also well actually i would have to explain this a bit more but um let's let's just try this so here in the index eraser component what i want to do is first i add the code block and if you're familiar with blazer then you know that we've got three lifecycle methods and one of them is on initialize and we can use the asynchronous one and in here now this simply means that when this component is loaded we well we run the code that we will write here in a second and what i want to do is now just make a call right for that we need the http client we can inject the http client here with at inject http client and then simply http for instance and now down here what we can do is we say var heroes is a weight almost awaits http and then get from json async list super hero and then the actual url which is api super hero and we add the [Music] async keyword here and also the reference again and with that now on initialization we are making this call all right so let's save everything and try that all right application is rebuilding [Music] let's go here and now we have a look at the network tab we get an error here that's correct because it the application is trying to make this call although we are not authenticated yet we will also change that and this is just https related stuff just ignore that for this tutorial but when we now log in with for instance oh see that responsive responsive design this is nice so now we log in with tony at stark.com and then the proper password we at least see that there's no error anymore here's our call in the network tab but we have no superheroes and that's correct because we did not include them so let's do that real quick and you will get why i did this that way so first i was waiting to include the superheroes and now i'm doing this so now we will actually include this relationship uh to the superheroes is rebuilding i don't know superheroes [Music] again yeah i did all right this is nice so now we get iron man all right so this is one way to get the related data we've got our user we get the we get the id of the actual user by using the the context user and so on so this is one way but let me now show you another way using the user manager so people would maybe say with more experience with identity that you should definitely use the user manager to access the user so let's just try that and first we inject this thing so user manager application user we call this user manager and we need references again so first asp.net core identity and then our models and again let's create and assign the field here all right and add the underscore here as well and now let me first just comment this out and the var user is now await user manager and then we've got a couple of methods here we also get user async but this did not work in my case maybe you know why but what you can also do is find by id async and in here now we can actually copy this and we're done that way we also get the user save that application is rebuilding i guess so yeah it was reloading and now it's again empty and this is why i showed you the include method or the this this call here first without the include method and then with the include method because here we have exactly the same problem we get the user objects but we do not get related data but of course there's a way to fix this and this way is actually here in our application db context there's this great method called on model creating so we overwrite this method again overrides on model creating that's the one make sure to use the the base method here so based on model creating builder this is really important otherwise it won't work anymore and now we can say for our application user we always want to include the superheroes so builder entity application user that's correct navigation and then super heroes auto includes we save that it is rebuilding i hope yep it is and now you got the call and you also get the hero here and now we will log out and do this again with uh peter parker for instance peter parker.com and the password it's making the call and here's spiderman isn't that nice so this now works and the very last thing i want to show you when we go here again we see this error so why is that happening again because in our client project here in the index razer we're doing this call no matter if the user is authenticated or not but of course we can change that now that's really actually lots of authentication related stuff in blazer that you might need to know to understand this completely but the magic keyword here in blazer is the authentication state provider and well as the name implies it provides the current authentication state of the user and what you can use then in blazer just real quick we've got our main layout here for instance right and also what we have is the app razer file and here you see the component cascading authentication state and then authorized route view not authorized and also authorized in another component login display for instance right so here we've got the authorized view and with all that we just to make this quick with all that we can give this application the current state of the of the user so is the user authorized or not and in this particular case here this is a nice example with the authorized view you can also decide what you want to display when the user is authorized or when the user is not authorized and you've already seen that you see hello and then you also get the http context or the authentication state in this case with the user and the name and if the user is not authorized we just display the register and the login link for instance right so we can make use of that but we are not in the html here we are in our code block so we have to access the authentication state provider which is also built in here in this complete solution with identity so let's have a look at the index razor again and to make use of the authentication step provider we have to inject it similar to the http client so add inject and then authentication state provider let's just also call this authentication state provider and now down here what we can do is we can actually write our user is a weight authentication state provider get authentication state async user and then identity [Music] and with that we can ask if the user is not null and the user is authenticated in this case we make the call save that it's rebuilding and reloading and now we are not logged in we do not see the call here right so i let's do this one more time reload no call all right and now when i log in with tony for instance and password we log in and now we should yeah here's the call right so let's remove this again reload and here's the call all right so this works and i hope this was a well good quick first introduction for asp.net core identity and let me push this as well further implementations maybe all right this is actually the relationship let's just call this edit super heroes all right and we also push this stuff all right so make sure to check out the link in the video description and then you also get the complete code all right that's it i hope this makes things a lot easier for you if so please give me some feedback i love your feedback guys i love to see your comments and again if you want to see more meaning maybe doing the complete crud stuff with a blazer the web api and identity and so on and also um third party authorization authentication with google twitter github i don't know whatever you need then we can also do that of course in another video i think this is really interesting so if you want to see that please write it down in the comments and apart from that if you learned something i would really appreciate it if you click the like button subscribe to my channel bell icon to get a notification about new videos thank you so so much guys also again the newsletter for these videos here earlier in your inbox upcoming online courses and now maybe also interesting for you the online course lab but in general please let me know if you want to see some information about creating tutorials here on youtube and online courses that kind of stuff so maybe this is something i can also do on this channel won't be much don't worry about that the main focus should really be web development and programming and stuff but um i i get these i get asked these questions what microphone do you use what camera do you use what software do you use how do you script all that stuff and well this is of course covered in the online course lab but maybe i can also do this on this channel here as some tutorials about that stuff so if you want to see that please let me know and the last thing again thank you so much for all your support guys love you forever [Music] tea today so if you want to support me too check out the links in the video description everything is there in the video description so thank you so so much for watching if you want to see more tutorials like that you can either choose to write it down in the comments for a new topic or check out these videos here on the side and watch another video and another one and then binge watch all my tutorials that would be nice and then i think we can get to know each other a bit better a bit more it's late so again thank you so much for your time and i hope i see you next time take care
Info
Channel: Patrick God
Views: 26,175
Rating: undefined out of 5
Keywords:
Id: 6_S46MCokbk
Channel Id: undefined
Length: 50min 46sec (3046 seconds)
Published: Tue Jul 05 2022
Related Videos
Note
Please note that this website is currently a work in progress! Lots of interesting data and statistics to come.