问题
I'd like to handle Basic Auth with AngularJS the right way. I'm pretty sure the answer is somewhere on SO, but I didn't find it. It seems that everyone has particular need about authentication and I'm confused. Note that I have no particular knowledge about authentication so sorry for dummy questions.
The case
- A REST API on a Django server that handles HTTP Basic Auth (The server)
- An AngularJS application embedded in Cordova/Phonegap to be used in smartphones (The client(s))
- The client logs in using HTTP basic auth. It's stateless, means the client need to provide credentials for each call to the API, for each web service.
What works for now
Login works now this way:
- User sees a login page, enters its email/pwd and validate
- angularJS client set the credentials in a cookie using $cookiestore
- angularJS client calls a GET with $http to http://myapp.com/api/login and with credentials in th HTTP header (basic authentication)
- If the request is a success, the user is considered logged.
- After that, as the cookie stores credentials, these credentials are sent in the HTTP Header at each web service call.
It works as expected.
What's wrong with this
The only problem with that system, is that when the smartphone application (ie. the angularJS/Cordova app) is closed, everything is lost and the user needs to log in again.
How could I fix it? Thanks a lot.
回答1:
Actually, it seems that cookies (even if the expiration date if set in the future) are deleted by Cordova when the application is closed, and there is now way to work around this.
However, using LocalStorage instead of cookies solves the problem perfectly. It's basically the same way to use than cookies since it's a key->value store. It's even cleaner.
This article is a good introduction to localStorage.
来源:https://stackoverflow.com/questions/27476336/howto-angularjs-basic-auth-cookie-to-a-rest-api-server