I'm now two weeks into learning and building an AngularJS
+ PHP
system and I'm still struggling with authentication. I've been reading a lot of posts about AngularJS
and not one of them seem to consider the security aspect of authentication. I also had an interesting response when I asked about the security of AngularJS
storages on another post, and got two great links to Stormpath's blogs which cover areas of security when dealing with tokens
.
Most tutorials and examples about AngularJS
seem to be taking a JWT
approach and sending that token to your REST API
via HTTP headers
, but given that the token is stored in Javascript this can expose it to multiple attack types. One of them being MITM. To be secure against this type of attack the solution is to set a cookie with HttpOnly and Secure flags. Now the token gets passed on every request, it's not being stored by Javascript and it's secure. However, this raises the question at the point where you authenticate the user: How is this any different than using sessions when you're only dealing with HTTP requests originating from the same server?
When checking if a user has already logged in we usually check if a $_SESSION
variable exists, let's say uid
. Now on a token based approach we send the token in HTTP headers
and read that token, then validate it and get user information. In AngularJS
we then get the successful response and return a promise.
Sessions have the advantage of being handled by the server. They create a session and they handle it's destruction automatically if it still lingers there. When dealing with a token based authentication you have to take care of it's expiration, refreshing and destruction with a scheduled script if the user has not destroyed it himself. This seems like too much work.