Asp.Net Core MVC & Identity UI - User Registration and Login

Video Statistics and Information

Video
Captions Word Cloud
Reddit Comments
Captions
quick demo of this video in this asp.net core MVC tutorial will Implement user registration authentication authorization and user profile management all of these features can easily be implemented in your MVC application with the help of asp.net core identity Library finally as a bonus I'll be providing you with the necessary resources for further customizing this application I am sure you will find this tutorial helpful for your upcoming.net core projects so please watch till the very end sub YouTube Welcome to quota fiction let's go ahead with building a complete authentication system in asp.netco MVC before going forward I would like to thank for your donations through PayPal and other platforms for my previous Works in order to make more and more quality tutorials like this you can also support me through PayPal and other platforms details are given in video description I have already discussed this topic in one of my all video using asp.net core 3.1 it's been three years now the same steps will not work with the latest.net coercion so I decided to make that video again with the latest version of.net now without further Ado let's get started with the topic it is obvious that there are two ways to add the identity library to an asp.net core project you could add the identity Library while creating the project or you could add it later in the development process independent of when you add the library into the project you could follow the steps that I'm showing here so first of all let me create a DOT net core MVC project now select this project template here asp.netco MVC you could easily find this project template if you select C sharp from this first drop down and web from this last drop down here click on next I will name this project as auth system select the location where you want to save the project click on next we are creating this project in dot net 7. if you select this individual accounts from this drop down the identity Library will be added to this project however I believe that it would be better to import the library and its UI interfaces later for our understanding of the topic we are discussing since we are creating this project for demonstration I will uncheck this https configuration here let's create the project so here we have the brand new asp.net go MVC Project without making any changes inside the application let me run this now this is how the fresh MVC app looks like now back to visual studio now let me add the identity Library into this project before that let me open this project configuration here so that you could see the install and you get packages into the project currently we don't have any package installed into this project you could check that inside this dependencies also we only have some Frameworks we don't have any inugate packages installed now let's build this project now let's add the identity library for that right click on this project then add new scaffolded item from this left panel select identity then select this identity here click on ADD now inside this window you could see the list of Razor Pages available in asp.net core identity you could select the Razer pages that you want to customize for now I will be selecting these Pages login and register so the rest of these pages will be loaded directly from the identity UI library with the default behaviors and features now from this option here we could select a layout page for the selected views here so I will select the default MVC layout page which is inside this views shared folder underscore layout.cshtml click on ok now here we have to provide a DB context class for that click on this plus button I will name this class file as auth DB context click on ADD now we have to select a model class for the user click on plus button here I will name it as application user now click on ADD as you can see behind the scene it is installing the required packages into this application finally here we have added the asp.net core entity into this MVC project and these are the required and you get packages which you can see inside this dependencies packages here so this is the main package added to UI it contains the Razer pages that we just talked about and here is the newly added area identity if you expand that you could see these folders data and Pages inside these Pages we have the Razer views for the respective views login and register and inside this data folder we have the model application user for Entity framework and the corresponding DB context class now let me build this project again while building this project we got an error saying that there is a missing using statement which is inside this program.cs file like we had some changes inside the application after adding the library we also have some changes inside this program.cs file also we'll next explain that in a bit now let's add a missing using statement for this model Clause here for that you can use the shortcut hold Ctrl then press period so here we have the namespace areas dot identity dot data and you could verify that inside this model class application you saw identity.data now back to this program.cs file which is the starting point for executing a.net core project inside the file we have mainly two objects first of all we have Builder which is created as a result of invoking this method here create buildup we'll use this Builder object to add more services into this application and here we have the second object app which is created as a result of calling this method build from Builder and this app object is used for the configuration of this project finally with the execution of this run method the whole application is opened in our default web browser so that's the overview of this program.cs file now in order to view these phraser Pages log in and register we have to add the support for Razer Pages inside the application that we can do inside this program.cs file like this Builder dot Services dot at Razer pages by default newly created MVC project only had the support for the conventional control of with separate views now we have added the support for Razer Pages now in order to add browse for the identity UI eraser pages into this application we have to do this by default here we have the routes for the default conventional MVC controller now let's add the routes from Identity Razer pages so that we could do this app dot map Razer Pages that's it all of the routes for the identity UI Razer pages are already configured inside the Library we are only importing it here now let's build this project now let's try to access these phasor Pages for login Android itself from Identity UI so here we have the running instance in order to access the login page here is the corresponding URL identity Pogo slash account forward slash login boom that's it and you could see the registration form like this forward slash register now as I already mentioned the meat of this video is to know how to customize asp.net core identity as per our requirement we'll get into that in a bit first of all let's start with small customizations that is showing both of these forms for registration and login form inside a bootstrap nav tabs so back to the IDE let's start from this default layout page here so this layout page contains the HTML wrapper for rest of the controllers or views inside this MVC application and here you could see that here we have already imported bootstrap by default so we'll be using the same for styling the user interface inside this application and here we have the global stylesheet site.css which can be seen inside this folder here now inside the booty we have the header inside that we have shown this now bar here bootstrap navbar and then within this container this place called the add render body will be replaced with the HTML from this given routes here so that's the overview of how this user interface is rendered inside a default MVC application now to show both of these Pages login and register inside a tab control apart from this default layout page I'm going to create a layout page specific to both of these Pages login and register containing a tab control then I will add inside this identity Pages folder here so right click on it then add new item then select this Razer layout here and let it be underscore auth layout click on ADD now this layout is created as a main layout which is not what we want we already have a main layout underscore layout here we'll be using that as a layout for this newly created layout here so let's get rid of these HTML codes and let's specify the layout for this layout page as this default layout here so here we go layout is equal to forward slash views forward slash shared forward slash underscore layout C HTML now let's create a tab control you could see the corresponding documentation here tabs will be customizing this bootstrap now Taps as per our equipment first of all we need a div for bootstrap grade system now let's put everything inside this div at Center and here we have a grid column having five column space let's apply a top margin of the range 5. we'll be wrapping the tap control inside a bootstrap card so here we have the corresponding outer div now for the further customization here is our custom class login logout card first of all we have the card header then after that we have the card body the tab control header will be shown inside this card header here with this unorder list now these are the necessary tab header classes nav then nav tabs then card header tabs now let's add two Li elements for both login and register having the class nav item inside that we have this anchor element having this class nav link now let's provide the corresponding URL inside this attribute that I will copy paste from here inside that we will show this text login now like this we need one more Li element for registration so I will copy paste this here we corresponding URL will be like this forward slash register now based on the selected tab corresponding content should be shown inside this card body for that I will add this div with these classes raw then justify content at Center so here we have a bootstrap grid and we want to apply margin on y-axis of the range 4. inside that we can have this placeholder in VC placeholder at render body so here we have the new layout page auth layout for both of these Pages login and register now for this register and login page we want to set this new layout page auth layout as its layout so let me copy this and pasting here inside this register page now let's provide the corresponding relative path child power slash areas forward slash identity forward slash Pages forward slash underscore Aus layout now let me copy this and pasting inside this login page let's build this after successful build back to the application looks like we have an error the layout view could not be located the following locations were searched after SRO inspection I didn't find any type points I will give one path here if you face the same problem even after providing the correct relative URL for the layout page you could do this right click on this layout page then go to properties then inside this build action drop down select content okay now let's close this properties build this project again back to the app but this time we have another error saying that the following sessions have been defined but not have been rented by the page that we have just created which is the auth layout page so we are not using this script section inside our Aus layout page you could see this script section inside the identity Pages login and register it must be loaded inside the default layout script section but in between these pages and this layout page now we have this middle layout page auth layout so in order to keep the connection inside this new layout we have to specify the session like this add section scripts just copy paste this section from the default layout here that's it let's build the project again back to the app boom see here we have the tab controls and inside the tab you could see the pages from the corresponding views now to customize this tab control open the global style sheet site dot CSS now here is the custom CSS for styling the element tab control save this build the project back to the app that's it okay now based on the current page we are rendering we have to mark the active tab from this tab control for that we need some jQuery so back to the auth layout if you check the default layout page you could see that the jQuery library is already added into this project by default now we can make use of that to Mark the active tab from this tab header so here we go so first of all we can have this script tag everything inside this function will be executed once the page is completely loaded now first of all we have created this variable current page and which is initialized with the URL of the current page and then we are iterating through the LI element angle elements that we have provided here so here we have the each function inside that we have the Callback to be executed on each iteration and inside that we have this variable which is corresponding to each of the anchor elements and then here we have the if Clause within that we are comparing the current angle element hrf attribute that we have provided here with the current URL and based on that we are adding the active class to it so this will highlight the respective tab header so let's build this back to the app So currently we are inside the login tab now let's switch into the register tab boom now before going forward I want to change this app font into Google font Roboto which is my favorite font so let's search for Google font in order to remove previously selected fonts click on this remove all here so here we have the Roboto phone select it and choose the appropriate font weights 300 400 and 700 copy the second link tag here back to the app open default layout page and let's paste it inside the header open the global search sheet site.css and let's change the font family here now here we have the phone Roboto now as a backup I will provide this send serif build the project back to the app that's it so that's all about tab control navigation next we're gonna customize this registration form here here we are only asking for the user email and password now into this registration form I want to add the extra fields for first name and last name how can we do so for that back to the project here first of all we want to understand how this asp.net core identity Works inside this MVC project as you already know here we have the corresponding Pages for login and register and inside this data folder we have the model classes for NDT framework now inside the Library this model class identity user represent a user model and here we are just inheriting the Base Class into this application user so that we can extend the user model now into the user entity we have to add these properties for first name and last name first of all we have first name which is of the type string now you could see the green sprinkly line along with this property indicating this property they must be initialized somewhere inside the class in order to hide this indication here just hover because on the property like this then you could see this bulb symbol expand it then go to this option here suppress or configure issues inside this severity select silent that's it now let's specify the column data type so here we have the attribute column let's assign the data type with this parameter type name Let It Be invoke a hundred now since we are adding a personal data we have to add this attribute here personal data now let's copy paste this for the next property last name last name now along with the default properties inside this identity user we have added these two properties you will see all of the properties inside this identity user model once we do the migration so here we have done with the application user model now here we have the askdb context class which is also inheriting from the corresponding identity DB context class here now as you know in Entity framework we will interact with the DB physical DB so an instance of DB context class so an instance of this auth DB context will be automatically created inside this program.cs file here so dependency injection you could see it here we are creating an instance of auth DB context through dependency injection so into this DB context Constructor parameter here we have to pass the DB provider it might be SQL Server MySQL Etc and the connection string to the physical DB so here we have specified the DB provider as SQL Server by invoking this method use SQL server and here we have provided the connection string and this connection string must be the inside this app settings.json with the given key auth DB connection now instead of this logdel DB instance I'm gonna use a separate instance local and the name of the instance would be SQL Express and the corresponding DB would be auth system DB since we are using the local authentication method we have set trusted connection as true and in order to execute multiple queries at a given time we have set this attribute here now we have to set one more attribute which is trust server certificate so here we have done with the DB connection string now if you are having any difficulty in generating a connection string according to your machine let me know in the comment box below now here we have set everything for the DB migration so first of all build this project after successful build select the project from solution Explorer then go to tools then in you get package manager then package manager console in my case it is open inside this bottom panel here now first of all let's create a migration with this command add migration and let's provide a name here initial create hit enter as a result of that you could see the new folder migrations here within that we have a c-sharp file with the given migration name here containing the C sharp chord for generating the corresponding SQL Server tables so far we have not created a corresponding physical DB in order to do so we have to execute this second command here update database hit enter it looks like we have done the migration without any problem now if there is any error in the given DB connection string here you will get an error by executing this second command update database if that's the case double check your DB connection string provided here okay fine now let's see the physical DB that we have just created through migration for that let me open the management studio now let's connect with the same SQL Server instance that we have given inside the connection string expand this databases so here we have the new database auth systemdb that's expand it and here we have the tables so these are the default tables inside and asp.net core identity Library it's already mentioned inside this msdn documentation here you could see each of the entities and what they represent I'll be providing the necessary references like this in video description so please check it out so this table SP net users represent the users inside the Library let's check its design here you could see various columns for a user entity along with that you could see the newly added Properties or columns here first name and last name now with that being done back to visual studio next we are going to add input fields for newly added columns first name and last name so head over to this register page here actually this is a Razer page so this file with the extension cshtml contains the front-end HTML part of the page underneath it you could see a file with the extension ending with cs which act as a code behind similar to the old aspx Pages now this page is completely written for the default behaviors inside the identity but we have to make some changes as per our requirement for now inside this tutorial we will be customizing this registration form for the newly added properties first name our last name now if you check the Razer page you could see these methods on get async which is get invoked when we load the page and when we submit this form this pause method will be invoked now if you check the page cshtml you can see that all of these fields are designed with the input model which you can see inside this page as input model now to add input fields for first name and last name we have to change this model here input model so first of all we have first name now with this attribute this play we can specify the display name which is the label that you want to show along with the corresponding input field so here we go name first name now let's specify the data type of this text field as text now let's make this text field as required now let me copy paste this for last name and let's make the required changes here now inside the registration view first of all let's get rid of The Unwanted HTML elements so here we have the corresponding HTML for the registration page we don't need this H1 element and let's get it off this grid system from bootstrap we have already added that inside the additional layout auth layout let me build this back to the app boom that's it now let's add the input fields for first name and last name we'll show both of them in a single row so here we have the div row we will have two columns with equal width now let's copy paste this email div here input DOT first name now let's make the appropriate changes inside these elements here now let's copy paste this for last name inside the second div this is for last name sorry before go to update the label here first name last name let's build the project and then back to the view boom that's it so here we have the new controls for first name and last name so here we have done with the registration form design now let's update the submit or post method for feeding the data from these two newly added text boxes so here we have the c-sharp file this on get async method will be called for loading this form here and when we submit this form this post method will be invoked we submit the data from the form can be received with this object here input so here we have the newly created user instance which is going to be inserted into the physical DB industry of the code now we just need to add post name and last name into it so user DOT first name is equal to input DOT first name now you could see the suggestion from the IDE for populating the last name also so hit tab now let's place them in a separate line like this username and email is assigned to corresponding properties here and the user will be created with this method create a sync into that as a parameter we have passed the password and that's the basic overview of this method if the operation when successful we will deal that inside this if close you can go through the rest of the codes here one feature at a time so that you can understand what is going behind the identity Library having an overall idea will be helpful to customize the library further now let's build the project back to the view now let's talk about default validation for this registration form and related configurations first for I will disable email verification for a newly created account to disable the feature head over to the program.cs file you could see the service added here add default identity and here we have the configuration require confirmed account to reset this property as false apart from assigning True to this property there are some additional configurations to be done inside the project then only the very verification mail will be sent to the corresponding given email so that's the reason we are not implementing that in this video if you are interested we can discuss that in another tutorial let me know in comment box below now let's build this project back to the app now to see various default validation inside the registration form just submit this fresh form so that you can see the various default validations here we have apply required violation for first name and last name but inside the actual Entity framework model we didn't mention these properties as required so I'm gonna remove the validation required validation for these properties first name and last name now let's update the corresponding view here we just need to remove this pan let's build the project back to the view submit the fresh form again now let's provide a random email here I will provide the password as one two three then you could see other validations coming up like number of characters must be between 6 and entered now in order to see all of the existing default validations inside the identity back to program.cs file we can configure the validations like this build.services.configure and we want to configure identity options so here we have the Lambda expression with options now I'm going to disable one of the default validation which is need of an uppercase character so in order to disable that we could do this password dot require uppercase to set that as false here in order to see all of the default validations right click on this require uppercase then go to definition you could see various validations inside this password options require length that is minimum length should be 6 and there should be at least one unique character require known alphanumeric character meaning a special character the need of lowercase need of an uppercase required digit by default all of these are set to true now we have just disabled this validation here require uppercase okay now let's build this back to the form let's reload this now let's create a new user now first of all I will try the password ABC and here we have the validation error it must be at least six character because of this default validation we have to have a special character so I will be appending either way it's simple here and we also need digits with this validation here so I will append one two three so a b c at one two three is the password we have to provide the same here ABC at one two three now let's submit the form boom that's it it looks like everything went successful now let's check inside this table users you see here we have the newly created you saw Eva Elliot you could see the email here then the password is passed inside this column so user registration is properly working now by default inside identity Library when we create a new user the same user will be logged in by default which you can see inside this success if close here if there is no need of email confirmation you could see the code for sign in the same user So currently inside this application we have already logged in so next we are going to show the logged in user email address along with a logout button inside the snap bar that will be then inside this default layout page here so here we have the now bar first of all remove these nav links for home and privacy which is here inside this unordered list now to show the logged in user there is a partial view that comes with identity Library which you can see here underscore login password we just need to render that inside this div here so here we go partial name is equal to underscore login Powershell now let's build this project then back to the view here let me reload this page see here we have the greeting message with the email address and here we have the logout button now for the proper placement of these elements let's update this view instead of this container fluid we need a container div now to move this div to the right side we can have this class Flex raw reverse build the view back to the app now let's start this logout button that's it currently now you could see these links for register and login we have already implemented this registration form now let's go ahead with this login form here inside that we want to login with the newly created user credentials before that I want to remove these links for register and login from this app bar since it is already present inside this tab header we don't need a separate links here so that is coming from this partial View login password inside that first therefore it checks whether the user is logged in or not if the user is logged in user email address and a logout button will be shown and this else part is responsible for these links here so let's get rid of it now let's customize this login view so here we have the corresponding razor page login cshtml First of all we don't need this talk H1 header we only need this login form so let's get rid of these grid columns here instead of four columns we need 10 columns in order to place it at Center we can have this class justify content Center let's build the project back to the view that's it in this tutorial we are not implementing the email verification feature so we don't need this link and this is just to navigate a fresh registration form which can be accessed with this tab control and we are not implementing this provision for forgot password inside this tutorial so let's get it off these links in both of these forms I have kept the top Edge to header it's up to you to remove or keep it inside this login form I will change the text to something like a welcome back now let's try to login with the newly created user credentials now let's try to login without selecting this option for remember me boom that's it so here we have successfully logged into the MVC application now let me show you the browser cookie worldview session is stored for that right click then inspect then switch to this application tab then from this left panel select cookies inside that we have the URL of this application if you select that you could see various cookies stored inside this application now this is the item we are talking about currently logged in user session will be stored inside this cookie here now inside this XPS column you could see the value session meaning that the correctly logged in user cookie will be lost once we close this browser now let's try to re-log in with the remember me option select this option remember me then login now let's check the cookie see this time we have a date after 14 days meaning by default if we select remember me option inside the login page the user session will last for next 14 days or two weeks so that's all about logged in user cookie now let's check how to retrieve logged in user details for example logged in user ID which we have inside this use a table here which is a crucial data which will be stored in other tables to know the activities done by a particular user now let me show you how to retrieve and display logged in user details inside this home page here so here we have the uh home controller and here we have the corresponding index view so first of all our retrieved user ID inside this home controller here for that we have to make use of the user manager object which you can see inside these login and register Pages here inside this code behind you could see this user registration is done with an instance of user manager as you can see here see we have created the user with an instance of user manager we'll use the same instance inside this home control also for that first of all we have to inject the user manager inside this home controller Constructor so user manager which is of the type application user now as a best practice as you can see for this I logo parameter here there is a corresponding private read only property and which is assigned with the parameter here we will do the same for this user manager also with that when you place the cursor over this parameter you could see a bulb icon here expand it and then select this option create and assign field user manager now to prefix this property with an underscore like this logo let's rename this for that you can use the shortcut hold Ctrl then double press r underscore user manager hit enter so here we have injected an instance of user manager into this controller now to retrieve the logged in user details we could do this underscore user manager from that we can call this method get user ID and let's pass the user here this dot user which is corresponding to the logged in user this is a claim which is details of user saved due during the login operation okay this is not an instance of this application user you could verify that if you hover the cursor on it you see it is claims meaning details of users saved during the login operation now let's save this inside the view data within this key user ID now let's print that inside this index View now here we go user ID now we can retrieve that from the corresponding view data let's build this project back to the view boom that's it you could see the same user ID inside this table also so that's how you can retrieve the user ID or user claims saved during the login operation now let me log out from this application even though we are logged out we are inside the home controller home controller will only be shown for the authenticated or logged in user in order to prevent unauthorized users from accessing this home controller inside the controller home controller we just need to add this attribute authorize so we are telling that this is not for unauthorized users let's build the project back to the view see here we are redirected to the login page so this attribute otherwise is already configured inside the identity Library you could verify it again we are going to access the home controller which is what we have the default route inside the application by default it will load this home controller index action method Let's see we are getting redirected to the login page now we have to do the reverse operation also that is once a user is already logged in if you try to access this login form or register view we have to redirect him back to the uh home page that inside this login page backend inside this get async method you just need to add this if Clause if user dot identity dot is authenticated is true meaning that this user is already logged in now we just need to redirect him to the home page like this now let me copy this and pasting it inside this register on get async method let's build this now let's try whether it works or not here we are successfully logged into the application now if I try to access the login page or registration page will be redirected back to the home page now if you click on this email address you could see the corresponding use of profile details update phone number email address could be changed password can be changed then two-factor authentication personal data Etc and Etc as I mentioned already to make use of the default features like email verification or this two-factor authentication or forgot password we need extra configurations if you guys are interested in implementing these features we could extend this project in upcoming tutorials let me know your suggestions in the comment box below now if you want to customize any of the identity features on your own you could follow the same steps that we have initially followed inside this project just right click on this project then add newscap folder item select identity click on ADD select the appropriate views from this list and then select the same DB context from this drop down which is auth TB context click on ADD it will add the corresponding View and then you can customize your own I have given the necessary MSD and documentation links in video description please go through that you could download or clone this project from the GitHub repository link given in video description there are a lot of helpful MVC tutorials in our Channel links are given in video description under the title related videos hope you will enjoy it if you found this video helpful please consider subscribing to the channel if you haven't yet please like and share this video with your friends and colleagues so that they can also benefit from this have a nice day bye
Info
Channel: CodAffection
Views: 25,698
Rating: undefined out of 5
Keywords: CodAffection, asp.net core mvc login with Identity, add asp.net core identity to existing project, asp.net core customize identity, user authentication in asp.net core mvc, login and logout in asp.net mvc, .net core mvc user authentication, add asp.net core identity to an existing project, asp.net core beginners tutorial, asp.net core identity, user authentication and authorization in asp.net core, asp.net core mvc tutorial, asp.net core mvc login and registration
Id: wzaoQiS_9dI
Channel Id: undefined
Length: 39min 36sec (2376 seconds)
Published: Mon Mar 13 2023
Related Videos
Note
Please note that this website is currently a work in progress! Lots of interesting data and statistics to come.