0

我正在使用Azure B2C身份驗證。在成功重定向後,訪問令牌被存儲在瀏覽器的localStorage中,並且對於後續的API調用,http攔截器類應該將auth令牌附加到所有出站請求。問題是localStorage.getItem()在嘗試從localStorage讀取授權令牌時返回null。下面是代碼,Angular 4自定義http攔截器。 localStorage.getItem()返回空值

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

@Injectable() 
export class HttpManagerInterceptor implements HttpInterceptor { 

intercept(req: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> { 
    req = req.clone({ headers: req.headers.set('Accept', 'application/json') }); 
    req = req.clone({ headers: req.headers.set('X-CRSP-TOKEN', 'ToBeImplemented') }); 

    // this line always returns null 
    const authToken = window.localStorage.getItem('auth_token'); 

    console.log('Inside http interceptor. Access token: ' + authToken); 
    if (authToken) { 
     req = req.clone({ headers: req.headers.set('Authorization', `Bearer 
     ${authToken}`) }); 
    } 

    console.log(JSON.stringify(req.headers)); 
    return next.handle(req); 
} 

控制檯登錄
令牌發現:
eyJ0eXAiOiJKV1QiLCJhbGciOiJSUzI1NiIsImtpZCI6Ilg1ZVhrNHh5b2pORnVtMWtsMll0djhkbE5QNC1jNTdkTzZRR1RWQndhTmsifQ.eyJpc3MiOiJodHRwczovL2xvZ2luLm1pY3Jvc29mdG9ubGluZS5jb20vYmY5Njg3YWYtOTliMy00YzU3LWI2YjAtOWE5OGIzNTRhOWQyL3YyLjAvIiwiZXhwIjoxNTA0MTMxNzM3LCJuYmYiOjE1MDQxMjgxMzcsImF1ZCI6IjI4ZGM0NjZkLWRhZGUtNDNkMy04ZjBhLTJkYmNlNTQxYmIxMyIsIm9pZCI6IjcyMzljZWVjLTMzN2ItNDlmNS04YzViLTVkMzcwZGEwZmIxOCIsImdpdmVuX25hbWUiOiJaZWVzaGFuIiwiZmFtaWx5X25hbWUiOiJIYWlkZXIiLCJzdWIiOiJOb3Qgc3VwcG9ydGVkIGN1cnJlbnRseS4gVXNlIG9pZCBjbGFpbS4iLCJlbWFpbHMiOlsiWmVlc2hhbi5IYWlkZXJAY3JzcC5jaGlj YWdvYm9vdGguZWR1Il0sImF6cCI6IjI4ZGM0NjZkLWRhZGUtNDNkMy04ZjBhLTJkYmNlNTQxYmIxMyIsInZlciI6IjEuMCJ9.DUebFoHuzLXIbjMOmRrCRYswMB1g-7J6kVOaYyI3-b5AuaTjrcTtTsZkiGbloseaKqKtKoRtO72EkyQ2XvJ2lyhCBybpD4skeOcwQ2p_RBcO1dlFSoWIOkQK7WPN_f3tLxzuvKgrcPuR2LurB_n0uEq8PTdMIKXgfuCVDUSjxGrcwlzGi61k2g24wzO-u9YdN5Xqx0eFqooE0hhiifTsAsXPNJhXTmLinr4qt25bRfvVs1UpYNk6hv1RQ3afrg7UZavr-Osjh5amQ6Qi_q6kKTQWorB9Cgoj_UTIA8ojkK-6y7D8uzY-YtLzomuNvD8mELCeZC8ZdPbbibzC2Kj6Rw

內部HTTP攔截。訪問令牌:空

我懷疑INTERCEPTORS是否可以在localStorage可用之前初始化或創建。如果是這種情況並且沒有解決方法,任何人都可以提出其他解決方案嗎?

您的幫助將不勝感激!

回答

0

您的組件內部進樣窗口

@Inject(WINDOW) private window: any