Authentication and Session Storage

In this topic we will create our authentication service, use session storage and we will enable menu links based on user authentication.

Let's create a service by using command "ng generate service foldername/servicefilename", always create services in a folder otherwise it will create everything in src folder and it is very difficult to track it.

Now create our authentication service so the command will be "ng generate service service/hardcodedAuthentication", make sure you are in the project folder when you use the command. as shown below


When you open this service file you can see it is a simple class except @Injectable, it make this class as service and we can use this at any place of or project by importing it. Injectable make a class available for dependency injection Now add some method in this class.


Now we use this Authentication service in our login component, for using this we have to add this in constructor  and now as we move the authentication part in our service we need to update our handleLogin() method.

Till now we have created the authentication service and added the logic, now what we want to do is we want show the menu item based on user is logged in or not for that we will use session storage

Session storage is something which is a part of browser window, it allow us to access object of session storage, session storage is limited to the browser session it means when we close the browser session will be lost as well its object.

Now we will add some content in session storage and will check if the user is logged in or not.

Now if you click on inspect element and in application tab you can see session storage and when you log in you will the session object there.


Now we will enable or disable menu items based on user logged in for that we need to update of menu component, we have to add authentication service in constructor of menu.component.ts file and on the initialization of menu component we want to check if user is logged in.


In this approach we have one issue i.e. if we clear data from session storage and click on menu items it will work, this is because menu component is initialized only we refresh our page but here only content of page is refreshed. We can avoid it by directly calling the service and remove logic from ngOnInit to html.



Now Refresh you page and check.

In Next Topic we will implement logout functionality and see the use of route guard. 



Previous Topic                                                                             Next Topic


Comments

Popular posts from this blog

Installing Node Js (NPM) & Visual Studio Code

Header, Menu and Footer Component with CSS