Objectives |
---|
Compare and contrast Cookie-Session and Web Token authentication strategies |
Use the Satellizer module to implement Web Token authentication in Angular |
With Express and Rails you learned the Cookie-Session authentication strategy. However, there's a better way to communicate authentication in Single Page Applications. You're going to use an encoded and signed chunk of JSON called a JSON Web Token, or JWT (pronounced "jot"), to communicate authentication between client and server.
Cookies vs Tokens. Getting auth right with Angular.JS [Auth0 Blog]
Aren't you tired of keeping track of all these things?
- Sessions: JWT doesn't require sessions.
- Cookies: With JWT, you save the web token to the client using
localStorage
. - CSRF: With JWT, you send the web token instead of a CSRF token.
- CORS: Forget about it - if your JWT is valid, the data is on its way.
JWT also has these benefits:
- Speed: You don't have to look up the session information.
- Storage: You don't have to store the session information.
- Mobile-Ready: Mobile apps don't let you set cookies, but they can save auth tokens.
- Testing: You don't have to make logging in a special case in your tests - just send the web token.
A JWT is pretty easy to identify. It is three strings separated by .
's.
aaaaaaaaaa.bbbbbbbbbbb.cccccccccccc
Each part has a different significance:
var header = {
"typ": "JWT",
"alg": "HS256"
}
var payload = {
"iss": "scotch.io",
"exp": 1300819380,
"name": "Chris Sevilleja",
"admin": true
}
var encodedString = base64UrlEncode(header) + "." + base64UrlEncode(payload);
HMACSHA256(encodedString, 'secret');
The
secret
acts as an encryption string known only by the two parties communicating via JWT. Protect your secrets!
eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJpc3MiOiJzY290Y2guaW8iLCJleHAiOjEzMDA4MTkzODAsIm5hbWUiOiJDaHJpcyBTZXZpbGxlamEiLCJhZG1pbiI6dHJ1ZX0.03f329983b86f7d9a9f5fef85305880101d5e302afafa20154d094b229f75773
Angular interceptors allow you to "intercept" HTTP requests and responses and change them. You can use an interceptor to attach a JWT to every outgoing HTTP request, and handle 401 (Unauthorized) statuses in any HTTP response.
/*
* app.js
*/
app.factory('authInterceptor', ['$rootScope', '$q', '$window', function ($rootScope, $q, $window) {
return {
request: function (config) {
config.headers = config.headers || {};
if ($window.localStorage.jwtToken) {
config.headers.Authorization = 'Bearer ' + $window.localStorage.jwtToken;
}
return config;
},
response: function (response) {
if (response.status === 401) {
// handle the case where the user is not authorized
}
return response || $q.when(response);
}
};
}]);
app.config(['$httpProvider', function ($httpProvider) {
$httpProvider.interceptors.push('authInterceptor');
}]);
Express4 + Mongoose + JSON Web Token Authentication [matoski.com]
- User signs up with email and password (client).
- Server creates a new user if everything is valid and sends back a JWT.
- Client receives the JWT and stores it in
localStorage
. - Client makes requests to the server with the JWT (this happens automatically using an Angular Interceptor).
- Server decodes the JWT and uses the token data to decide if user has access to the resource.
- User logs in with email and password (client).
- Server checks email and password, and if valid sends back a JWT.
- Client receives the JWT and stores it in
localStorage
. - Client makes requests to the server with the JWT (this happens automatically using an Angular Interceptor).
- Server decodes the JWT and uses the token data to decide if user has access to the resource.
Satellizer is an Angular module that hides a lot of the complexity of using JWTs. This is both a good and a bad thing. Let's not lose sight of how Satellizer is helping us:
- Provides methods to authenticate a user with email/password and any OAuth provider. These methods send requests to the server, and when the server responds, Satellizer takes care of saving the JWT to
localStorage
. - Sends the JWT with every request using an Angular Interceptor.
Work on the Angular Auth Satellizer Challenges.
- Cookies vs Tokens. Getting auth right with Angular.JS [Auth0 Blog]
- Express4 + Mongoose + JSON Web Token Authentication [matoski.com]
- JSON Web Tokens [jwt.io]
- Understanding JWT [Atlassian]
- The Anatomy of a JSON Web Token [scotch.io]
- Satellizer Docs