问题描述
我正在发出发布请求(登录)。
它在响应标头(Set-Auth)中返回一个令牌。
如何在请求标头中提取和使用令牌?
login() {
if (this.loginForm.invalid) {
this.messageService.warning('You\'re missing something important',null);
return;
}
this.connecting.creating = true;
if (this.loginForm.valid) {
console.log(this.loginForm.value);
this.adminService.submitLogin(this.loginForm.value).subscribe(
(data: any) => {
this.messageService.success('Login Success','Success!');
this.router.navigate(['']).then();
},error => {
this.messageService.error('Something went wrong','Error!');
this.connecting.creating = false;
this.connectingErrors.creating = true;
}
);
}
}
解决方法
您需要在响应体内返回令牌。 获取该值并将其存储在localStorage中。然后创建这样的拦截器。
// src/app/auth/token.interceptor.ts
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);
}
}
// src/app/app.module.ts
import { HTTP_INTERCEPTORS } from '@angular/common/http';
import { TokenInterceptor } from './../auth/token.interceptor';
@NgModule({
bootstrap: [AppComponent],imports: [...],providers: [
{
provide: HTTP_INTERCEPTORS,useClass: TokenInterceptor,multi: true
}
]
})
export class AppModule {}
在此之后,每个http请求令牌都将作为授权...附加在标头上。
将jwt令牌存储在本地存储中很危险,因此我建议您使用XSS攻击来保护cookie方法。