Save JWT token in LocalStorage Angular
I want to store a JWT token that I receive from my Spring Boot backend in the Local Storage of my Angular app. The JWT is send from Spring Boot in the header of the response.
In the method I call to log in I tried to save the token but I get this error in my browser console:
ERROR TypeError: Cannot read property 'get' of undefined
at SafeSubscriber.authenticationService.login.pipe.subscribe.wrongInput
My authentication.service
:
export class AuthenticationService {
private currentUserSubject: BehaviorSubject<User>;
public currentUser: Observable<User>;
tempUser: User;
constructor(
private loginService: LoginService,
private localStoreManager: LocalStorageManagerService
) {
this.currentUserSubject = new BehaviorSubject<User>(JSON.parse(this.localStoreManager.get()));
this.currentUser = this.currentUserSubject.asObservable();
}
public get currentUserValue(): User {
return this.currentUserSubject.value;
}
public login(data: User) {
return this.loginService.postLogin<any>(data)
.pipe(map(user => {
// tried to store the JWT Token here but I dont know how to get the headers here
this.localStoreManager.save(user);
this.currentUserSubject.next(user);
return user;
}));
}
My loginService.ts
:
export class LoginService {
constructor(private http: HttpClient) { }
public postLogin<T>(data: User): Observable<T> {
const url = 'http://localhost:8080/api/auth/login';
return this.http.post<T>(url, data);
}
My login.component.ts
(where I log in from component):
export class LoginComponent implements OnInit {
tempUser: User;
submitted = false;
loginForm: FormGroup;
wrongInput = false;
constructor(
private formBuilder: FormBuilder,
private router: Router,
private authenticationService: AuthenticationService,
private localStorage: LocalStorageManagerService
) {
this.createLoginForm();
}
ngOnInit(): void {
}
createLoginForm(): void{
this.loginForm = this.formBuilder.group({
email: [''],
password: ['']
});
}
onSubmit(): void {
this.submitted = true; //
this.wrongInput = false;
this.authenticationService.login(this.loginForm.value)
.pipe(first())
.subscribe((data: HttpResponse<any>) => {
console.log(data.headers.get('Authorization'))
this.localStorage.saveToken(data.headers.get('Authorization'))
this.router.navigate(['/home']);
},
error => {
this.wrongInput = true;
});
}
}
How can I save the JWT token that I receive in the response header from my post request to Spring boot on logging in?
Source: Angular Questions