Angular 5 HTTP客户端具有"授权"响应标头中缺少

时间:2018-02-13 23:16:14

标签: angular http jwt

我正在使用JWT(JSON Web Tokens)作为将人员记录到系统中的一部分。执行此操作的代码如下:

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

usernamepassword发送到服务器时,Response对象包含Header中的加密授权。

作为标题的一部分包含Authorization条目和Pragma条目。 Authorization已正确定义令牌(并且可以正常工作)。 Pragma也定义为no-cache

Chrome中的“网络”标签:

enter image description here

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

 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 ----");

执行代码的结果:

enter image description here

从执行的代码中,可以看到尝试查找Authorization时返回nullPragma获得no-cache。发生了什么事?

更新

感谢所有人提供的信息。

我按照这里的信息: https://github.com/angular/angular/issues/13554

并对java代码进行了更改:

@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);

    }

再次感谢!

1 个答案:

答案 0 :(得分:1)

要解决此问题,我们需要从后端公开所需的标头,并使用并编写自定义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'));
        }
      }),
    );
  }
}

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

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 {}

sample coderepos can有助于进一步了解Angular HttpInterceptor