在服务器端你NEARY到正确的事情。你需要做的:令牌返回到客户端:
router.post("/login", koaBody, (ctx, next) => {
const data = ctx.request.body;
// ...
// extract username and password from body
// ...
db
.any("SELECT * FROM users ORDER BY id ASC") // here using and checking credentials is also missing ;-)
.then(function(data) {
// create the token
token = jwt.sign(data, token_secret, {
expiresIn: "24h" // expires in 24 hours
});
// now you have to pass it back to the client
// the token is NOT stored on the server side!
ctx.body = { 'token': token }
})
.catch(function(error) {
// error;
});
在客户端 - 如果你在身体得到一个令牌 - 你存储它例如在本地存储
我在客户端采用了棱角分明2,这里的代码(客户端登录服务)看起来是这样的:
login(credentials) {
const headers = new Headers();
headers.append('Content-Type', 'application/json');
headers.append('Accept', 'application/json');
const reqopt: RequestOptions = new RequestOptions({
headers: headers
});
// credentials: username, password --
return this.http.post(...your_api_endpoint_ + '/login', credentials, reqopt)
.map(res => {
const data = res.json();
if (data && data.token) {
localStorage.setItem('token', data.token); // <--- here you store your token
}
});
}
每次你现在又打你的API,不忘记在标题中提供标记并在服务器端检查它(JWT.verify()
)。
在这里你可以找到一个更一般性介绍JWT: https://medium.com/vandium-software/5-easy-steps-to-understanding-json-web-tokens-jwt-1164c0adfcec
希望有所帮助。
存储JWT的两种技术是本地存储和cookies(我知道) – RandomUs1r
Cookie是否仅存储在客户端Javascript? 我无法弄清楚它做服务器端。 –