角度http拦截器响应标头

问题描述

我正在发出发布请求(登录)。

它在响应标头(Set-Auth)中返回一个令牌。

如何在请求标头中提取和使用令牌?

response header

    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方法。

相关问答

Selenium Web驱动程序和Java。元素在(x,y)点处不可单击。其...
Python-如何使用点“。” 访问字典成员?
Java 字符串是不可变的。到底是什么意思?
Java中的“ final”关键字如何工作?(我仍然可以修改对象。...
“loop:”在Java代码中。这是什么,为什么要编译?
java.lang.ClassNotFoundException:sun.jdbc.odbc.JdbcOdbc...