Angular 5 HTTP客户端具有“授权"响应标头中缺少 [英] Angular 5 HTTP Client has "Authorization" missing from the Response header

查看:121
本文介绍了Angular 5 HTTP客户端具有“授权"响应标头中缺少的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用JWT(JSON Web令牌)作为将人们登录到系统的一部分.执行此操作的代码如下:

I am working with JWT (JSON Web Tokens) as a part of logging people into the system. The code that does this is as follows:

this.http.post(url, JSON.stringify({ username: username, password: password }), { observe: 'response' })
      .subscribe((response: HttpResponse<any>) => {

usernamepassword发送到服务器时,响应对象在标头中包含加密的授权.

When sending the username and password to the server, the Response object contains the encrypted authorization in the Header.

作为标题的一部分包括的是Authorization条目和Pragma条目. Authorization具有正确定义的令牌(并且有效). Pragma也定义为no-cache

Included as part of the headers is an Authorization entry and also a Pragma entry. The Authorization has the token correctly defined (and it works). Pragma is also defined as no-cache

在Chrome的网络"标签中:

From Network tab in Chrome:

,但是在运行代码来处理响应标头时,Authorization标头不存在.

but when running the code to process the response headers, the Authorization header is not present.

 adminLogin(username, password) {
    let url = `${this._apiRoot}/login`;
    let tokenResp = {};

    this.http.post(url, JSON.stringify({ username: username, password: password }), { observe: 'response' })
      .subscribe((response: HttpResponse<any>) => {

        console.log(" ---- begin response ----");
        console.log( response );
        console.log(" ---- end response ----");

        let token = response.headers.get("Authorization");

        console.log(" ---- begin token ----");
        console.log ( token );
        console.log(" ---- end token ----");

        let pragma = response.headers.get("pragma");

        console.log(" ---- begin pragma ----");
        console.log ( pragma );
        console.log(" ---- end pragma ----");

执行代码的结果:

从执行的代码中,可以看到尝试找到Authorization的尝试返回了null,而Pragma的获取了no-cache.发生了什么事?

From the code executed, one can see that the trying to find the Authorization returns null while Pragma gets no-cache. What is going on?

更新

感谢所有信息.

我在这里关注了以下信息: https://github.com/angular/angular/issues/13554

I followed the information here: https://github.com/angular/angular/issues/13554

并更改了Java代码:

and made changes to the java code:

@Override
    protected void successfulAuthentication(HttpServletRequest req,
            HttpServletResponse res, FilterChain chain, Authentication auth)
            throws IOException, ServletException {
        String username = ((User) auth.getPrincipal()).getUsername();
        ApplicationUser user = applicationUserRepository
                .findByUsername(username);

        String token = Jwts
                .builder()
                .setSubject(((User) auth.getPrincipal()).getUsername())
                .claim("id", user.getId())

            [... snip ...]

            res.addHeader("Access-Control-Expose-Headers", "Authorization");
            res.addHeader(SecurityConstants.HEADER_STRING,SecurityConstants.TOKEN_PREFIX + token);

    }

再次感谢!

推荐答案

要解决此问题,我们需要从后端公开所需的标头,并使用并编写自定义

To solve this issue we need to expose the desired header from the backend side and use and write a custom HttpInterceptor.

NodeJs API示例:从后端公开authorization标头

res.setHeader('Access-Control-Expose-Headers', 'authorization'); 
res.setHeader('authorization', 'foo-bar');

示例角度拦截器

@Injectable()
export class HttpInterceptorService implements HttpInterceptor {
  intercept(request: HttpRequest<any>, next: HttpHandler): Observable<any> {
    return next.handle(request).pipe(
      tap(response => {
        if (response.headers) {
          console.log('Header keys', response.headers.keys());
          console.log('Authorization: ', response.headers.get('authorization'));
        }
      }),
    );
  }
}

最后,我们将拦截器添加到模块提供程序中

Lastly we add our interceptor to our module providers

import { NgModule } from '@angular/core';
import { HTTP_INTERCEPTORS } from '@angular/common/http';
import { HttpInterceptorService } from './http-interceptor.service';

@NgModule({
  ...
  providers: [
    { provide: HTTP_INTERCEPTORS, useClass: HttpInterceptorService, multi: true },
  ],
})
export class AppModule {}

示例代码

This sample code and repos can be usefull to know more about Angular HttpInterceptor

这篇关于Angular 5 HTTP客户端具有“授权"响应标头中缺少的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆