0
My JWT application has the following code:
my Model of user:
export class User {
id: number;
username: string;
password: string;
name: string;
admin: boolean;
token?: string;
}
The ts of the Login is:
this.authenticationService.login(this.f.username.value, this.f.password.value, this.fingerprint, this.admin)
.pipe(first())
.subscribe(
user => {
this.router.navigate(['/']);
},
error => {
this.error = error;
this.loading = false;
});
}
My headline is like this:
const httpOptions = {
headers: new HttpHeaders({
'Content-Type': 'application/json;charset=UTF-8',
'Accept-Language': '1'
}),
};
The login call is like this:
login(username: string, password: string, fingerprint: string, admin: boolean) {
return this.http.post<any>("http://site.com/url/login", { username, password, admin, fingerprint}, httpOptions)
.pipe(map(user => {
// login successful if there's a jwt token in the response
console.log("USER: " + user);
if (user) {
// store user details and jwt token in local storage to keep user logged in between page refreshes
localStorage.setItem('currentUser', JSON.stringify(user));
this.currentUserSubject.next(user);
}
return user;
}));
}
my contractor is like this:
intercept(request: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
// add authorization header with jwt token if available
let currentUser = this.authenticationService.currentUserValue;
if (currentUser && currentUser.token) {
request = request.clone({
setHeaders: {
'Authorization': `Bearer ${currentUser.token}`,
'Accept-Language': '1'
}
});
}
return next.handle(request);
}
Accessing the network tab. It does the request and returns 200 normally and the token appears in the header, but when I try to use the map to get the answer, in the application it is returning null. I have tested several methods and continues as null.
I’m making based on the jasonwatmore code of angular jwt 7;
Below is the return 200 and the token
Someone’s been through it?
Opa, like this it returns a [Object Object] in the console, but in this collection it does not pass to the Interceptor it from the error in: this.currentUserSubject.next(user); no service. , the error is: Argument of type '{ token: any; }' is not Assignable to Parameter of type 'User'. Type '{ token: any; }' is Missing the following properties from type 'User': id, username, password, name, admin
– Rubens Junior
obs. no note I put: note: 'Answer' as 'body', only answer if it gave an error
– Rubens Junior
I managed to print the token with your help, but doing so: . pipe(map((Answer: Httpresponse<any>) => { console.log("USER: " + Answer.headers.get('Authorization')); Now I need to fix this part of this.currentUserSubject.next(user)
– Rubens Junior
Just modify the User model to accept a token property, and pass the other required properties to it in the login service creation. Qto on note: 'Replay' as 'body', should work as well.
– Dante
Oops! Vlw bro!! It worked here, saved me!
– Rubens Junior