On the server side you neary to the right thing. What you need to do: return back the token to the client:
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;
});
On the client side - if you get back a token in the body - you store it e.g. in the local storage
I am using angular 2 on the client side, here the code (client side login service) could look like this:
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
}
});
}
Each time you now hit your API again, do not forget to provide you token in the header and check it on the server side (JWT.verify()
).
Here you can find a more general introduction to JWT:
https://medium.com/vandium-software/5-easy-steps-to-understanding-json-web-tokens-jwt-1164c0adfcec
Hope that helps.