1.通常登录方式都有哪些?

登录那些事儿

2.restful API 形式的 登录服务 passport-jwt

jwt 如何保证在浏览器中的安全存储

  1. Set-Cookie (http only)
  2. LocalStorage: JWT 在浏览器中以加密方式存储在 localStorage 中,但 localStorage 无法防范 XSS 攻击,好在 Angular2 有”跨站脚本安全模型”, 可按照文档

服务端实现

需要用到的库

  • jwt-simple (jwt encode decode)
  • moment
  • passport
  • passport-jwt

1.验证用户名密码后,响应生成的 jwt

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21

const me = {id:'1', email: 'seven__up@sina.cn', password: '123456', role: 'admin'};
const SECRET = 'my-jwt-secret';

app.post("/login", function(req, res) {
let email = req.body.email;
let password = req.body.password;
if (me.email == email && me.password && password) {
let payload = {
id: me.id,
role: me.role,
iat: moment().unix(), // 签发时间
exp: moment().add(5, 'minute').unix() // 过期时间
};
res.json({
token: jwt.encode(payload, SECRET);
});
} else {
res.sendStatus(401);
}
});

2.受限 API 的访问

route:

1
2
3
app.get("/user", auth.authenticate(), function(req, res) {  
res.json(users[0]);
});

authenticate:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
module.exports = function() {  
var strategy = new Strategy(params, function(req, payload, done) {
var user = users[payload.id] || null;
if (user) {
return done(null, {
id: user.id
});
} else {
return done(new Error("User not found"), null);
}
});
passport.use('jwt', strategy);
return {
initialize: function() {
return passport.initialize();
},
authenticate: function() {
return passport.authenticate('jwt', cfg.jwtSession);
}
};

get token

1
curl -H "Content-Type: application/json" -X POST -d '{"email":"seven__up@sina.cn","password":"123456"}' http://localhost:4300/api/auth/login

request with token

1
curl -I --header "Authorization:JWT TOKEN" localhost:4300/api/user