ASP.NET Core 3 - Authentication - Ep.2 Identity Authentication (UPDATED: READ DESCRIPTION)

Video Statistics and Information

Video
Captions Word Cloud
Reddit Comments
Captions
everyone welcome back in the previous episode we learned how to create a user object that dotnet core can store into cookies and essentially provide authentication and authorization based on it now we're going to look at identity and what it provides in terms of infrastructure around this claims principle and claims basically this these concepts and what identity is abstraction around interfacing with the database and the collection of objects and it's just another toolbox that will allow you to roll your own authentication so what I will do is I will ditch this project and I will keep it at basic here and what I will do is I will add another project so new project and again this will be another clean project and I will just copy some stuff over from the previous project so let's create asp.net core web authentication and I will create identity example okay and this is just going to be an empty project configure first yes I don't need that dotnet core three cool so the first couple of things that I will know is that I'm gonna store stuff in the database I'm not gonna bother too much with SQL I will use an in-memory database to make my examples okay so what I will do is I will go into my manage nugget packages and what I want to search for is entity framework so let's go ahead and find entity framework what I want is entity framework or since that's built for dotnet core so let's install that okay so once that it's installed the next thing that I want is this Microsoft entity framework in memory package and what this will allow me to do is give me a provider for an in-memory database as opposed to sequel and it will be a little bit easier to set up as well okay so we'll stop right there and we'll just go ahead and quickly set up the database I will go to my startup and I will do what I will actually do is I'll go to basic start up I'll control a control C to copy everything and then I will control a control V to paste it into here because we will be using most of this anyway and I will actually give an example of configuring cookies for identity as well so what we want to do first since we have a database if we go into in Visual Studio 2019 if you double-click on the project you are gonna go to its say s purge file it saves a really right-click and finding where it says edit CS project you know if we can see the two packages here which have been added so they're not part of the main framework and T framework or and the in memory package are on their own here so using those two I will just go ahead and I will quickly create a data folder and then here I will create an app DB context does yes so DB context is where you register your tables and their configuration for a relational database so R up DB context to be valid DB context has to inherit from a DB context and a DB context is a class provided by the framework and this is essentially hiding well functionality behind registering stuff for our communication with the database okay so in here we will create a constructor and what this will allow us to do is to pass some options to our DB context in order to configure it to either being a sequel or a memory connection etc so we'll need to do is to get our dbcontext options which is again it's just a class which is going to be passed in from the dependency injection container where will register it so let's just say options and we'll we'll pass them to the base so essentially these options will propagate down into the base functionality not just in our DB context so you can think of this as the tip of the iceberg and DB context is really the route where the rest of the iceberg is and we want our options to be valid at throughout the iceberg not just at the tip okay so let's go into services and let's add DB context again this expansion comes from the entity framework package but the namespace is just Microsoft extensions dependency injection I think it is so if we you press f12 we can see Microsoft extensions dependency injection but the real assembly is Microsoft entity framework or okay so let's add app DB context now what we want to do is configure it to use the in-memory database let's go ahead type in config this can be really called anything you want and in here I will say config use in memory maybe not memory database yep so use the in memory database and we will have to import I think it is let's see what where it comes from Microsoft the entity framework or package so this using Microsoft de NT framework or and in here we will just have to specify the name for the database and I'll just call it memory okay let's put a semicolon here okay so what this does is this class which essentially gives us all the functionality to communicate with the database this makes it available to be injected anywhere within the application okay so now essentially that we have a connection to the database or available to the whole application what we want to do is register identity and identity it really works with the database to basically provide tables where to you where to store users user information so like a username password email where to store claims so if you know if you remember the previous example where we if I stop opening everything and I just open the thing I need if we just hard code these things in a real world application they will need to be stored on a file in a database most likely so so identity provides all the infrastructure for setting that up so let's go ahead into services and let's add identity okay and if we f12 on ADD identity we have a type of user and the type of role so the type of user is your own object that you would like your user to be but and the only thing that it expects it is to be a class ok I will default to be to using an identity user what identity framework sorry what identity is library essentially provides so identity user and then identity roll okay let's call up so what this will do is it will register a couple of repositories okay so if you don't if you're not familiar with the repository pattern it's essentially a collection of functions its interfaces something that abstracts your calls to the database etc so just adds a bunch of objects which are collections of functions to our dependency injection container which we will talk a little bit in a minute okay and now what we want to add is add default token providers this is just used to generate tokens that are regarding to like password the stuff that's passed in the URL so you know if somebody sends you a password reset link and you will have a token in the URL that's assigned to a password reset and that will expire this is essentially a default mechanism for that and that's what that does okay so if you don't have it it will give you an error but now it will work so for these two to work together what we will need is to add a bridge from one to another now the and now entity framework is only concerned with the database so the bridge exists from identity to the database okay so if the identity package wants to work with entity framework the identity package will have to extend itself to use entity framework and create wrappers for that so let's go ahead into the identity example and let's Megan manage new care packages and let's browse for a identity yep let's just find the identity and in here we should have Microsoft asp net core identity and framework or okay so let's go ahead and install that except that and what this will allow us to do is on here now call entity framework stores and provide our app DB context as a means to configure identity to communicate with which with which database to communicate and for our up DB context to accept all the tables will to basically have all the user tables we will need to get identity DB context okay so I'll just put a comment here so you are aware it contains all the tables say user tables and and identity registers the services the services in this context is what we will know is infrastructure that allow us to communicate with the database and essentially authenticate our user and create user records etc so let's close that I will consider that as setup and ready to go yeah well we will do now is will tree a controllers folder and we'll create a home controller don't see us again I will inherit from controller really I could have probably let me delete this because I already messed up the name of the folder let me copy this controller and the folders and I'll place them into here I have probably messed up the name space and here as well okay let me go into program real quick I'll copy identity example and I'll rename the namespace to it and the example and startup and I'll rename the basics namespace in home controls to dos seus okay so let me close this basics file and let me grab home controller again so we will have the index page and here where we identify essentially I want to change this login to be able to log it so let's go ahead and say login and we'll do something simple we'll just pass in a string with a username and a string with a password what I'm essentially trying to do here is create the typical structure to be able to login to register and show you how the identity package provides that infrastructure for you and how you can take care of it and find out about the services available to it etc so let's go ahead and create a public I action result and register hope keyboard lagged register and again we'll just say user name and again we'll just say password we'll just have to be very careful with our password and we'll have to return here so let's go ahead and create these views I'm gonna go ahead into here and I will take secret I'll copy it twice I'll name one to login and the other one I will name it to register and what I actually forgot to do I'll actually copy these two I'll paste this these here and this here and what this will allow me to do is actually serve the page first before doing the redirect okay and let's do return view remove this part here okay my keyboard logging okay and now let's go ahead and grab this and put this here okay so here we'll finality login functionality we all go here and register functionality will go here and this functionality will be provided by the identity packages okay so let's go ahead and quickly implement these forms I'm gonna go ahead and call this a login page I'll try to type these out as quickly as possible form and put name username text password button login submit' let's copy this go into register base this here let's say register and let's say register here okay don't have layout not to fret so at the moment what we're gonna do is we're gonna post some a username and the password into here and then we're gonna in the register will post a username and the password here now what we do for a login is what we we want to find out if this user exists and then we want to find out if we can sign in with this user if the password is correct so what we want to do is let's create a constructor and we will essentially inject some services that we have registered in our startup using our identity so as I said this multiple times already this adds some services let's go ahead and inject them same way that we can inject app dbcontext if we would use services though add singleton type of some class write these internally do the same thing but provide their own classes okay so up DB context is a service that's provided to us by a DB context and add identity would use that internally to communicate with the database okay so what we're gonna do is add a user manager of type identity user okay so user manager is an object provided to us by Microsoft it's been a core identity and that's what you will need to import let's create this user manager user manager and user manager okay so user manager it does what it sounds like it manages user information okay let's make that read-only so what we will want to use the user manager for is to either get user information or create user information or delete it you know manage user information so let's go into our two functions here and the way we want to manage our information is we either want to get a user here to check if he exists or create a user here when somebody registers okay so let's go ahead and use the user manager to create a sync okay and what this will accept is and I hope I'm building let me close this so what we will need to do for create a sync is provide a type of user and this is the type that we have specified with identity user here okay so if you're providing your own class this is where you will need to put it and make sure to specify it here as well and when you go to up dbcontext you want to go ahead and specify the tables for which your type here as well basically to scaffold the correct tables so quickly going back to the home controller we essentially we want to create a user but for that we'll need to create an identity user okay so let's go ahead and do that let's say bar user equals new identity user and let's say username equals a username okay and this should be essentially it usually people also capture email information we don't for simplicity purposes but if you're building a form you will be probably capturing and you'd want an email so let's go ahead and make this asynchronous so we can await these tasks that identity provides to us let's import this okay let's pass user here okay let's save our result equals and away okay so we at this point we have created a user but what do we do with our password you know we we don't know what to do with it well another function that this interface exposes out of all the other functions you can go ahead and read through them I encourage you just so you're aware what user manager can do for you it can do stuff like add claims add add the user to role the password to the user you know you can do all kinds of stuff just read through this and it will give you an idea for when you want to use this user manager when you need to inject it or the kind of stuff that identity provides you with so the other function that was there it allows us to provide a password so the reason this one exists is if you want to go ahead and set the password hash yourself so just custom hash so if you have a custom password hash you can do that but you don't really need to bother with a entity framework do the heavy lifting just put the password here and that will get a result so this result we can go ahead and check if it's successful and if it has been successful we can sign the user in okay let's pause here and I'll just put a comment sign user here because the functionality of managing a user and managing the sign-in state so if I could draw a line and there's basics controller right here is essentially where we are crafting the user okay and this is where when we are signing in so if I would have drawn a line between signing in functionality which needs interface with HTTP context and then a user information functionality which will need to interface with DB context and database under the hood okay so this is the line that Microsoft draws and I would have drawn it too so let's go ahead and close all of this stuff since it's a little bit in the way I'll save that line so this is the database part where we are creating something in the database we're creating a record and here's where we'll want to do the sign-in but I will pause there because I want to do another user management operation here and I want to get the user so before I can sign a user in I want to get the user so let's go ahead and grab a user so user manager and get user okay so get user async get user by ad and we have get user let's say get user by or okay so these functions seem like getting specific properties of the user what I'm interested in is that the user so I think it's fine okay so find by name async so here is where we'll need to provide a username so let's go ahead and find the user here and again let's go ahead and make this a task so we can await an async task so we can await on this okay so we got our user and if user doesn't equal null then we essentially want to proceed because we have the user we're ready to sign in and this is where the sign-in operation will you happen just the same as that happens down below there after a successful user management operation now the next interface that the identity package provides us is is called a sign-in manager and that will essentially handle the communication with HTTP context and the sign-in and sign-out functionality okay so let's say sign-in manager and will provide the identity user object again we want to let identity know what kind of objects it's interacting with and let's call the sign-in manager okay so sign the manager let's do the same thing we did before let's initialize a field although I want an underscore here yep let's grab the sign-in manager and let's eat what I what you can do is just grab any method just so you can press f12 or you can press f12 on this class right here and just do the same thing if you did it with the user manager just go through the classes and try to get an understanding of what these functions do if you don't understand you can for example you have this get two-factor authentication user acing just click on the plus here and you'll get the X more comments and hopefully you will get a little bit more information out of these comments they can be a little bit not up to value but there's nonetheless they can help you so what I want to do is I already get the method sign in async and what this world essentially give me as is to passing a user but I still do I get a password nope want the password sign the neck sync function and what this will allow me to do is essentially go ahead pass in a user and a password and then there are two other parameters parameters which is a persistent which affects the way your cookie gets created and the lock out on failure which is just a counter in the database so this persistent is going to set an indefinite expiry time so like no expiry time on your cookie and that will stay in your browser for a long time so if you do that you will need to inform your users I'm not gonna do it here so I'm just gonna set these both to false and then I'm gonna wait this let's note that password async we can go ahead and provide the username straightaway here so you if you need to do this check do it if you don't go ahead and just try to sign in the user anyway so let's go ahead and save our result equals and we can call this sign-in result and we can perform all kinds of checks and based on this result we can do something else but for now all I'll do is I'll just redirect to index here let's copy this and I'll just paste this here since the functionality is the same so before we can sign in a user we we need to create one okay so this is what this will do and again if this is succeeded I want to go ahead and go to the index page and this is pretty much a part of the what the identity package can do for you and basically the scaffolding around authentication in dotnet core using identity and let's actually go ahead and say public async task I action result and let's say log out and again we can use the sign and manager to sign out async we can awake on this and return again let's go back to the index page here this stuff so let's mark some of these s post so we can post to them HTTP post and let's mark this as post as well and let's see how this work so I'm gonna launched it okay so I'm gonna go ahead to the login page to home slash login okay I launched the wrong application so I want to go to identity example and instead okay so home slash login there is our page so actually I won't be able to login because I don't have an account so let's go ahead and go to register first so let's register test and I'll actually open dev tools so we can see the cookies in action here so test and password that I will say set it to password let's go ahead and register and we didn't get a cookie because they think I didn't post it anywhere valuable yeah I think I messed up the forms so let's go ahead and post to slash home slash login here and this will want to be home slash register ok that's refresh now okay let's go to home register again let's do tests at password register ok and it seems something is failing if we go back to the project and we click on output we can go ahead and find something that for example says warning so user password validation failed password requires none of them ok so this is the fourth part where it's failing because the password is too simple and the way you could configure the password is in where you add a identity so let's go ahead and say config and this is where we can grab the config and we can essentially go to password and set the configuration for what you want so again this is what I'm talking about in terms of infrastructure they abstracted all the stuff and allow you to configure it as in any possible way that you want ok well not any possible way but the way that you would want to configure it generally so let's set the required length to 4 let's copy this a couple of times and actually I will want to set it to false because I already know what's coming so I want to be able to use password as a password so require digit false require a unique characters I don't think I'll need not-not-not alphanumeric false and upper case whereas my require upper case is false as well okay so what this will do for me is it will remove restrictions on the password and allow me to use which of my own rules for the password okay so let's go ahead and run this again and let's actually try something else so let's see what happens if we go to slash secret little slash home slash secret Nazi secret there we go okay so the same thing happens if we go to account login sorry we're getting redirected here so if you remember in the previous episode we have fixed it using this code so I left it here for a reason to show you that we cannot configure the authentication cookie and default authentication to this because now it uses the identity authentication as its default identities so what we'll need to do is use a function that is being exposed to us by the identity package so services and I think it's configure application cookie and in here we will need to provide this config and this config is essentially the same as this one but what this configuration allows you to do is to configure the cookie for add identity so let's go ahead and do the same so we'll just grab both of these and put this here and but this will be grandpa's cookie okay so just a different site or let's just say identity something a little bit more relevant and will redirect to the login page and now let's go ahead and delete this let's run this okay so let's close all that let's go to home slash secret okay and we're redirected to the login page but we don't have an account yet so let's go ahead to home slash register and I will just type in test password register okay so you seen it's been a little bit longer there and now we get an identity cookie which is what we named it as and here it is so now if we go to slash secret and again if I remember that it's home slash secret we're authenticated and we're authorized to go okay so what we can do is go to logout and now our cookie will be cleared here so that's what's I know a sync does alright so it will remove your cookie for you but because our user now exists we can go to home slash login and we'll go into tests and we'll type in password oh and that should log us in again and there's our identity cookie again and again it redirects us to the index page so I'm gonna close that and again just to recap for this episode what identity package provides you with so when I say identity package I mean Microsoft is bean accord the identity is a package which provides infrastructure for managing your user records and all the information related to those users and allows you to easily interface with the HTTP context or if you get additional packages like if we go to identity a go p-- identity example and double click so where we have as installed installed identity and c framework or where it extends its functionality to entity framework or and store the users there ok so identity is all about the infrastructure in the next episode we'll look a little bit at authorization and how we can use claims roles etc to authorize already made an episode about it so if you're a little bit impatient you can go watch my comparison on roles claims and policies well not there will be it for this episode thanks for watching if you enjoyed it leave a like subscribe if you have any questions make sure to leave a comment and as always see my other episodes
Info
Channel: Raw Coding
Views: 131,963
Rating: undefined out of 5
Keywords: .net core 3, .net core 3 tutorial, asp.net core 3, asp.net core 3 tutorial, auth, authentication, authorization, authentication tutorial, authorization tutorial, Claims, ClaimsIdentity, ClaimsPrincipal, Identity, Identity Authentication, UserManager, SignInManager, IdentityUser, IdentityRole
Id: IjbtWPXVJGw
Channel Id: undefined
Length: 33min 37sec (2017 seconds)
Published: Thu Oct 10 2019
Related Videos
Note
Please note that this website is currently a work in progress! Lots of interesting data and statistics to come.