1

내 앱에서 전역 인증 헤더를 만들고 있습니다. 나는 get() 함수에서 권한 헤더를 선언하지 않도록 인터셉터를 사용했습니다. get() 함수를 호출 할 때부터 토큰을 요구하기 때문에 인터셉터를 올바르게 구현하고 있는가? 토큰이 제공되지 않는다고합니다. 내 auth.interceptor에 문제가 있습니까? 모든 get() 함수에서 권한 헤더 무기명 토큰을 선언해야합니까? 요청을 받거나받을 때마다 인터셉터가 호출된다고 생각 했나요?HttpClient 인터셉터에서 전역 권한 부여 헤더 만들기

auth.interceptor.ts

@Injectable() 
export class AuthInterceptor implements HttpInterceptor { 
    private authService: AuthService; 

    constructor(private injector: Injector) {} 

    intercept(req: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> { 
     // Get the auth header from the service. 
     this.authService = this.injector.get(AuthService); 
     const token = this.authService.getToken(); 
      if (token) { 
       req = req.clone({ headers: req.headers.set('Authorization', 'Bearer ' + token) }); 
      } 

      if (!req.headers.has('Content-Type')) { 
       req = req.clone({ headers: req.headers.set('Content-Type', 'application/json') }); 
      } 

      req = req.clone({ headers: req.headers.set('Accept', 'application/json') }); 
      return next.handle(req); 
     } 
} 

products.component.ts

getAll() { 
    return this.httpClient.get<any>(this.url).map(response => response.json()); 
    } 

답변

1

당신은 올바른 방법을 다하고 있습니다!

인터셉터는 모든 http 호출을 가로채는 데 사용되며 전역 요청을 변경할 수 있습니다.

나는이 조건에서 문제가 있다고 생각합니다. 당신은 그들을 디버그하고 그들을 해결할 수 있습니다.

  if (token) { 
       req = req.clone({ headers: req.headers.set('Authorization', 'Bearer ' + token) }); 
      } 

      if (!req.headers.has('Content-Type')) { 
       req = req.clone({ headers: req.headers.set('Content-Type', 'application/json') }); 
      } 

일부는 null을 반환합니다.

그러나 타이밍이 토큰을 얻는 데 문제가 있으면 비동기 호출을 통해 토큰을 얻을 수 있습니다.

this.authService.LoginUser().subscribe((token) => { 
    if (token) { 
    req = req.clone({ headers: req.headers.set('Authorization', 'Bearer ' + token) }); 
    } 

    if (!req.headers.has('Content-Type')) { 
    req = req.clone({ headers: req.headers.set('Content-Type', 'application/json') }); 
    } 

    req = req.clone({ headers: req.headers.set('Accept', 'application/json') }); 
    return next.handle(req); 
} 
}); 
+0

디버깅 해보십시오. 콘텐츠 유형있을 수 있습니다 거기에 들었어요 –

+0

하지만 왜 내 애플 리케이션에 로그인 할 수 있습니까? 어떻게 디버깅 할 수 있습니까> – Joseph

+0

몇 가지 중단 점을두고 실행이 여기에오고 모든 것이 정상임을 확인하십시오. 하나 더. 이 인터셉터를 모듈에 추가했다고 확신합니다. –