or
How to secure your API so that it can be accessed by any device, including Angularjs
what is authentication?
Why do we need authentication?
How have we implemented authentication so far?
What are the problems?
We need something that is
We need a token
Stands for JSON Web Tokens
Pronounced JOT
Almost every language can use them
var jwt = require('jsonwebtoken');
var payload = {id: 0};
var secret = 'wyuflgjwuylf';
var options = {};
jwt.sign(payload, secret, options, getToken);
function getToken(token){
console.log(token);
}
angular-auth git:(auth) ✗ node creating-token.js
eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJpZCI6MCwiaWF0IjoxNDU2NzgzMzk0fQ.yUuF48IMzTP0xIElmeHeQyaxy81jtRR8fU7xEBVz-aU
➜ angular-auth git:(auth) ✗
That results in
jwt.verify(token, secret, options, verifyToken);
function verifyToken(err, decoded){
console.log(decoded);
}
➜ angular-auth git:(auth) ✗ node verify-token.js
{ id: 0, iat: 1456784065 }
➜ angular-auth git:(auth) ✗
That results in
Use the super secure secret:
galvanize_rocks!
Using tokens with Angular is simple
app.controller('LoginController', login);
function($scope, AuthService, LocalStorageService, $location){
$scope.login = function(form){
AuthService.login(form.username, form.password)
.then(userLoggedIn);
}
function userLoggedIn(result){
LocalStorageService.set('token', result.token);
$location.path('/dashboard');
}
}
app.service('AuthService', auth);
function auth($http){
function login(username, password){
return $http({
method: 'POST',
url: '/api/v1/users/login',
data: {
username: username,
password: password
}
});
}
return {
login: login
};
}
app.service('LocalStorageService', localStorage);
function localStorage(){
function set(key, value) {
localStorage.setItem(key, value);
}
return {
set: set
};
}
app.service('BookService', book);
function book($http, LocalStorageService){
function edit(dataToUpdate){
var token = LocalStorageService.get('token');
return $http({
method: 'PUT',
url: '/api/v1/books/' + dataToUpdate.id,
headers: {
token: token
},
data: dataToUpdate
});
}
return {
edit: edit
};
}
How would you delete the token?
Start building that app!