Reputation: 404
I'm using Jwt token based authentication and use Angular 7 and node.js, I want to send a POST request to the server with a Token, everything is going well, but when I reload the page I have this error on the server side:
I have this node.js code in the middleware :
router.all('/*', function (req, res, next) {
let tok = '';
tok = req.headers["authorization"].split(' ')[1] || req.headers["authorization"];
jwt.verify(tok, secureKeyToken, (err, token) => {
if (err) return console.log('NO TOKEN! VERIFY');
res.locals.token = token;
next();
});
});
And I have this code in the Angular :
httpOptions = {
headers: new HttpHeaders({
"authorization": this._token.tokenGetter() || ''
})
};
reloadVorlage(id){
let endpoint = this.HOST_TURL + '/vorlag/go' // get one
return this.httpClient.post(endpoint, {id},this.httpOptions)
.pipe(catchError(this.errorHandler));
}
The question is, why does the token disappear when i reload the page? and how do I fix it ?
My English is weak, forgive me.
Upvotes: 0
Views: 2806
Reputation: 509
In order to have a JWT available after page refresh you have to store it in client side. you could use the browser localStorage or the cookies. my be this link will help you https://stormpath.com/blog/where-to-store-your-jwts-cookies-vs-html5-web-storage
Upvotes: 0
Reputation: 40
You have to store the jwt token in your localstorage (client side). So, when you login you generate the token in your api and send it to the angular app. In your angular app, you are going to receive the token, so you can put it in the localstorage:
localStorage.setItem("token", receivedToken);
Then, you can add a HttpInterceptor to intercept all your requests and automatically add the token in the authorization header.
The interceptor would be something like :
import { Injectable } from '@angular/core';
import {
HttpRequest,
HttpHandler,
HttpEvent,
HttpInterceptor
} from '@angular/common/http';
import { AuthService } from './auth/auth.service';
import { Observable } from 'rxjs/Observable';
@Injectable()
export class TokenInterceptor implements HttpInterceptor {
constructor(public auth: AuthService) {}
intercept(request: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
request = request.clone({
setHeaders: {
Authorization: `Bearer ${this.auth.getToken()}`
}
});
return next.handle(request);
}
}
Here you have a guide: https://medium.com/@ryanchenkie_40935/angular-authentication-using-the-http-client-and-http-interceptors-2f9d1540eb8
If you don't store your token in client side, you can't keep it after reloading the page.
Upvotes: 1