0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 3 years have passed since last update.

AngularでヘッダーにJWTトークンを常につけたい

Posted at

Angularで取得した認証用JWTトークンを、ヘッダーに常につけておきたいですよね。

1.そんな時はInterceptorを使います。

ng g interceptor JwtToken

JwtTokenInterceptor.ts
import { Injectable } from '@angular/core';
import {
    HttpRequest,
    HttpHandler,
    HttpEvent,
    HttpInterceptor
} from '@angular/common/http';
import { Observable } from 'rxjs';

@Injectable()
export class JwtTokenInterceptor implements HttpInterceptor {

    constructor() {
    }

    intercept(request: HttpRequest<unknown>, next: HttpHandler): Observable<HttpEvent<unknown>> {
        const token = localStorage.getItem('jwt-token'); // 何らかの方法でJWTトークンを保持・取得
        if (token) {
            const req = request.clone({
                setHeaders: {
                    'Content-Type': 'application/json',
                    Authorization: 'Bearer ' + token,
                },
            });
            return next.handle(req);
        }
        return next.handle(request);
    }
}

2.app.module.tsのprovidersにinterceptorを登録する。

app.module.ts
    providers: [
        {provide: HTTP_INTERCEPTORS, useClass: JwtTokenInterceptor, multi: true},
    ]


これでリクエストごとにヘッダーにAuthorizationが追加され、JWTトークンが送られます。

0
0
3

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?