ASP.NET Core 5 Authentication using Identity - Login and Registration in ASP.NET Core Razor Web App

Video Statistics and Information

Video
Captions Word Cloud
Reddit Comments
Captions
hey what's up everyone in this video we will learn how to add authentication and authorization to an asp.net core web application and we will use dotnet core version 5 and razer pages to create our application in this one we will have a register page in which you will give email address password and confirm password and once the user is registered we can then log them in using the email address and password they registered with and once they are logged in they will see a different menu and then they can see the home and privacy pages and all the other pages that uh you have authorized them to view and you can see we also have the user identity name over here and we also have implemented the logger functionality so on clicking log out they'll ask are you sure you want to log out and you can either click yes or no if you click yes you'll be logged out and redirected back to the login page so it's nice fun little application to implement identity and authentication inside an asp.net application so without wasting any further time let's get started i have opened visual studio 2019 and i will click on create a new project i have my filter selected as c-sharp all platforms and web and i will click this option over here which is called asp.net core web application and it uses razer pages so i will click next i will give it a location and name and once i have given the name to the solution on the project i will click next i will use net core 5 as i have installed this one uh if you have dotnet 3 you can also follow this tutorial but it is advisable to follow uh because this is the current.net core version so please install.net 5 and also update your visual studio um so that it it allows to use dotnet 5. i will not choose any authentication over here because this is part of the tutorial so i will choose none and click create our project has been created so we will spin up the application to see what we get out of the box we can see that we have a website which is of razer pages and we have two pages in here a homepage and a privacy page and the theme for this is based on bootstrap css and the version that is being used at the moment out of the box is version 4.3 let's go ahead and change that to the latest version of bootstrap which is version 5. coming back to our application we will go to the layout page and we will remove the references to the bootstrap version 4 which is this one and one at the bottom for the scripts which is this one we will remove that and we will mention the bootstrap version 5. we'll go back to bootstrap's website and you can see this is version five and we'll go to get started page and copy the css and paste it right below the link over here just above the uh local style sheet for our website and we will also copy the script tag which is the bundle file over here and we'll paste that right over here just above the site.js file with those changes we will go back to our website and refresh the page to see nothing changed but now this is referencing bootstrap version 5 and not 4.3 now that we have our website ready let's look at the steps of how we are going to approach this this video tutorial over here we will install entity framework core and we will follow the code first approach to create a database inside sql server so that asp.net core can basically add our users and other authentication material inside those tables the next would be the changes to the startup.cs project to actually add authentication and we will do migrations the entity framework core migrations in between these two steps and we will go and see how the database looks like we will create and implement the register page after we have added the authentication to our application we will create and implement the login page for the registered user so that the user will be able to log in and we will be able to see or we will be able to redirect the user to a different page from there we will change the navigation menu in the layout file so that we could only see uh the login and register buttons and nothing else in the in navigation menu and once the user has been able to log in we will be able to see the log out button as well and after that we will add authorization in the home and privacy page so that users are redirected to the login page if they are not logged in and only if they are logged in uh will be will they be able to see the home and privacy page and at last we will also create and implement the logout functionality so once the user is logged in we will have them visit a button and then from there ask if they really want to log out or not and if they say yes we will redirect them back to the home page if you want to skip ahead to a certain topic you can do that by clicking on the chapters defined below and also defined in the description box of the youtube video all right let's move on to our first step and install entity framework core we will go to dependencies right click on that and go to manage nuget packages in the browse section we will search for two packages one by one we will search for this one first which is microsoft entity framework code dot sql server and i will have the description of these two packages in the video description below as well i will click on the latest version and install you can see from the output window that this has been installed we will go on to the next one and choose entityframework.tools this is used for entity framework migrations so that when we run the script this will actually create a database and inside our sql server database so with that clicked i will click on install the second package has installed successfully as well we will close that and add a connection to our database we will go to the app settings and just after this i will create the connection strings property and add a connection string for our new authentication database i will create the name of auth connection string the property of this would be a server which is dot because i have installed sql server by that name the database would be let's say asp.net auth demo or just auth asp.net auth and then we will also have a trusted connection equal to true with that in place let's go on to the startup file and add our connection to the entity framework and we also need a db context for it so let's create an app dbcontext first i will right click on the project add new folder i will call this model and inside the model i will also create another class file called auth db context this will inherit from identitydb context and when i do a control dot on it it basically comes from this package called microsoft asp.net core identity entity framework core so i will say install package now that our package is installed we will create a constructor over here and inside that we will have the db context options this comes from dot entity framework core and this will be of type auth db context and i will pass this to the base class and that's it we will now go back to our startup file and under the configure services method we will add services dot add db context pool or db context and this will be auth db context and to this method it takes an options and we will say options dot use sql server press ctrl dot to import it is from microsoft dot entity framework core and this takes a connection string as you can see a string connection string so we will use the connection string string that we defined in the app settings.json and we will use this object the configuration to get connection string and we will mention the name of the connection string which was um auth connection string so we will specify that here i think i'm missing one bracket like that and that that's it to enable authentication to our web application we will initialize the code uh in the configure method and we will come over here and say app dot use authentication and then in the configure services method to use the database and the adding identity together we will say services dot add identity and this will be um of of this will take two parameters one is the user which is identity user we will press ctrl dot to import this from microsoft asp.net core identity and we will say comma t role which will be identity role and then we will bind this to the entity framework store that we have and that is of type auth db context and close that next we need to create a migration now we will go to tools new git package manager package manager console and we will use entity frameworks tool to create migration so we will write add hyphen migration and give it any name but for this one i will give add authentication and click enter our add migration command has successfully completed and it has created a migrations folder over here this is basically a representation of our database and tables so now to execute this and basically install uh or create tables inside and the database inside our sql server we will use this command called update database and click enter the update database command has successfully finished as well and this should have created a database and tables for our asp.net identity inside sql server so to view that we will go to view server explorer and create a connection over here we will add a connection with the server name called dot and choose the database our database was called asp.net auth we'll click ok so we can see that the database has been created so let's see if the tables have been created or not i will expand on that tables and as you can see uh entity framework core and asp.net identity has created these tables inside our database our migrations have successfully completed and now it's time to implement identity and implement the register page and the login page so that we can use the microsoft core identity to basically register a user that comes to our website so we will go to pages and right click on here and add a new razer page we will call this register we will create a viewmodel folder over here and inside the viewmodels folder we will create a viewmodel class called uh register this is basically the model class which will use to represent the uh the inputs on the screen so we would need three things the email field the password field and the confirm password field so let's create these three properties so we need an email password and confirm password and we will decorate these with some some data annotation so email would be a required field so i will say required press control dot and we will import system dot component model dot data annotations and along with that i will also mention the data type for this one to be data type dot email address i will mention the same required attribute for the password for this one i will mention the data type as data type dot password and i will copy these two for the confirm password field as well and along with that i will also compare this to the other property which is the password and i will have an error message which says password and confirmation password dot match all right with that in place we will go back to our register dot cs html page and the actual class file and we will have a public property inside here so that we can represent our model i will import this from the view models directory and we'll call it register model i don't need anything on the on get method i can't name it register model because it conflicts with this one so i will just call it model and i will go back to my cs html file and style the page and add elements to the page as well so because we are using bootstrap 5 i will use bootstrap classes i will use the container class first and add a top margin so margin top of 5. inside that we will create another div and give this a class of row and then justify content center and also align item center because this is a flex box and we're using flexbox properties uh this will basically align everything uh horizontally and vertically we will create another div inside that and have a class which has a call sm of 12 so all 12 columns for the small screens call md 12 so all 12 columns for the uh md screens and call lg 4 so in in a desktop it will be horizontally in the center inside that we will create an h1 tag which will say register and we will give this a margin bottom of three we will now create a form tag and remove the action attribute from here and inside the form we will have a div for the validation summary so any errors that come out of the the model state will be caught here and represented here we'll give this a class of text danger next we will create three divs for our three input elements i will give them a class of mb 3 margin bottom 3 and will have a label inside that which will be of class form label and this is asp4 so this is for the form uh from the model uh this is for email and you can mention the name of the label the value for the label email address and then i'll also create an input element of type text and this will be asp for the same model dot email and the class for this one would be form control i will also add another span for the validation failure so asp validation for model dot email and we'll give this a class of text danger so i'll copy this div and we'll paste it two more times for our password and confirm password and similarly for confirm password now that that's ready we will create one last div for our submit button we'll give this a class of mb3 and have a button of type submit and the name of the button would be register and this will have the class of button and button primary these are all bootstrap classes and yeah it's very easy to implement so now that we have the register page ready uh let's go and spin our application up to see how this looks like i have my application opened i will go ahead in the url and type register to open the register page and as you can see we have the email address we have the password and we have the confirm password screen with the uh the submit button and this is all looking very pretty because of the bootstrap classes we have used let's go on and implement the on post property of the register method register page so back to visual studio and on the register.cshtml.cs file we will create a constructor first we will move this up and to the register model we will basically inject this constructor with two properties one is the user manager control dot on that and import asp.net core dot identity and this takes a type and the type that of our user is identity user and call this user manager and another one which is sign in manager this takes a type of identity user as well and we'll call this sign in manager and basically assign and create these fields so control dot and create and assign this property so we have two properties that we can use in the on post method so let's create the method for that so public void for now and on post i will call this on post async we will implement the async functions and first of all we will check if our model is valid so if model state dot is valid do stuff otherwise just come outside and return the page and to implement the return functionality i'll also implement a task of i action result and if the model state is successful we will create a new user so where user is equal to new identity identity user and this takes a lot of properties but the ones that we are interested in is username which will be model dot email and we'll also give the email which will be again model dot email we will have this object ready and we will use the user manager which is over here the user manager and it has a function an inbuilt function provided to us by asp.net core identity package which is create a sync and this takes uploads so it takes an identity user object which we have over here and the second property it takes is a password which we got from the model so model dot password and that so we will await on that because this is an async method and we will get the result so we will check if the result dot has succeeded that means our registration process was successful and our user has been created uh we will sign in the user so we will use the sign in manager and we will say sign in manager dot sign in async that's an async method as well and it takes a few things one is the user so we will pass in the same user from here and the next thing is is persistent we'll say false for now and being an async method we will use the await keyword and use this uh so once this has signed in um this is a task so nothing is returned back uh once this is signed in successfully we will return to the home page which is redirect to page and we have an index page over here so we will redirect it to the home page which is also called the index page in our case and in case this is not succeeded so we have any errors in here we will loop this and we will use the errors in the result so result dot errors and we will add the errors to the model state dot add model error error dot description so we will add all the errors in the model state so that it goes back and shows it to the page so now we have this ready let's go on and see if this is working or not spin up the application we are on the register page so we will give an email address so let's say semi one at mailingdata.com i will give it a password and we'll change this from text to being a password field now let's do that now back to our code and on the register page instead of type equal text we'll say type equal to password and the same for confirm password as well refresh the page again and sameer one at millionaire.com as our email address and password at one two three and password at one two three just to be a successful uh registration i will click on the register button and hopefully this should bring us back to the home page and it fails let's see what the error is i think the issue is that we are using the model property in our view over here but we are not really binding this uh using the bind property attribute so i'll i'll mention this as bind property so now the values coming back from the the model over here will uh be passed on to the identity user over here so with that change let's go back to our application and click refresh we will give the email address passwords again and click on register and as you can see now it has registered us successfully and has redirected us back to the home page let's go on to visual studio and see if we are able to uh view this inside our sql server so in our connected database i will right click on the asp.net users show table as you can see our user has been successfully created and we can see the user name as samir1 at melenator.com and the email as the same because we gave it like that so our registration works now so let's move on to uh basically fixing our layout page so that we can you know easily know if we are logged in or not so let's go to pages and layout and we can see we have two menus over here one for home page one for privacy we basically want to check if the user is signed in or not so to do that we will have to inject a service over here and before that we will import a package so we will say using microsoft dot asp.net core dot identity and we will now inject a service so we will inject the service the sign in manager sig and sign in manager which is of type identity user and then we will call this sign-in manager now we will use the sign-in manager to basically check before this ul starts we will write in some code over here we will see if sign in manager says if this user has been signed in and only if this user is signed in and this takes a user principle so we will mention user over here and yeah after that we will say only if the user is signed in we will show the the home and privacy pages so i've removed the ul from there and put it in the in the code block over here i will format this and otherwise i will also add an else column over here and otherwise i want to create a nav bar so a ul tag and inside the ul tag i will have an li which will have an anchor link and this goes to asp page login so if you if the user is not logged in they should be able to see two buttons login and register so this is for the login page and i will give this some classes so this will be a button and a button primary and similarly for the second li this will be called register and this will go to the register page i will remove the primary class from here and we will have to also give classes to the ul so that it looks nice in the navbar so i will give the us ul class the ul element a class of navbar nav and we'll display this as a flex so d flex justify the content to be in the end because this is the login register button we want the buttons over here at the end for a desktop and we will have the flex grow property to be one so that it occupies the complete space if there's no other nav um yeah and for the allies we will have the class of nav item and the same for the register button as well for some reason the formatting didn't work right and it removed the names of my anchor tags so i will remove this this curly braces over here and move the if statement right over here and if that is this i don't need an extra bracket over here um now i'll add the home uh value and the privacy privacy value to my anchor tags and i need another button for the logout so i'll say logout and it goes to the logout page later on when we implement that and this will be off button button primary uh yeah and basically i can do that or basically or i can add another ul and push the log out button straight to the to the end to the right hand side over here so i need another ul like this one and can remove both of these cut the log out from here paste it here i don't want this to grow because um i have the the original ul to grow so this just pushes that right to the end and hopefully this all works right and i'll format this quickly spin up the application to see uh refresh the page and now our logout button has been pushed to the side till the container so that's looking good it it feels like our user has been logged in so that because you can see the logout button yeah and once the user logs out we should be able to see the login and the register buttons and not the home and privacy anymore so let's implement the login page now because we still haven't done that coming back to the pages right click add eraser page we will create a login dot cs html and once that has been done we will create another view model so right click on the view model add a class called login and inside that we will have uh three properties one for the email which is a string we will have another property for the password again of type string and another one for remember me which will be of type boolean and we will annotate our properties uh with the required attribute control dot and import the packages so we'll have the required attribute for the email and the password and will have data types dot email address and similarly for password and we will leave the remember me as it is we will come back to our login dot cshtml.cs which is over here and we will basically have a property for this model import this from the vmware models directly create the name as model and like last time we'll not forget to bind this to a annotate this to the blind property so that we get the communication from the html page as well back to our cs class now we'll go ahead and create the login page the elements on the html file we'll start by creating a div with a class for container and margin top of five we will create another class another div element with a class of row justify content to be center and align items to be center as well just because this is a flexbox we will create another div with a class of column so call sm 12 call md 12 call lg 4 so a 4 width wide column for desktops inside that we will create an h1 tag for the login header and give this a class of margin bottom three we will now create a form remove the action from there and then create three divs inside it so the first one would be having a class of mb 3 then a label inside it with a class of form label and then the label takes to be email address the asp for this is for the model property email we will then create an input button input input element of type text asp for asp for model dot email and class is form [Music] control we will uh copy this or we will also have a span which will be an asp for validation for model dot email and a class of text danger we will now copy this div two more times at least one more time first to change this to a password password and password and we will have one more for the input checkbox so we will create a div class of mb3 margin bottom and then we will have an input type of checkbox the asp for would be model dot remember me and the class would be form check input and then we'll create a label and we will have the dia the class for the label to be called a form check label the asp for would be model dot remember me and then the text would be remember me with the question mark uh so this will this will be a check box so the users can take yes or no and the div for this one will have another class called form check so that it aligns everything nicely in a single line the another one which is the last one for the submit button would be a div of class mb3 this will have a button of type submit and the name of the button would be login will give classes button and button primary all right with that up let's go back to our application again refresh it and use the url to navigate to login page and we can see that the login form looks nice we have the checks box and the elements as well let's implement the login functionality so going back to the html we will implement the uh the on post method so void for now on post async and we will also use the uh return url because if uh the if there's a return url we basically want to redirect the user back to the return url um so we'll say string return url is equal to null and then we'll check if the model state is valid then we basically want to call the sign in manager but for that we have to inject that in the constructor we will call the sign in manager control dot import stuff and then pass the identity user type and then call this sign in manager we basically want to call the sign in manager to use its function we want to assign and create an assign property so we want to use this one to call the method password sign in async which requires a user object a password or the second one uses a username we have the username so we will pass in the model dot email which is our username model dot password the next one is persistent that we wanted to check if the user needs to be remembered so we will say model dot remember me and lockout on failure will just mention this as false and because this is async we will use the await keyword and also change our method to be an async method and use a task of i action result we will store this in a result and we will check if the result got succeeded that means the user is able to log in so that password and username was correct we will check inside this if the request has a return url or it doesn't have a return url or return url is an empty thing or a home page then return redirect to page and let's redirect the user back to the index page otherwise if the user got a return url redirect the user back to the return url and if this wasn't successful we will add the error to the model state dot add model error we will say username or password incorrect close that and we will return the page back let's see if that works so spin up the application again and refresh the website we are on the login page so i'll spin up the website again refresh the page we are on the login page we already have a user created so let's go on and try to just log in with that user and we have to change this to our type of password so let's do that first the type of this one should be a password field going back refreshing the page i know we can see that this user is registered but even then they should be able to navigate us back to the home page on a successful login so i'll mention the password and click on login and you can see it has redirected us back to the home page on a successful login so our login works uh fine here as well so now it's time to implement the logout functionality so that we can clearly see if we are able to log out from here or not so we will create a page over here called logout and to this page we will have some html over here we will create a form remove the action method over here and in this form we will basically ask the user do they really want to log out or not so we will have a div a class of container and margin top of five another div inside that with the class of row and justify content to be in the center another div for the column call sm 12 call md 12 and call lg 4 we will then create a paragraph asking the user if they want to log out and then after that paragraph we'll create another paragraph with two buttons in it the one would be yes and the another one would be no for the first one i will give it a primary class so button button primary and then i will also define because these are two buttons and only one form i will create an asp page handler so asp page handler this to be called logout because they're saying yes i want to log out i will give the classes to the next button so button button light and then margin left of 5 to separate these two buttons and a border of dark and then i will give this one an asp page handler of don't log out because the user has selected no so now i will come to the cs file of this one and implement the the post methods over here i will create a constructor and will basically inject the sign-in manager and this takes a type of identity user i will create and assign this property and now i can use this so i will create a public async task of i action result we'll call this method on post logout async and this is when the user has selected yes so the logout page handler comes here and i will basically use the sign in manager to call the logout function so sign out async and because this is an async function i will use await once the user has been signed out so asp.net core will handle all the sign out functionality for us and will delete the cookie and once the user has been signed out i will return the user to the home page or let's say the login page because that's the correct way to do it so redirect to page and mention the login page over here will copy this function and paste it over here and change this to be called post on post don't log out so that the other handler works we basically because the user hasn't has said we don't want to log out uh we'll just take them back to the index page uh yeah and this doesn't need an async method because there's nothing for us to use an async function so on post log out and on post don't log out has been implemented let's spin up the application and see if this is working or not refresh the browser it looks like the user is logged in so it's a good opportunity to test the logout button i will click on logout it goes to the logout page and ask the user are you sure you want to log out if the user selects no they will be redirected back to the home page if the user selects yes they are logged out you can't see the logout button and the home page and privacy page and um and you see the login and the register pages so the logout functionality works fine now we have to also see one more thing that even though we can't see the the index and the privacy page we can still access that but if the user wanted to go to the privacy page this is still accessible although the navs are not visible but we can restrict that functionality uh by using the authorized attribute so let's go back to our application and let's say we want to restrict the view of the pages uh index or just the privacy page for now just to show that it works so we'll go to the class file and decorate this class with the authorized attribute import this from asp.net core authorization and once we have that the user will no longer be able to see the privacy page if they are not logged in so let's go back spin our application again and if the user wanted to click on the privacy page we can see that it's going to account login because we still uh asp.net core thinks that this is the path to our login page whereas the path is just the login so let's go back to the settings the startup.cs and change that bit so on the services section on the configure services we'll call the services and we will configure the application cookie and this takes a config so we will say config dot and we can change the login path here and the cookie name and other stuff so let's change the login path to be at this location because our page is directly under the solution under this path so now if if somebody tries to visit the privacy page so let's go back to the application and sorry just visit the home page again to see nothing with the user is not logged in if somebody tries to visit the privacy page they are redirected back to the login page with the return url so once the user enters the login name and password they should be able to redirect to the privacy page and here it is so the user has been redirected from the login page to the privacy page because uh you know they were redirected back from there because they were not logged in so now our application is all complete and the login register and log out functionalities working are working as expected i hope you liked the video if you did press the like button subscribe to my channel and press the bell icon so that you don't miss my next video see you all in the next one you
Info
Channel: Sameer Saini
Views: 6,662
Rating: 4.9459457 out of 5
Keywords: ASP.NET Core, ASP.NET, ASP.NET 5, ASPNET, ASPNET Core, ASP.NET Core Authentication, ASP.NET Web Application, Login page in asp.net, asp.net login page, asp.net login authentication, asp.net login and registration page, asp.net core identity, Entity Framework Core, AspNet Core Identity, Asp.net Core Identity, asp.net core authentication tutorial, .net core 5, authentication, authorization, razor pages, web application, asp.net core tutorial
Id: B0_gM-wBlmE
Channel Id: undefined
Length: 58min 2sec (3482 seconds)
Published: Tue Jul 13 2021
Related Videos
Note
Please note that this website is currently a work in progress! Lots of interesting data and statistics to come.