Angular4 session handling

Viewed 11832

I have a sailsjs backend for API's and I want to use Angular4 for my frontend. I was wondering, how can I handle sessions on Angular? I tried reading the documentation and was unable to come up with anything.

Specifically I need to be able to handle the login, log out, CSRF protection, etc. Is it possible to use Angular4 in Sails because Sails has all of that built in?

4 Answers

yes, you can manage session by storing session details through a session service.

for best practice use google firebase auth feature which manages all the session, login and logout.

easy to implement... free from google... maintained by google....

Currently, I am working on an angular4 app whose backend API's are written in PHP and I am simply hitting them from my angular front end and getting the data, now in order to maintain session, I am simply using the SessionStorage and sometimes LocalStorage properties of javascript that allow us to save key/value pairs in a web browser.

ex: sessionStorage.setItem("keyname", "value");// to set

var myvar=sessionStorage.getItem("keyname");//to get

You have two options to do this

1. window.SessionStorage 2. Angular Service

1.In your case you can use SessionStroage So whenever user is logged in, just set the data in sessionStroage like this

sessionStorage.setItem('userData', userObj);

and on logout

sessionStroage.clear();

2. Second Option is to put your data in a globalService So this service will contain in-app data and as soon as user is logged out, just clear the service Data. Like this:-

@Injectable()
export class GlobalService {
login(){
  //initialize data here....
}

logout(){
   //remove your data....
 }
}

Note: if browser tab is closed this data will be lost. if you want to recover this data then put it inside window.localStorage

Related