簡體   English   中英

角度http攔截器響應頭

[英]angular http interceptor response header

我正在提出發布請求(登錄)。

它在響應頭(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 令牌存儲在本地存儲中是危險的,因此我建議您使用安全的 cookie 方法,因為 XSS 攻擊。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM