Asp.Net Core Web API - Login and Logout with Angular 7

Video Statistics and Information

Video
Captions Word Cloud
Reddit Comments
Captions
quick demo of this video tutorial in this video we will implement JWT authentication login and logout in asp.net Web API project with angular 7 so here we have the final project after implementing JWT user authentication in order to show you the demo of this application first of all let me sign up a new user username will be Maria one-two-three Maria Rodriguez password will be 1 2 3 4 finally submit the form so here we have successfully created the user record for Maria username is Maria 1 2 3 then password will be 1 2 3 4 hit enter so here we have successfully authenticated inside this application using GWT auth system inside this home page we have shown the details of currently logged in user Maria Rodriguez in order to sign out from this application you can use this logout button here so inside this application we have discussed a lot of things starting from what is meant by JSON web token authentication how to implement this and web token authentication inside asp.net Web API project how to design this login form in angular 7 how to consume secure dotnet kabab API method from angular 7 and we have demonstrated the integrity and security of JSON web token using this application in short we will cover complete JSON web token authentication in dotnet cop web api with angular 7 so please watch till the end of this video tutorial before starting this video I would like to ask you a favor if you found this video helpful please thumbs up this video if you are new here please please subscribe to this channel and click on the bell icon to get notification about my new videos most of the video lesson here also has a written blog post you can find the link in video description you can grab code from the as well what's up YouTube welcome to God affection in this video we are going to implement JWT user authentication in asp.net web api using angular 7 in previous video we have discussed how to implement user registration in SP dotnet code web api using angular 7 and identity core so in this video we are going to update both dotnet core web api and angular 7 project from previous tutorial to implement JSON web token authentication so before watching this authentication login and logout tutorial please watch user registration tutorial I have given the link in force comment and video description before getting started with this topic I would like to thank for your paypal donations for my previous books in order to make more helpful and quality tutorials like this you can support me through PayPal donation I have given the donation link in force command and video description without further adieu let get started so here we have the previous angular 7 user registration application for client-side currently this application looks like this into this application we have to accommodate a loking form also after that we can update dotnet Coco BPI for JWT authentication so here we have the current application structure under this user parent component we have to create one more component for login form so here we have the component Logan now let's create this component for that I'm going to open one more terminal here then we have to use this angular CLI command ng G for generate C for component and we have to create this component under this user parent component component name will be login and we have to skip the creation of spec file which is for test purpose I will reset this flag as false and we want to skip the creation of component specific style sheet for that you can add this flag here double - yes hit enter newly created component can be seen inside this login folder here we have one typescript file and one HTML file now we have to update application routing for this newly created component so here we have the routing module app routing module like this registration route let me add one more children route here I will copy paste that here this is for logging so path will be login then then component will be login component we have shown this registration component HTML inside this user component HTML here with this router outlet tag instead of that inside this user component we have to show HTML from both components registration component and login component so I'm gonna do that with tab control so first of all let me get rid of these existing HTML from here first of all we need a div with class wrap up inside that we need another deal with class wrapper - do inside that we have another div with class tab header inside this day we can have hyperlink for sign in and sign up first of all we have an h2 header for this element we have to specify the hyperlink reference in short href which can be specified using angular attribute router link so here it is router link and here we have to specify the route that we have configured for the login component so it will be something like this forward slash you saw for slash login when we navigate inside this route here we have to set the class active for this h2 element for that we can use this attribute router link active is equal to here we have to specify the route that we have to add so it will be active inside this hyperlink text will be in like this we have to create one more h2 header so let me copy this and paste it below that router link will be something like this for / user / slash registration corresponding text will be signed up just below this deal we have to show the component HTML based on the active tab for that we will have another div with class row inside that we will have another div with class called MD - 10 and we need an offset of 1 column so we have to specify this class offset MD 1 inside this we will have this router outlet tag so based on the active tab here corresponding component HTML will be replaced inside this router outlet tag here now let me update the global style sheet here Stiles dot CSS let me remove existing CSS rules then I will paste the new rules here let me save all of these modifications then back to the application here currently our application looks like this we have to do few more modifications before that inside this registration component form we don't need this header anymore so let me get rid of this header so inside this registration component HTML I will remove this from here we only need this form for user registration let me save this then back to the application so that's it there are some disallowance inside the application caching of previous global stash it might cause this problem so let me clear the browser cache for that let's go to the history tab here and click on this clear browsing data inside this Advanced tab I have selected all time as time range and I have selected this option image and files to be cleaned click on clean data that's it now back to the application reload this page inside this user component here we have some typos instead of wrapper div it should be wrapped if instead of tab header it should be tab head let me save all of these modifications here then back to the application boom that's it so inside this signup form here we have the user registration form that we have implemented in previous video and inside this sign-in tab here we have to show a login form for user authentication inside this tab you can already see the default HTML from login component now let's update the default HTML inside the login component HTML let me get rid of this default paragraph from here first of all we need a form we don't need this action attribute here let me get rid of that instead of that I will add a local reference form inside this login form we will have two controls one for username one for password if the form is complex or which is to be killed in future then reactive forms approach would be a better option so here we have a local reference form which is equal to ng form and I want to add a single class for this form so class is equal to Mb which applies margin bottom of the size 4 and I want to prevent the autocomplete from previous posted form data so we can set this property autocomplete as off inside this form first of all we will have a deal with class form - group inside this div we will have controls for username so first of all we have the label we don't need this for attribute here label text will be something like this username after that we have to have the input control input you don't need this type attribute by default it would text in order to design this template driven form we need a component property so I will define the property here form model it will contain properties like username and password username and I will initialize this property with empty string after that we have password which is equal to empty string now using this poor model property we can bind input controls inside the form here so first of all I will set the local reference username is equal to ng model after that we have to set the name attribute it will be username then we have the two-way data-binding ng model is equal to form model dot username we need one more form group div for password also so I am going to replicate this selection here so you can use this shortcut alt shift then downward arrow instead of username we have password then we have local reference then name attribute two-way data-binding after all of these input controls we need a submit button for the form for that I will copy this registration signup button from the corresponding component HTML here let me copy this div from here then I will paste that here we don't need this disabled attribute after that we need to change this button text it will be login since we have designed this form using template driven approach we have to add the corresponding module inside app module dot T as file here so we have to import forms module here forms module let's add the same class inside this imports array here let me save all of these modifications here back to the application inside the sign-in tab we should have a login forms sorry we forgot to add bootstrap class form control into these text boxes here so back to the component HTML let's add the corresponding class class it will be form - control let me copy this and pasting here for password let me save this back to the application boo so here we have the sign-in form with username and password text box now just above the login form here we need an image so first of all let's add that image inside this assets folder IMG here so here is the image let me drag that and place inside this IMG folder here just about this form element here we need an IMG control corresponding path will be something like this forward slash assets 4 / IMG inside that we have this image or single user dot PNG for this IMG control we have few classes so class is equal to so here we have the class MX - auto it will align the image in center horizontal center after that we have D block we will set the display as block let me save this then back to the application here that's it now I want to set this password text box type as password so that characters entered into this text box will be hidden so back to the component HTML here then I will set the type here type is equal to password save this back to the application now I want to implement form validation for these two input control here both of these username and password is mandatory for this form submission so I'm going to add the required attribute for both of these controls here required same can be added to the next password text box here we are not going to show the validation error indication we just disabled this login button whenever when this form as a whole is not valid so we can add the disabled attribute for this submit button here it will add this disabled attribute whenever this form as a whole is not valid in order to reference this form here we have the local reference form so we just need to do this form dot invalid let me save this back to the application here initially you can see this blurred submit button login here if you populate these form controls properly then this submit button will be enabled for now we can stop the angular development let's switch into web api project from previous tutorial we have to implement the JSON web token authentication so here we have the dotnet Korb API project from previous user registration part before updating this project let's check what is meant by JWT authentication and how it works for that you can go to this website JWT dot io so this is the official website for GWT you can go to this introduction for more information about this authentication here you can see the definition decent web token is an open standard that defines a compact and self-contained way of securely transmitting information between parties as a JSON as per the definition GWT is an open standard which provides a secure way of transmitting information between two parties as this own object for example if you go to this debugger here you can see the sample JSON object string here it has three parts the first red part is called header and this is called a payload and here we have the signature all of these three parts are separated with a period in between de we will discuss what we meant by these sections held our payload and signature in may be before that let's discuss there WT authentication flow chart so first of all on the left side we have the client side application which is the angular 7 application and here we have this server which is the web api implemented in asp.net core so first of all from this angular 7 application we will send a request with credentials like username and password which will be sent as a result of this login form submission here so upon receiving that request at the server side JWT auth system will retain a JSON web token if there is a use of with given credentials username and password so as a result of this request and response we will have a JSON web token inclined site which will be stored inside this angular 7 application in browser local storage that JSON web token will be similar to this one here after this successful authentication we have to append this JSON web token for all the subsequent requests which demand authentication upon receiving this request at server side it will extract the JSON web token and it will verify the token basically inside this talk and we have information about the user along with these details we will have an expiration time so if the token is expired this request will fail if there is a manipulation inside this token which we have saved inside the browser local storage which can be identified by VG's and auth system if the token verification is successful it will process the resource and it will return the response back to the server so this is the workflow of JSON web token auth system now let's briefly discuss the structure of the token mainly it consists of three parts head door and we have payload and finally we have the signature all of these parts are separated with a period in between them inside the header they will have these two informations type and algorithm inside the type attribute we have JWT means data stored inside B Jason is a decent web token and inside this a LG attribute which stands for algorithm means we have shown this signature last part of the JSON web token as a result of encryption that encryption algorithm should be mentioned inside this attribute a LG here in most of the case we will use sha-256 algorithm or RSA algorithm so here we have used sha-256 algorithm and here we have the second part of the token which is payload inside this payload will bestow information about the token or use during token generation there will be some default claims such as issued at means or time at which this token is generator then we will have the expression time at which this token will be expelled like that there might be some default claims other than that we developers can define or store some custom claims related to user such as you saw ID role etc and keep in mind that you only want to store required data since IV token otherwise bandwidth consumed for the transmission of the token will be higher other than that inside the payload do not store security data like password because both of these parts header and payload are represented as a result of basic C for URL encoding and thereby these two parts header and payload can be easily decoded at the client-side so better avoid storing security data inside the payload part now we have the final part of the token which is signature which is responsible for the integrity and security of the token which is generated as a Celt of the encryption here first of all we will encode both header and pello using base 64 URL encoding and we will separate them with a period in between them so this string here is same as that of the first two parts here okay and we will encrypt this result using sha-256 algorithm for this encryption we will use a secret code so this secret will be stored only at server side it should not be disclosed to anyone outside and finally we will concatenate into this existing token here so this is how the JWT token is generated once it is issued it will be stored at the client-side browser and we have to abandon talk and for further subsequent requests wisdom and authentication at the server side this token will be verified as a part of that first of all it will decode these two parts here header and payload which we have encoded during generation so so inside this payload we will have the expression time if the token is expired this verification will fail if there is a manipulation from client side for this talk and because this token will be saved inside the local storage so anyone can manipulate this data but upon receiving this talk and at server side it can check the integrity of the token because both of this header and payload are encrypted inside this last signature part here if there is a modification in any of these parts which can be compared inside the original data from this signature part here so that's all about Jesus and web token as per the definition here you can see that it is a standard it defines how the JSON web token is to be implemented in order to implement this JSON web token in a technology we have to depend on providers that you can go to this libraries here depending on the development and we are we have different packages here for dort net framework applications we have these much packages and for Python we have different packages like that depending on the development environment we have different packages to implement this open standard for JSON web tokens so let's look how we can implement JSON web token user authentication inside this doughnut code web API project here so here we have the dotnet core Web API project from previous user registration tutorial inside this start applause function configuration services we have to configure this application for JSON web token authentication for that we have to call the add send occasion function from this services variable so add authentication inside this function we have to configure the application for JSON web token so inside this function we will have a lambda expression with parameter X so basically inside this function we will set different types of authentication schema as JSON web token authentication so first of all we have default authenticate schema and we want to set that as this and web talk and authentication so we just need to do this JWT beer defaults and we have to add this namespace Microsoft espied or not Co authentication dot JWT bearer inside that we have this authentication schema like this we have to set few more authentication schemas so let me copy this and pasting below that two times this time instead of this default authentication schema we have default challenge scheme and finally we have default scheme after setting these authentication schemas we have to configure this JWT itself for that we can chain one more function call to this add authentication function JWT be error function can be called inside this function we will have another arrow function with parameter X first of all we have to reset this property require HTTP meta data as false means using this require HTTP metadata property we can restrict the authentication resources to only requests which is of the type HTTP we don't need that restriction so we have reserved this property after that we have this property safe token we have we said that property to false means after a successful authentication whether we want to save that talk and inside the server or not we don't need to save the token in server so we have reset this property as false finally we have to define how do we want to validate a token once it is received from the client side after successful authentication for that we can use this property token validation parameters is equal to new talk and validation parameters inside this class we have to configure a few properties first so far we will set this property validate issue signing key as true so that the system will validate the security key during the token validation after that we have to provide the issue signing key which we have discussed inside the official website documentation here we have to provide this secret for the encryption of the signature part in token so we have to assign the key inside this property issue assigning key before that we have to define new variable key and here I will provide this string for the JSON web talk and encryption so here it is at least it should have 16 characters so I have given 16 digits here instead of directly passing this string here we have to pass the encoded version so we can do this encoding for that we have to add this namespace system dot text from that we have this utf-8 dot get bytes function and be called inside that function we can pass this security secret now in order to assign this key into this property here we have to create an instance of symmetric security key Clause so we can do this new symmetric security key for that we have to use this namespace item model dot tokens inside this instance we can pass the key that we have defined before after this property we have to configure a few more violation parameters so we have validate issuer and we will reset that false and then we have validate audience the research that force during generation of a talk and we can define the issuer of the token which means who generated this token obviously it will be a name for server and inside the audience attribute we can set the target audience for the talk so while receiving the token after successful authentication we can compare whether we have the same issue or audience which we have provided during generation of the token we don't have to validate those properties issue or an audience so we have reset the property as false here finally we have to set this property clock skew and I will set it as time span dot 0 we have assigned this property as 0 timespan for checking expression time of token there is no timezone difference between server and client side so we have said this time span as 0 so here we have done with general configuration for authentication with JWT now instead of hard-coding this JWT secret code inside this data file here we have to move that into this configuration file app settings dot JSON here just below this connection string I will add another key application settings inside that we can add a key for JWT secret course so it will be something like this JWT underscore secret and I will copy this and paste in here now in order to access this value from this start of class here we just need to do this we have this high configuration property configuration so we just need to do this configuration inside that we can provide the path of this key here so let me copy this app settings here inside app settings we have another key JWT secret let me copy this and pissing here that's it like this we can access values from app settings dot JSON file finally we have to convert this into a string so we can call this two string function now I want to move this client URL into app settings file we have mentioned this angular 7 application URL for enabling course just below this secret code I will add another key client URL copy paste this URL let me copy this and paste in here now in order to access this value we can do the same like we have done for secret code let me copy this and pissing here instead of jwd secret code we have client URL now we have to create a post web api method for user authentication in to that we can pass user name and password so that we can consume that web api method from this login form submit event so let's add that web api method inside this controller application user controller which we have added in previous tutorial so i will add a new web api method here which is of the type HTTP POST now for this web api method we have to configure the route like this route it will be logging now in order to consume this web api method we have to make a post request with the URI like this application user for slash login and the Web API method will be something like this public I think and its return type will be something like this task I action result and I will name this method as login into this Web API method we have to pass the credentials username and password for that I am going to create a model class inside this models folder here add class I will name the class as Logan model inside that we will have string properties for username and password string first of all we have user name and then we have the password now we can define a parameter inside this method of the type Logan model so here it is login model and parameter name will be model now inside this function we can do this first of all we have injected the user manager as underscore user manager here we have to use this property in order to check whether we have a user with given user name so I will define a new variable user which is equal to avoid underscore use of manager dot find by name I think function can be called so that we can get a user using his username so inside this function we just need to pass the username after that we can check whether we have a user with given user names so I will add this if close here inside that it will check whether this user variable is null or not if it is not null we can say that there is a use of with even user name and if there is a use of it given user name we have to check the our password so we will do this underscore user manager dot check password I think function can be called inside that you have to pass the use of password and we can retrieve from model dot password property since we are calling asking function here we have to add the avoid keyword here also as sorry as the first parameter to this function we have to pass the user object also now inside this if closed we have to successfully authenticate we use so first of all I will define a new variable torque and descriptor is equal to new security talk and descriptor for that we have to add this namespace identity model dot tokens now into this we have to pass few property values so first of all we have subject inside the subject property we will pass the claims associated with the user in order to set the clients for the user you can do this claims identity instance can be used in order to use this class we have to use this namespace security dot claims in order to pass the claims we will use the claim alright for now I just want to save the user ID so we can do this new as a first parameter we can set the claim key which is user ID as a second parameter we can set the value which we can retrieve from this variable user so you saw dot ID and we want to convert that into string so to string function can be called after this subject property we have to set the talk and expiration time so expires property can be set here date time dot UTC now from that property I will call this add minutes function inside the function I will pass five so this token will be expired after five minutes of token generation after this property we have to set sign in credential property for that we can use the sign in credential instance as a first parameter we have to pass the signing secret key which we have passed here inside this startup clause here using this instance symmetric security key instance let me copy this and paste in here and forkie we have done this LP copy this and replacing this key here in order to use this encoding class here we have to use this namespace system dot text and we have accessed the JWT secret inside the startup class from this app settings not Jason we cannot do that same inside this controller we have to do something different that we can do in a bit for now I will just pass a hard-coded string here let me copy that from here I have settings and I will paste that here as a second parameter to this function we have to mention the algorithm that we want to use for encryption of the signature so we can do this security algorithms dot H m.a.c sha-256 signature algorithm can be passed here so here we have created the variable talk and descriptor after that we have another variable token handler which is equal to new JWT security token handler for that we have to use this namespace identity model dot tokens dot JWT after that we have to create another variable security token now we can actually generate the token using the variable token handler token handler dot create token function can be called inside that we have to pass this talk and descriptor now we have to write this token for that I will create another variable token is equal to token handler dot right token function can be called inside that we have to pass this security token variable finally we have the return statement and we'll call okay function inside that we have to pass the token that we have just created for that I will pass an anonymous object token is equal to token in short you can pass talking here so here we have successfully authenticated the user using JWT now we have to do some modifications for this encryption secret code for JWT which we have already mentioned inside this configuration file app settings nor JSON you can access these values from start up class like we have done here in order to access the same outside the start up class we have to inject these information into the application for that inside this configuration services function we just need to do this here we are going to inject these app settings so inject app settings for that we just need to do this services dot configure function can be called configuration property can be used here and from that we can call this get section function can be called inside that we have to provide this or section name which is app settings in order to access these values using strong typing I am going to add one more class inside this models folder here right-click then add class I will name this class as application settings inside this class we will add properties corresponding to these keys here so first of all we will add the property of the type string and I will name this property exactly like this JWT underscore secret like this we have to create one more property for line URL that's it now back to this start applause here I'm going to mention that plus here application settings now in order to access these injected informations from this application user controller we have to modify this constructor here so I'm going to add one more property here it is of the type I options for that we have to use this namespace Microsoft extensions not options which is of the type application settings I will name this property as app settings now in order to assign this value into a property I'm going to define one more private property here private read-only application settings and I will name this property as underscore AB settings you can assign this property here underscore AB settings is equal to AB settings dot value can be assigned here so this is how we can inject the application settings section from this app settings dot JSON file now we can update this hard-coded secret code here we just need to do this underscore AB settings dot JWT secret now we have to test the working of this post Web API method login for that first therefore we have to run this application without debug mode for that go to debug then start without debugging so here we have started the web api from this port number now in order to test the working of this post will be bi method i'm going to create one more user so back to the angular project here we are inside the signup form here so let me create an user for linda username will be lint one two three full name will Linda Thomas password will be 1 2 3 4 1 2 3 4 now submit the form so here we have successfully created the user for Linda now we can use that same user in order to test the working of this post will BPI method login we have not yet implemented this login form submission event so in order to test the working of this post API method I'm going to use this postman application here so here we have to make a post request and corresponding URI will be something like this let me copy this corresponding URI will be for slash API forward slash application user forward slash login let me copy and pasting here now inside this body we have to provide the user credentials username and password so I will use the raw version here and we have to set Jason here it will be a JSON object first of all we have user name it will be Linda 1 2 3 after that we have password it will be 1 2 3 4 now let me send this request boom inside this response we have the JWT token so first of all here we have the header part after that we have payload and finally we have the signature part here so here we have a successful authentication now this JWT token will be saved inside the browser local storage we will send that same token for access insecure or private routes inside the web api project here now in order to show you how to access such private or circular outs from this donut co application using JWT token I'm gonna create new controller here so right-click on controllers folder then add controller I will select API controller empty I will name this controller as user profile controller and now inside this controller I am going to create a get Web API method which will return details of signed in user like full name email address user name etc this way baby I met there will be of the type HTTP GET we are going to create a secure private web api method we have to add this attribute otherwise now we have to add this namespace espied or net code dot authorization actual web api method will be something like this public I think it will return off the type tasks of object I will name this web api method as get user profile so in order to consume this Web API method we have to make a get request corresponding URI will be something like this API forward slash user profile now inside this Web API method we have to retain corresponding user details now how do we identify the user who made this request so in order to access this private or circular routes which has this attribute otherwise we have to send the JWT token which we have received during loking operation and then JWT auth system will validate that talk inside that token we have added this clip user ID so while accessing this secure web api method here the ability auth system will extract the payload or this user ID clay so in order to access that user ID here I'm gonna create a new property here string user ID is equal to user dot claims property can be accessed inside that we just need to call this force function with this lambda expression C such that C dot type is equal to you saw ID which we have used for this claim here finally we have to access the value property here value sorry here we have an extra equal symbol so using this user ID we can retrieve the details of you saw such as first name email address user name etc for that we just need to do this what you saw is equal to actually in order to access those properties from the user table we have to inject user manager like we have done inside this application user controller here so here we have injected user manager sign-in manager we have discussed these injections in previous video tutorial so in order to inject this user manager we have to add this property inside we control a constructor so first of all let me add a constructor for that you can use this snippet ctor and I will add this constructor property of the type user manager now we have to add corresponding namespace here now let's create a corresponding private property like we have done here let me copy this and paste in here underscore user manager is equal to user manager now using this user manager property we can access the user details so we just need to do this user manager from that we can call this function find by ID assing function can be called since we have an icing function we have to add this keyword right here inside this function we have to pass the you saw ID so currently inside this variable we will have the details of you so now we just need to return that from this Web API method return and we will return a new anonymous object here first of all we have full name is equal to use a dot full name in short we just need to pass this user dot full name like this we can pass email address this dot email then finally we have user name now let me build this project again now back to the postman we are going to make a new get request corresponding URI will be something like this let me copy this and paste in here API forward slash you saw profile now along with this request we have to pass the token that we have received while authenticating the user so let me copy this token from here and inside this get request go to this authorization tab here then we will set the type as we have to send the token as be oral tokens so I will select this option here and we just need to paste that token here now let me send this request and here we have the response for not 1 and authorized if you go to this header here can see the detailed error description bearer error 'invalid talk and error description the token is expired so the token that we have used it for this requires is expired inside the login Web API method here we have said the expiration time as 5 mins so token will be expired after 5 mins of creation I will set it as 1 day so instead of calling this we'll call ad days function the token will be expired after a day let me build this project again after successful build back to the postman let's make this post request again for a new token send this request so here we have the new token let me copy this and replacing that inside this tab here let me make this request again so here we have the status 200 okay and here we have the response which contains informations like full name email address user name of corresponding user now we have done with JWT user authentication inside this donut web api project now let's look how to implement JWT user authentication inside this angular 7 project for that first of all we have to submit the user credentials username and password into this post web method here inside this application is a controller logon for that we can add a submit event for this login form here so back to the component HTML login component HTML I will add a submit even here submit when we submit this form we will call another function on submit inside this function core we will pass this form local reference now let's define this on submit function inside this component type script file here so here we have the function on submit with a single parameter form it's of the type ng for now inside this function we have to consume this post web method loking for that I'm going to add a function inside this user service Clause here so I will name that function as login for this function we will have a single parameter form data in order to make the post request we can use this HTTP client object which we have already injected in previous tutorial ok so in order to post a request you can use this same statement here let me copy this and paste in here we have to make a post request inside this base URI we have call the localhost for slash API along with that we have to concat this URI here for slash application user for slash logging into this post Berk method we have to pass user credentials username and password that we can pass into this parameter here so instead of body we have form data as a result of this post function invocation it will retain an absorber so from this function we will return that absorber so when we call this same login function inside this on submit function we can subscribe to that so first of all we have to inject this user service class inside this login component so here we have the constructor I will add a private parameter here service it's of the type you saw service now we just need to do this this dot service dot Logan function can be called inside that we have to pass a JSON object containing values from these textboxes username and password for that we just need to do this form dot value property can be passed from this function we will return an absorber so we can subscribe to that absorber here so inside this function subscribe we can have to call back function one for success it has a single parameter response it is of the type in E with second callback function we can deal or error situations this post request will be similar - this one here so as a result of the user authentication successful use of authentication it will retain a talk and decent web token so we have to save that JSON web token inside the browser local storage but that we just need to do this local storage dot set item function can be called as a first parameter we have to pass the key name which will be a token as a second parameter we have to pass the actual value itself that we can retrieve from this response parameter response dot token as a result of successful authentication we usually redirect the user into dashboard or home component so in order to redirect the user we have to inject router class here so private router which is of the type router class now we just need to do this this dot router dot navigate by URL function can be called inside that you just need to do this for slash home inside this application we don't have a route path I will set up that crowd in a bit before that let me complete this function on submit so we have done with success case now if there is any error we have to deal with that inside this second callback function here from this door net go web api method we will return a bad request with status 400 with this message username or password is incorrect if the authentication is failed so we have to check that here if this error object contains a property status so we will compare that here if it is equal to 400 we have to show the message incorrect username or password in order to show this notification I will use package toaster which we have configured in previous tutorial so first of all we have to inject that tosser service here private toaster which is of the type toaster service now we can do this this dot toaster dot error function can be called as a first parameter you can pass the message in correct username or password as a title for this notification we can pass this authentication failed if there is any other error we can deal that inside this else block here we will just consult this error object console dot log function can be called inside that we just need to pass this error object now we have to set up this new route path /home for that we are going to add a new component home component so let me update this application structure here currently our application structure is almost like this now for this new route we have to create a new component home so let's create this component home for that I'm going to open one more terminal here in order to create this component you can execute this angular CLI command ng G for generate C for component and we have to create home component and we have to skip the creation of test files so I will set this flag spec as false and also we have to skip the component specific stash so you can use this as flag now hit enter newly created component can be seen here home now let's add a cloud for this new component so here we have the route module I will add a new path here path is equal to four slash home and corresponding component is equal to home component as you can see here by default will be redirected to registration component instead of that I want to redirect the application into Logan component inside this home route we don't have to provide this for slash here let me remove that let me save all of these modifications then back to the application here now let me try to login with Linda user record so username will be Linda one two three then password will be one two three four click on login boom so here we have successfully authenticated inside this application as a result of that we are redirected to home component inside this home component we have to list informations of currently logged in user before that I want to add a now Bob with logout button for that I will copy the now Bob from bootstrap official documentation so go to this website get bootstrap comm click on get started then search for navbar here then I will copy this now bar HTML here this one dark one let me copy this and then back to the application here open home component HTML I will replace this default paragraph here inside this now bar we will have an anchor element with few classes first of all we have now bar - brand inside this angle element we want to show font color ass white so I will add this class text - white inside this hyperlink I will show this application name it will be something JWT authentication in short cause system along with that we need a logout button so I will add this button with few classes tn than VTN - danger - apply some margin I will add these two classes my - - then my - ASM - zero button text will be log out let me save all of these modifications here then back to the application so here we have added the now BA with logout button now let's check how to logout from this application for that I'm going to add a click event for this logout button here click when we click on this button we will call another function on logout now we have to define that logout function inside this typescript file here on logout in order to logout from this application we have to do the reverse that we have done inside this login function here so we have added this token into local storage so we have to remove that during logout operation so we just need to do this local storage dot remove item function can be called inside that we have to pass the corresponding key value after logout operation we have to redirect the user into login page for that we have to inject router here so private router which is of the type router class now we can do this this dot router dot navigate function can be called inside that we can pass an array with corresponding route so it will be for slash user forward slash login let me save all of these modifications and back to the application here currently we are successfully authenticated inside this application if you click on this logout button boom so here we have logout from this application even though you can directly access that home component by typing corresponding path inside this browser you are here so /home hit enter so here we are inside the home component now we have to make this path or route as private or secure so let's look how we can do that after that only log in user can access these private routes so back to the application in order to make this route home route as private or secure route we have to implement guards inside this application so let's look how we can do that for that let me update this application structure here in order to create the route guard I will create a new file or inside that we will add this Oh God now we have to create a god so you can use this angular CLI command ng g4 gyrate and D for God and we have to create that inside this earth folder and we have to create an auth guard and in order to skip the creation of test file with extension spec dot TS we can add this flag spec as false hit enter so here we have a typo we have to add a space between this G and this odds so here we have the previous command I will add a space in between this D and AHS now hit enter so here we have the newly created guard inside this auth folder oh god dot TS so basically this is a class or God which implement this interface can activate so we have to define this function can activate inside this class so this function can return these types of datas so in this application we only want to return a boolean so I will remove other types here so inside this function we basically need to check whether this user is authenticated or not if the user is not authenticated we have to block that user from accessing private routes we will have this if closed inside that we will check the local storage local storage dot get item for can be called and we have to check for this token if the value is not null means there is a JSON web token stored inside these our local storage so in that case we will return true otherwise we have to redirect this user into login page in order to redirect the user into login page we have to inject router class here so I will add the constructor here for that we can use this a snippet ctor we don't need to call this super function inside this constructor we just need to inject that router so we just need to do this private router which is of the type router class now in order to redirect into login page we just need to do this this dot router dot navigate function can be called inside that we will have an array with this path forward slash you saw forward slash login after all in order to prevent this user from accessing that route we just need to return false from this close return false now in order to make a route as private we just need to mention that auth got here so we have to make this home route as private so we just need to set this property can activate here with this array inside that we can provide the earth God let me save all of these modifications here then back to the application currently we are not authenticated inside this application now let me try to access this home component so here we have redirected back to login page because we are not authenticated inside this application if you try to login inside this application with linked our code now we can access this home component when an user is already authentic we have to prevent that user from accessing this login page here so in order to prevent this we have to update the corresponding component in the Oni lifecycle hook so here we have the login component and here we have the ng on it lifecycle hook inside this we will check whether this user is logged in or not for that we can do the same like we have done inside this can activate function here let me copy this and pissing here if the user is already authenticated we have to redirect that user into home page for that we need a router instance which we have already injected here so we can do this this dot router dot now we get by URL function can be caught inside that we just need to pass this path for slash home let me save all of these modifications here then back to the application currently we are authenticated inside this application if you try to access their login page again you will be redirected to home page now inside this home component we have to show details of currently logged in user for that we can consume this Web API method which we have created inside this user profile controller get user profile now the key to access this verb method we have to append the JWT token which we have saved inside this local storage so let's look how we can do that for that we will add a new function inside this service class here get user profile so here we have to make a get request so we can do this this dot HTTP dot get function can be called as a first parameter to this function we have to pass the URI so you can do this this dot base URI into that we have to concat this forward slash user profile now let's look how to upend the JWT token into this request for that I will create a new variable here token hello is equal to nu se GDP headers with a single attribute authorization authorization is equal to first of all we have to add this prefix B error then a space and we have to concat that actual JWT token in order to access that you can do this local storage dot get item function can be called and we have to provide the corresponding key value token now we can pass this talk and header as a second parameter here so we will have a JSON object size that we can do this headers is equal to talk and header as a result of this gate function invocation it will return an absorber so we can return that observable from this function now let's call this function get user profile inside this home component here that we can do inside this ng on a lifecycle hook so first of all we have to inject the user service class here private service which is of the type you saw service class now we can do this this dot service dot get user profile function can be called it will return an absorber so we can subscribe to that absorber here it will have to call back function one for success and one for error so let me copy this and pasting below that for error callback function corresponding parameter will be something like this inside this error callback function I will just print that error object into console so so we can call this function console dot log inside that we just need to pass this error object inside this response parameter we will have an object similar to this one here so in order to say that I'm going to create a new parameter here you saw details and I will initialize that property inside this success callback function this dot user details is equal to response so here we have a typo instead of roud we have to use this class router okay now we have to show these user details like full name email address and username inside this home component HTML here so in order to display user details here I'm going to use card from bootstrap so we can have this div with class card along with that we will have this class M - 5 to apply merging from all sides and for this do I want to set a custom width so I will add this style attribute width is equal to 18 r.e.m we only want to show this div when this property is already populated this one user details so we can add this ng-if directive here ng-if is equal to you saw details inside this deal in order to show all of these information I will use lists from bootstrap so we can have this UL element with this class list - group inside this list we can add list item with this class list - group - item inside that we can have each information that we have returned from the server so first of all I will add this strong element inside that we can have username is equal to now we have to show or this property here username actually from this Web API method we have returned this username with this property name username here we have a difference here we have small U and here we have capital u same for other properties also so the response returned from the Web API method will be camel cased means first world first letter will be in small letter other words starting letter will be in capital letter for full name we have capital F here and here inside this response we have small F so my default from dotnet Web API project the response JSON object property will be camel cased so inside this Ally element here we have to show that for that we can use the property you saw details dot username like this we have to show remaining properties also so let me copy this and pissing below that two times here we have full name and corresponding property will be full name and finally we have email corresponding property will be email let me save all of these modifications here then back to the application here so here we have the currently logged in user details username is equal to Linda one two three full name will be Linda Thomas we did not provide email address for this user now back to this angular seven application here in order to append this JSON web token inside this user service function here we have created this talk and header for a big enterprise application in order to access most of the Web API method we should be authenticated so we have to repeatedly send this or append the our JWT token to every such request in order to avoid this repeated operation we can use HTTP interceptor from angular now let's look how to add HTTP interceptor to handle this operation at one place for this whole application for that we have to create a new file inside this auth folder here so first of all let me update this application structure here AB structure dot txt inside this same earth folder I will add a new type script file or interceptor dot TS let me copy this and inside this auth folder we can create a new file I will name this as auth dot interceptor dot TS and basically inside this file we have to create a new class so I will start with expose statement export class and I will name this class as auth interceptor and we have to inherit this from HTTP interceptor so we can do this implements HTTP in the scepter in order to make this class injectable in another places we have to add this decorator injectable since we have inherited this class from this interface HTTP interceptor we have to define the function intercept inside this class here in order to see the signature of that function you can right click on this interface here then go to definition so here we have the function intercept let me copy this and back to this file here I will paste that here now let's fix the import statement hold ctrl then press period then we have HTTP handler then absorber and HTTP event now inside this function we have to and that decent web token so all of the HTTP requests inside this application will be passed through this intercept function so first of all we will check whether this user is logged in or not so we can use this if close here local storage dot get item function can be called inside that we will check this key if it is not equal to null we can append the token into the request so inside this request parameter we have the request which we have made inside this application now into this HTTP request we have to add the authorization header but this request instance is read-only so in order to add that we have to clone this request or replicate this user and then we can add the header authorization so first of all I will create a constant and I will name this as client request is equal to request dot clone function can be called inside this function we have to pass an object and inside this object we will set the authorization header so we can do this headers is equal to request dot headers dot set function can be called here inside that we can pass the authorization header authorization as a second parameter we have to pass the token so we have this prefix bearer then space and here we have to congrat that token from local storage local storage dot get item and here we have the key token so here we have a copy of the current request now in order to process this new request we just need to do this return we can call handle function from this next parameter here so next dot handle function can be called inside that we and past this clown tree after processing this request we can handle some common errors inside this HTTP interceptor for that we just need to call this pipe function from our SDS inside that we can call another function tab now for this tab function we have to add the import statement manually so import statement we have to import that from our SDS operators and we have to import tab now inside this tab function we can have to call back function one for success and one for error one of the common error that we have to handle inside this HTTP interceptor will be for not one and authorized speakers it might be due to talk and exploration or something else so first of all it will add this if closed inside that we can check this status if status is equal to for not one I will redirect the user into login page instead of that you can short assert notification with detailed error also so in order to redirect this user to login page first of all we have to inject router here so I will add the private parameter here private router which is of the type router class and we can do this this dot navigate by URL function can be called inside that we just need to do this /q so for slash login so this is how we can happen this JSON web token at one place using HTTP interceptor instead of doing that for each function inside this service class here so we can remove that from here it will be added into this request from the HTTP interceptor here inside this as dog we just need to process the current request that we can do here else return next dot handle function can be called here and we just need to clone the current request because dot clone function can be called here also you can handle some common errors inside this application by using these two functions pipe and tap from Eric's days now here we have just created an interceptor now we have to mention this interceptor inside this AB dot module dot TS file here for that you just need to add an object inside these providers array like this it will have these properties provide use Clause and multi and we have to add corresponding import statement here that's it now let me save all of these modifications and back to the application so here we have fetched log in user informations using HTTP in their scepter also now inside this if Clause we have to do one more thing before redirecting the user to login component we have to remove the token from local storage so local storage dot remove item function can be caught and we have to remove this token let me save this and back to the application before winding up this tutorial I want to show one more thing since we are authenticated inside this application corresponding JSON web token will be stored inside this browser local storage you can see that inside this browser for that you just need to right click here then inspect then go to this application tab here and here we have the local storage for this website localhost four thousand and two hundred so here we have the token that we have received for this currently logged-in user so here we have the first part had a port after that we have payload and finally we have signature like we have discussed both header and payload is encoded so you can see the information that is represented by these train here for example let me copy this and then back to the console in order to decode that we can do this window dot a DOB function can be called inside that we just need to pass that copied header and so here we have the JSON object corresponding to that encoded string like that you can decode this payload here I can copy this second part from this token back to the console window I will replace that here hit enter so here we have the payload that we have sent from our Web API project so this is what we are saying do not store security informations like password inside payload and the last part of this talk and which is signature can't be decrypted in client-side because it is encrypted using a secret code in our server as long as that secret is kept as a secret inside the server no one can decrypt this signature here so that is the benefit of using decent web token with this signature it will maintain its integrity for example inside this application we have stored the JSON web token if someone manipulate this token from this or local storage here suppose if I delete few characters from this talk and then hit and though it would be saved inside the local storage and if I reload this page here we will be redirected to you saw or login page because inside this HTTP interceptor as a result of validating that JSON web token inside this server it will detect the change that we have made from our client side as part of that it will return a four node one response and the body will be redirected to login page so this is how JSON web token authentication maintains its security and integrity in these applications you can download this project source code from the github link given below in video description in order to make more helpful and quality tutorials like this you can support me through PayPal I have given the PayPal donation link in video description and force comment in this video we have discussed login and logout in dotnet go web api with angular 7 using JSON web token you saw authentication if you found this video helpful please thumbs up this video and for more awesome videos like this please please subscribe to this channel Cod affection please like and share this video with your friends and colleagues so that they can benefit from this have a nice day bye
Info
Channel: CodAffection
Views: 143,661
Rating: 4.9325747 out of 5
Keywords: asp.net core authentication with angular 7, login and logout in asp.net core web api with angular 7, asp.net core web api login and logout, json web token authentication in asp.net core, user authentication in web api with angular 7, asp.net core web api jwt authentication, angular 7 login and logout with .net core web api, jwt token authentication in asp.net core with angular 7, Login form in angular 7, Complete JWT Authentication System. asp.net core 2.2 tutorial, CodAffection
Id: s2zJ_g-iQvg
Channel Id: undefined
Length: 92min 19sec (5539 seconds)
Published: Mon Feb 25 2019
Related Videos
Note
Please note that this website is currently a work in progress! Lots of interesting data and statistics to come.