Angular 5 - Login and Logout with Web API using Token Based Authentication

Video Statistics and Information

Video
Captions Word Cloud
Reddit Comments
Captions
quick demo of this video tutorial in this tutorial we will implement angle of five login and logout with the baby I using token-based authentication so here we have the final output from this tutorial first of all I am going to register and user username will be Ethan then we have password as 1-2-3 then we have email even at gmail.com then we have first name it will be Ethan itself Ethan Robert now click on submit here so here we successfully created and you saw Ethan now I am going to login inside this application using this Ethan record username will be Ethan then password will be 1 2 3 click on login so here we successfully authenticated the user using token-based authentication inside this day we have shown details of user like username email full name then time of logging in order to logout from this application you can click on this log out button here so in this tutorial we will discuss points like how to create login form in angularfire application how to implement oven talk and based authentication in web api angularfire routing routing guards and HTTP interceptors and much more so I hope you will find this tutorial helpful for your upcoming angular five and may be bi projects so please watch till the end of this video tutorial what's up YouTube welcome to dotnet move in this tutorial we will discuss how to implement user authentication or login and logout in angular 5 with Web API project this is a continuation to the previous tutorial in which we have discussed how to implement user registration or user signup in angular 5 with Bob API and espied or net identity membership system if you have not watched that user registration tutorial please watch that force and then continue with this tutorial because in this tutorial we are going to authenticate you serve with username and password which we have given during user registration before continuing with this tutorial 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 dotnet Moe without further ado let's get started with previous tutorial angular Phi project in which we have created a user registration form like this so far so far inside this angular application and we design a login form for user authentication and we will move to the Web API project from previous tutorial in that we will implement oven talk and based authentication inside this angular 5 application we need to add few more components so here is the final structure of angular application which we are going to create inside this tutorial so here we have this signup component this is already the inside this application now we need to add three more components you sir component signing component and home component ok your sir component will be the parent component to these child component sign in and sign up inside this sign in component we will deal with user authentication and login form design after a successful user authentication we will open home component for that particular user and here we have the routes dot T as file inside that will configure application routing and finally we have odd photo inside that we have all got and auth interceptor now back to the angular application here we need to create three more components so let me open one more terminal here as you can see my photo path is too long in order to hide this path you can do this prompt then double dollar symbol hit end up in order to create an angular component you can use this command ng G for the rate C for component I will name this component as you saw hit enter so here we have the newly created component user as we have discussed user component will be the parent component for signing and sign component so now we need to move this sign up component inside this user photo so let me drag this inside this user component folder click on move now we need to create one more sign-in come on and inside this user folder so right click on it then open in terminal now let's create sign in Cameron ng g4z wait see for component component name will be sign in hit enter so here we have created the new folder for sign in component now we have to create one more component home so let me open one more terminal here ng g4 generate C for component component name will be home it end up so here we have created all required components inside this application now inside this signup component there might have some broken import statement due to its location change so first of all let's fix that so here we have some errors with this user and user service import statement so let me remove this statement from here now let's add import statement for these classes again so you can use this shortcut control then hold period and click on this imported man here same for user service class also that's it now back to AB dot module dot ES file here we have the proc and import statement let me remove this then click on the signup component then use the shortcut control period click on this import statement here now everything is fine now let me open this child sheet file Stiles dot CSS here we have these tiles from previous tutorial I want to update these ties here so let me update these CSS rules here then back to index dot HTML inside this index dot HTML we need to add a style sheet reference for material like in previous angular application we have used phone over some items inside this application we are going to use material icons like this okay so let me add the stat sheet reference for material icons here now back to the default app component HTML here now I am going to replace this dip with router outlet basically your router outlet will be replaced with the component HTML based on application routing don't worry if you are not aware of routing in angular applications we will discuss them in this tutorial itself so let me replace this with router outlet in order to work this router outlet we have to configure routing inside this application we will do that later now back to index dot HTML file here we have added style attribute for background color with hexadecimal color code in previous tutorial now I am going to replace this tile with some classes from material I CSS framework so let me add the class here class is equal to the - purple then we need one more class lighten - 5 as we have discussed in previous tutorial we have been using material as CSS instead of bootstrap so these two classes are from materialized thesis in order to apply background color inside this application you can see them inside the framework documentation just search for color here by using combination of meaningful and readable class names we can apply background color to HTML components like this okay that is what we have done inside this index dot HTML now let me open sign up component HTML inside that we have created user registration or user signup form in previous tutorial we have shown this form component inside a container component from material ICSS it almost looked like this okay we have shown this form inside card component with a title user registration here inside this application we have user component as a parent component for these two child component sign in component and sign-up component inside this child come on and sign in component we will show the login form and inside the signup component we show the user registration form only for these two child come on and we can add a container or outer part inside this parent component you saw component dot HTML file so let's look how we can do that so first of all from this sign up component HTML I'm going to remove the container or can't combine from this file so let me remove this card dip from here and we will just keep the user registration form here okay that's it so here we have your server discretion form inside the signup component inside this pattern come on in HTML you sir component HTML we are going to add a container for login form or user registration for it will be the current component from material I CSS in previous tutorial we have used card component with content and title in this project we need a card component with tab controls okay so it will look like this we need two tabs one for sign-in form and one for user registration I have prepared HTML 4 cards with tab control so let me copy paste the code here so here we have the deal with glass container then we have used grid system from the framework and we have used card component here okay inside that card we have two tabs one for signing and one for signup based on current URL or round we will show the form user registration or login form inside this div here okay now we need to configure routing inside this application for that I'm going to add a new file inside this app folder here create new file I will name this file as routes dot TS fun we have given inside the structure here routes dot T as inside that we have to configure routing for this angular application first of all I will add a constant here export constant I will name this constant as AB routes and it's of the type routes from angular library routes and basically it is an array for each route we will add one route object inside this error here ok now let's add import statement for this crowds class here import routes from angular router ok so first of all I am going to add a route for home component or dashboard so path will be equal to 4 then we need to provide become point component is equal to home component which will be this one ok now let me copy this home come run from here and paste in here now we need to add an import statement for this home component for that you can use the shortcut hold ctrl then press P deed then click on this import statement now let's add a route for user registration path is equal to sign up sign then component first of all I will type the route here and of then we will discuss them is equal to use component for that we have to add an important so here it is now we need to add a children error here children is equal to a new array inside that we will give the part but is equal to empty string then we have component component is equal to sign up component now let's add the import statement here so here we have added a route for sign up component but will be sign up then we have component has user component and we have children array with component sign up okay that means when we use this URL path sign up it will load two components use a component and sign up component you sir combine will be the parent component and child component will be the sign up component using this parent component we will load the container which is this card component from material I CSS inside this div can then do we will load the children component sign up component okay like this we have to add one more node for logging so let me copy this and paste it below that then path will be log in then parent component will be user component itself then children component will be sign in component so let me add the class and import statement here finally we have to add one route for default URL so it will be something like this path is equal to empty string then we will redirect to for slash login then path match is equal to 4 so this route will redirect to this signing component that means by default inside this application they will show logging for here we have the default route inside this application with these two routes we have had a routes for signing and sign up component both of these component does not require user authentication but other components like home component we need to authenticate the user that we can do after implementing token-based authentication in web api project for now here we have just created a constant for route purpose now we need to tell this application to follow these routes for that open app module dot e as file first of all we have to add an import statement for router module so here it is import router module from angular router now inside this imports array here we need to do this router module dot for route inside this function we have to pass the route constant which we have added here a proud let me copy this and paste it inside this function here now we have to add an imported man for that you can use this shortcut hot ctrl then press period then use this import statement ok now let me save all of these modifications here and back to the application here and here we have the tab control with sign in and sign up tab so when we click on this sign in component we have to show login form here which we have not designed it and we click on this sign up component we need to show user registration form here in order to work this tab first of all we need to do this go to user component HTML here we need a router link attribute here router link is equal to 4/9 and for sign up tab we need to do this router link is equal to sign up okay now let me save this and back to the application here if I click on this sign up here you can see that we are showing user registration now back to sign-in tab we have the HTML from sign-in component inside the framework documentation you can see some styles for active tabs here which we have not applied here okay here inside this documentation active tab got a CSS class active okay now we need to apply the same class inside these tabs here for that we can do this router link active is equal to active class so whenever login is the current active route we will apply this CSS class active we need to do the same for signup tab so let me copy this and paste in here let me save this and back to the application here so here we have applied active class to the current tab now we have to design login form inside signing component HTML so back to visual studio code editor then open sign-in component HTML here first of all we need a form with classes call then estriol then white background then hit tab so here we have the form component with given classes you don't need this action attribute here let me remove that first of all I am going to set a local reference login form is equal to ng form inside this form 4 so for we need a class row inside that we need another deal with class input field input field then then call as 12 inside that we will show a input text box for username so input then type will be 'text then we need to set local reference as username then ng-model then we need to set the name attribute as user name after that we need pace holder is equal to user name okay before this user name textbox we need to add a material icon okay we have already added statute reference for this material icon in index dot HTML and we need to add an icon which is this one account circle before this text box for that we can add an ID tag here with classes material - icons then we need the class prefix inside that we will give the name account instead of space we need to give underscore here account underscore circle let me save this and back to the application here so here we have a text box for username with material icon like this we need to add one more text box for password so let me copy this deal and pasting below that and then we need to change accordingly instead of this account circle I can we need and I can't with key so we will use this one we P underscore and here I will set this textbox type as password then we will change the local reference password password usually I use camel case for these local reference so let me edit here username username then password name will be password okay then peace holder will be password now finally we need to add one more dip for submit button so here it is we have added a button of the type submit' with text cloaking okay now let me save this and back to the application here now we need to add validation inside this form for that I will add required attribute to these two text boxes required and required here okay as we have discussed in previous tutorial we are going to validate these two text boxes based on angular classes ng invalid and ng dirty which we have given here inside this Thai stored CSS here when a text box has ng invalid and ng dirty at a time we will apply this validation indication with red border okay now back to the form here finally I want to disable the submit button login when this form as a whole is not valid for that we can add this attribute here disabled attribute when this form is not valid let me save all of these modifications here and back to the application if I under something inside this text box and then clear you can see this validation error indication with red border okay same for password also so when these form is valid then only we will enable this plug-in but he so here we have completed with angle of five logging for now back to the Web API project from previous tutorial that we have implemented user registration using asp.net identity now inside this application we are going to implement user authentication using oven oven stands for open web interface for dotnet applications basically it act as a middleware between application and web server that means middleware between SP dotnet application and IAS sawa nowadays new features are added to oven day by day in this project we will implement token-based authentication from scratch using oven ok first of all we have to install some in you get packages for that you can right click on this references here then click on manage in you get packages then search for identity dot oven then install this package microsoft SP door net identity oven click on install here click on accept now we need to add two more packages for that you can search for oven Dork host so you can install this package Microsoft dot or windowed host dot system web click on accept and here comes the final package or in dog course install this package Microsoft dot or Windows so here we have installed three packages related to oven in order to use oven inside this Web API project first of all we have to add oven startup class for that you can right click on this project then add new item then search for oven start of class I will name this class as startup click on add by default inside the startup class we have a function configuration with this parameter I a buildup inside this function we will configure token-based authentication that we can do in a bit before that we have to add one more earth provider class inside that we will validate a use of with given username and password for that you can right-click on this project then add class I will name this class as application or auth provider click on add so here we have the class now we need to inherit the parent class here or authorization server provider for that we have to use this namespace Microsoft of insecurity or generally inside this class we will override two functions first one is this one validate client authentication with this function we will authenticate the client device based on the given client ID and secret code inside this application we don't want to authenticate the client device instead we want to authenticate the user based on his username and password for that we can override this function grand resource owner credentials inside the function we will authenticate the user based on his username and password now let me add required namespace for task here system dot threading dot task inside this application we don't want to authenticate client device so I will directly validate this client authentication context here context dot validated inside this grant resource on a credential function we have to check given password and username inside our database for that I will add two objects of uses two and user manager ok let me add the namespace here now we have to find the user with given username and password for that we can do this user is equal to abide manager dot find I think inside the function we have to provide the username and password that we can get from this context parameter so we can do this context dot username then connects dot password if there is a use of with given username and password we can say that user authentication is successful okay otherwise we will just return from here and return now we are going to add claims related to the logged in user basically claim means a statement about the logged in user here we are going to store details like first name last name then time of login for that first of all we need to create an object of claims identity like this so let me add the namespace here now using this object we can add crimes related to the logged in user like this we have user name email first name last name and then then log in time so these clients will be stored as a key value dictionary inside the application finally we have to validate the user for that we can do this context door validated function can be called inside that we can pass this object identity so here we have completed with auth provider here we have specified how do we want to authenticate a user in previous tutorial in order to enable cause inside this application we have added this line inside Web API config file here we have allow request from port number four thousand and two hundred using a nine NuGet package web api COEs now let me try to enable cause using oven so let me come and this line here now back to start applause here we can do this Abdur that means I am bill the object used cause function can be called and passed this parameter here for that we have to use this namespace Microsoft Irving course now let's look how we can add token based authentication using oven inside this application for that first of all we have to create all options like this so here it is let me add required namespace here now we can discuss these options one by one before that let me run this application without debug mode for that you can use the shortcut hold ctrl then press f5 so here is the first option talk an endpoint path here we have given report as talk and forward slash talking here you can see the base address of this Web API project first of all we have to make an HTTP POST request with this token URL along with that we have to provide username and password okay so using this username and password we will check whether this user is authenticated or not if the user is authenticated then server will return a none Corder to constrain now how do we check a given user name and password is valid or not and we have already done inside this class here application or provider function gland to source owner credentials so with the second option provided or we have given how do we want to validate a user with given username and password and here we have the access token expert timespan that means so whenever we make a token request with correct username and password then server will return an encoded string this string will have a lifespan or expired type for now I have given the time span as one mint if you want to extend this time you can modify here here we have given 60 minutes that means one hour and finally we have this flag allow insect your HTTP to specify whether we allow in secure request or not now with these options we have configured token-based authentication inside this application now we need to tell the application we need to use these options for that we need to add these two lines here here we have provided the options and here we have specified Bureau authentication we will discuss what we meant by bearer later in this tutorial now let's check how these talk and creation works for that we need a username and password of registered user in previous tutorial we have registered few users but I forgot their password so let me add one more user we have both Web API and angular application running on our development server so here is the angular 5 interface I am going to add a new user here username will be ashton then password will be 1 2 3 then first name will be ashton then last name will be Cox - 10 Cox click on submit so here we have registered a new user for Ashton Cox now we can't test token creation inside this Web API project using Ashton Cox record for that we need to use one of the testing tool Web API testing tool like fiddler or postman in this system I have installed postman extension with Google Chrome so here it is here I am going to make a new request in order to get a token for Ashton Cox user for that we have to make a post request into this Web API project here here this Web API project is running inside this base URL so let me copy its URL from here and pasting here and in order to get a token for a believe you so we have to use this token path so here it is forward slash token then we have to post some data into this request for that you can go to body tab here and first of all we have to set the form type I will set it as XW double w forum URL encoder here we have username is equal to Ashton and we have password password is 1 2 3 finally we have to set grant type as password then underscore type is equal to password now click on send so here we have a small problem related to decent package Newton's soft dot decent for that we have to update web config file inside this solution here in order to fix this problem you can add this dependent assembly attribute for mutants off dot Jason I have given this dependent assembly attribute in video description you can copy paste from the let me save this file then build the solution now we need to make the request again for that you can click on the send button here so that's it here we have an encrypted token from Web API project and it's of the type burea and it is going to expire within this much seconds that means 60 minutes or one hour so in order to get this talk and we have made a post request into this URL so this is what we are going to do inside our angular 5 logging form submit event ok from now onwards we have to use or append this access token in order to consume web api method which require authentication now let's look in action inside this Web API project from our previous tutorial we have added a register where may be a method to register a new user this register method do not need authentication so I am going to add a new web api method in order to consume that will be a matter you so must be authenticated so here it is here we have a Web API method get user clients it's of the type HTTP GET first of all let me fix this namespace issues here with this Web API method we are trying to return claims of current news we have saved values for these claims during authentication process inside this odd provider function grant the source honor credentials here so here we are trying to return username email first name and last name along with this data I want to return logged on time for that we need to add one more property inside this account model class which we have created in previous tutorial it's of the type string then property name will be logged on let me save this then back to the Web API method here get user claims in order to return logged on time we can do this log on is equal to let me copy this and paste in here instead of last name we need log on key so this Web API method need authentication for that we need to add this authorization attribute here authorized attribute should be added here or you can apply this authorized filter throughout this application for that open web API config dot CSS file here we just need to add this line config filter stored at authorized filter so this will apply authorized attribute throughout our web ABI methods so we can remove this from here and whenever we have ever baby a mother which does not need authorization in that case we can add this filter or attribute allow anonymous now let me save this and build this solution again for that you can use this shortcut ctrl shift B or you can go here built then build solution now I am going to consume this Web API method get user climbs which need authorization so here is the base URL of the project so let me copy that and facing inside postman along with this we have to append this ap I get you the claims have been copy this and pasting here this ever be a method is of the type HTTP GET okay so we can keep this get as it is now let me try to make this request click on send so here we have get this message authorization has been denied for this request and here we have the status code for not one and authorized so this is what we were talking when we created this token okay in order to access a Web API method which need authorization we have to append this talk and along with that request so let me copy this token from here and then we can add that talk and inside headers here we just need to pass it as authorization then first of all you have to use this prefix Vieira Vieira then a space then paste you are talking here now click on send so here we have the response from our Web API method so this is how we can consume Web API method which need authentication if I passed a wrong key here we will get the same for not one error authorization has been denied for this request for not one an authorized status code so this is how token based authentication works now we have to implement these steps in our angular 5 application so let's look how we can implement login and logout inside this angular 5 app with existing web API project so far we have created a login form here inside this form submit even we will make a talk and because into this Web API project with username and password if the user is authenticated then Web API project will return an access token so that is what we are going to do inside this form submit event for that let me wire up a form submit even here inside signing component HTML ng submit is equal to we will call a function on submit into that function we will pass username and password from these text boxes for that I will use the local reference username door value will give the text inside that text box same for password also password dot value now we have to create on submit function inside the component type script file here on submit for this function we have two parameters username and password inside the function we have to make a token request to the web API project for that I am going to add a new function inside this service class user service class here function name will be used attend occation for this function we have two parameters username and password side this function we will make a token request to the web API project as we have done inside this postman here so here we have made a post request with this token URL along with that we have passed three that us here so first of all I'm going to declare a data variable here what data is equal to first of all we have user name is equal to I will append this username value to this data here user name then we have password and password is equal to can append this here password after that we have grant type as password so here it is and grant type grant type is equal to password after that we have to set request header content type as form URL encoded for there let me declare one more variable here to our request head down is equal to new HTTP headers for that we have to import this class here inside that we will pass a JSON object like this content type content - type is equal to application application /x www u RL encoded URL and coordinate now we can make the talk and request using injected HTTP client object so here it is return this dot HTTP dot post first parameter will be the URL so here is the base URL for that web api project so we can do this this dot root URL along with that we have to append this forward slash token after that we have to pass the data then we have to pass the head dog headers is equal to request header so here we have a function to make a token request to the web api project now back to the component type script file here we can call this user service function for that for so for we have to inject user service inside this component type script file in order to inject user service class here we can do this private you saw service its of the type you saw service class and here inside this function we can do this this dot user service dot user authentication into that function we have to pass this username and password username and password this user authentication function will return an absorber so we can subscribe to that absorber here subscribe inside that we will define an arrow function with parameter that it softly type any if this token request is successful then it will call this arrow function if this end speed and error response we have to add one more arrow function to handle that error or that we have another arrow function with a single parameter it's of the type HTTP error response if this token request is successful means you saw authentication is successful for given username and password in that case it will return a JSON object like this with these properties access talk and talk and type experience in so inside this success error function I am going to store the access token inclined web browser here for that we can do this local storage dot set item first parameter will be the storage key so it will be user token then we have to pass the value here data dot access underscore token most often after a successful authentication we will take that user to homepage or dashboard so here I am going to navigate the user to the home component for that first of all we have to inject router inside this component private router it's of the type router class now we can do this this dot router dot navigate inside the function we will pass an array with home component parts for slash home that's it now we have to handle this error response because of wrong username or password for that I am going to add a boolean property here is login error it's of the type boolean first of all I will initialize with false now if there is an error with user authentication I will set this boolean property here this dot is login error is equal to true now based on this property value I am going to show an error message inside this component HTML here first of all we need a deal with classes read text then we need send a class then we need error - message class in order to show and hide this deal based on that property we have to add this directive ng-if is equal to is login error property so let me copy this and paste in here inside this day we want to show the error message for that first of all I will add and I can from material icons for that we can do this I tagged with class material - icons then error after that we have the error message in correct username or password sorry here we have an error with had import inside user surface class so let me fix that force so this is the import statement that caused this error so let me copy this HTTP headers from here now we have to import that HTTP headers from angular common HTTP let me remove this line from here now let me save this we have few more errors with import statement inside signing component or TS file here we have to import HTTP error response from angular common HTTP then we have to import router from angular router let me save this and back to the application here now let me try to log in with ashton record username will be ashton then password will be one two three click on login so here we have successfully logged in inside this application and now we are inside the home component with default text now inside this home component i want to add a now bob with sign out button for that let me go to the materialized CSS documentation you can search for now bar here so i want to add a now bar with few more variations from this example so back to the component HTML here i want to replace this default paragraph with modified now Bob from materialized CSS so here it is let me save this and back to the application here so here we have a now bar along with that we have a logout button now I am going to wire up a click even for this logout button so back to the component HTML here so here we need a click event it will call another function look out now we have to define this logout function inside the component type script file here logout function we don't have any parameter for this function now in order to logout and user we can do the opposite that we have done during user authentication inside signing component type script file here here we have stored access token inside web browser local storage as uses token now using this user talk and we will implement you saw authentication and authorization inside this angular 5 application in a bit before that let me show you how to log out a user for that you can remove the use of token from web browser local storage for that we can do this local storage dot remove item inside this function we just need to pass this key of local storage user token let me copy this and pasting inside this function here so it will remove the user token from our web browser open storage after logout operation we need to show login form that means we have to navigate sign-in component here for that first of all we need to inject router here private router it's of the type router now let's add import statement for this router class for that you can use the shortcut hold control then press P read and click on this import statement so here we added counter import statement now we can use this object router this dot router dot navigate inside that we will pass an array /login let me save all of these modifications and back to the application here so here we have already logged inside this application in order to log out this application you can click on this logout button here so here we are successfully logout from this application and we are again inside this login for since we just logout from this application application should not allow me to access home component but if I directly and the home component URL here I can see the home component here now in order to handle these unauthorized requests inside this angular application we have to update our route talk with gods so let's look how we can implement router guards inside this angular 5 application for that first of all I will add a new folder here we'll name this folder as auth inside the folder I want to create a guard for that right click on it then open in terminal in order to create a guard you can use this angular CLI command ng g forgery then g for god then we want to name the god i want to create an old god so I will just type both here and hit enter so inside the folder we have created an oath guard here Oh God TS so here we have the old guard with default codes here we have the required import statement here and here we have a class old guard which implement from can activate from angular library and here we have the can activate function inside that we will check whether this request is authorized or not here we have the two parameters for this function and this function is allowed to return these types of data for now we are going to return a boolean here so let me remove other return types in order to check whether the current user is already authenticated or not for so for we will check the local storage with user token if there is a value inside local storage with this user token we can say that this user is authenticated in that case we will return true from this can activate function otherwise we will redirect the user to login form for that first of all we have to inject router inside this class so here we have the constructor inside that we have to inject router private router it's of the type router class now we have to add import statement for this whole control then press P read then click on this import statement here if the user is not authenticated we will redirect to login form here for that we can do this this dot router dot navigate to the login path which means sign in component finally we have to return false here so here we have created an oath guard now we need to tell the application where do we need to use this earth guard for that first of all go to app module dot e as file here and we have to add all God inside providers are here Oh God and here we have an import statement for earth God here now back to the router dot TS file here so here we have already configured router inside this application so here we have only one doubt which need authorization so this is the route home component for that we can do this can activate is equal to then we will pass an array with oh god oh god click on this it will automatically add import statement for God now let me say all of these modifications and back to the application currently we are inside the login form if I try to access home component because we are not authorized to access that home component now let me try to login again Ashton then password will be one two three click on login so here we are inside the home component now I want to show you one last thing here inside this Web API project we have created a Web API might they get user claims in order to consume this Web API method we need authorization in order to access methods which need authorization we have to pass access token like we have done inside this postman here we have passed authorization with beer or token now let's look how we can make a request with access token in our angular 5 application so back to visual studio code editor first of all let me close all tabs here and inside home component type squid file I'm going to show these use of flames username email first name last name logged on inside this home component here using card component from materialized CSS for that I will use ng on it lifecycle hook of home component first therefore we have to create a function inside this user service class get user claims you don't have a parameter for this function inside the function we will make an HTTP GET request like this okay so let me copy this URL from here and back to the IDE in order to make a get request we can do this this dot HTTP dot get first of all we have to pass the URL first parameter is the URL so we have base URL inside this property root URL along with that we have to append this API get user claims if we make a request like this it will return for not one and authorized status core because we are not passing access token here in order to pass an access token we can do this headers is equal to new HTTP headers inside that we will pass a JSON object with authorization so let me copy this authorization is equal to be error along with that we have to pass access token that we can retrieve from local storage local storage dot get item inside that we will pass the key user token finally from this function we will return the absorb back to the caller now we can call this function inside home component type script file first of all we have to inject user service class here private user service it's of the type user service class inside ng on it lifecycle hook we can do this this dot user service dot get user claims this function will return an absorber so we can subscribe to that absorber here subscribe inside that we will define an error function with a single parameter data it's of the type in E in order to store user claims I have created a user claims property here now we can do this this dot user claims is equal to that up now inside this user claims we have details of user like username email first name last name and logged in we want to show these user details inside home kamuran using card component from materialized CSS for that we can add this card component here we have a div we will show this div only when this use of claims details is retrieved from the BPI project now let me save all of these modifications here and back to the application here so here we have the use of claims username email full name then time of login so here we have shown how to consume where baby I met that by passing HTTP had the authorization using access token finally we need to make few more changes related to consuming web api method like this here we have two problems first problem we have to append this be error access token to every web api method which need authorization second problem when we pass access token like this we will get for not one unauthorized response because the access token that is saved inside local storage will expel within sixty minute or as per our configuration after that we will get for not one another rise status code in those cases we need to redirect the user to login component so these two steps should be done with everywhere babyis method which need authorization so we have to find a place where we can handle these common tasks for that we have interceptors in angular 5 now let's look how we can use interceptors in angular five for that first of all inside this earth folder I will create a new file new file I will name this file as auth door interceptor dot TS file first of all I will add all required import statement here after that we have to create a class which is to be injected in another places so I will this decorator injectable here so here we have created the class odd in the scepter which is implemented from HTTP in the scepter now we have to implement HTTP interceptor here inside this function we will do the common task before this intercept function I want to inject route or inside this class so here we have injected router here now back to the intercept function once we implement this HTTP interceptor inside this application or HTTP request will be passed through this function intercept inside this function we will append mirror access token to every request and we will handle for not one another I status code but there are some requests which does not mean authorization talk and like login and user registration in order to bypass those because from this intercept function we can do this we will have and if close here inside that we will check whether the requests have got a property no auth as true then we will bypass the request like this after that we will check this if local storage has a user token or not if there is a user token that means this user is authenticated in that case we will clone the current request inside the request hard or we will add authorization with access token from local storage and heavy executed the clone request if the request is successful we won't do anything inside error we will check if status code is for not one or not that means where the access token is expect or not in that case we will redirect the user to login page finally I want to add an else block for this if statement here that means there is no token for current user in local storage in that case also we will redirect the user to login page now we have created a node interceptor now we need to tell the application we have created an auth scepter and we need to use them for that you can open app module dot es file inside the providers array we have to add edges an object like this okay here we have provide use class and multi for these classes we have to add import statement hold ctrl then press P read click on this imported man same fourth interceptor also now back to the odd interceptor inside this intercept function first of all we made an assumption request which does not need access token will have had a property north as true so let's find those requests and add this property though for that open user service class first of all we have register user function inside that we made a request to the user register Web API method now we need to add no odd property to the header for that first of all I will create a property because header like this now we can pass this header here headers is equal to request header property now we have to do the same for this token request also so I will add this attribute North here North is equal to true since we have a derby our access token inside this HTTP interceptor we don't need to add this mirror talk and again inside this get user claims we will add them from HTTP interceptor so we can remove that from here now let me save all of these modifications here and back to the application let me log out from this application in order to test the complete working of this application first of all let me add a user here username will be benjamine then password will be 1 2 3 then we have email I will type it as 1 2 3 at gmail.com then we have first name I will tap it as Benjamin John click on submit let me try to log in with this Benjamin record username will be Benjamin then password will be one two three click on login now if you want to logout from this application you can click on this knock out button here so in this tutorial we have discussed how to implement login and logout in angular 5 with Web API and token-based authentication if you found this video helpful please thumbs up this video and for more over some videos like this please please subscribe to this channel dotnet mob you can download this project source code from the link given below in video description 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: 326,080
Rating: 4.8564401 out of 5
Keywords: Angular 5 Login Logout with Web API, Angular 5 User Authentication Using Token Based Authentication, user authantication in angular 5, how to create login form in angular 5 project, token based authentication in web api using owin, token based authentication in angular 5, logout in angular 5, Routing gaurds in angular 5, angular 5 sample login example, angular 5 token authentication, owin bearer token authentication, token based authentication in web api, CodAffection
Id: e8BlURn6SFk
Channel Id: undefined
Length: 69min 28sec (4168 seconds)
Published: Tue Feb 13 2018
Related Videos
Note
Please note that this website is currently a work in progress! Lots of interesting data and statistics to come.