簡體   English   中英

如何獲得標頭授權

[英]How to get header Authorization

我不知道為什么我無法從 Postman 中看到的標題 AUTHORIZATION 中獲取值(從服務器返回)。

http://img110.xooimage.com/files/1/6/9/postman-567005e.png

我嘗試了很多東西,但我不知道為什么我仍然得到一個空值。

http://img110.xooimage.com/files/b/c/f/debug-5670075.png

這是我的代碼:

authentication-service.ts

login(u: User): Observable<HttpResponse<Response>> {

if ((u.username && u.password)) {
  this.user.setUsername(u.username);
  this.user.setPassword(u.password);
  // @ts-ignore
  const request = this.http.post<Response>(this.authUrl, this.user, {observe: 'response'}  )
    .pipe(
      tap((data: any) => {
        // @ts-ignore
        this.log(`Succès ${data.status} authentification succès`, 'success');
        this.navigateToCollection();
        console.log('data');
        console.log(data);
        console.log('data.headers.get(Authorization)');
        console.log(data.headers.get('Authorization'));
        return localStorage.setItem(TOKEN_KEY, data.headers.get('Authorization'));
      }),
      catchError(this.handleError<any>('login',
        console.log('je passe ici3')))
    );
  request.subscribe(value => {
     // console.log(value.headers.get('Authorization'));
     console.log(localStorage.getItem(TOKEN_KEY));
  });
  this.presentLoading(request);

  console.log('je passe ici4');
  return request;
} else {
  this.log('Renseignez les champs', 'error');
  alert('Erreur de login ou de mot de passe');
}

}

如果您需要更多信息,請咨詢我,我的令牌由我的服務認證(spring boot)發送。

我想知道如何獲取此標頭值。

感謝您的時間。

您必須從后端(服務器)公開標頭或將其傳遞到響應正文中。

Access-Control-Expose-Headers:headerName; 在您的 springBoot 應用程序中添加以下代碼:

response.setHeader("Access-Control-Expose-Headers", "Authorization");

否則你會得到它為空,但你將能夠在郵遞員中看到它。

我解決了我的問題,我正在使用網關,但你可以把它放在你的方法“配置”下面

 @Bean
CorsConfigurationSource corsConfigurationSource() {
    CorsConfiguration configuration = new CorsConfiguration();
    configuration.setAllowedOrigins(Arrays.asList("*"));
    configuration.setAllowedMethods(Arrays.asList("GET","POST", "PUT", "DELETE", "OPTIONS"));
    configuration.setAllowedHeaders(Arrays.asList("authorization",  "content-type"));
    configuration.setExposedHeaders(Arrays.asList("authorization"));
    UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
    source.registerCorsConfiguration("/**", configuration);
    return source;
}

暫無
暫無

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

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