Angular2 Spring Boot JWT缺少响应头

时间:2017-01-11 10:49:08

标签: angular spring-boot jwt angular-cli angular2-jwt

我使用Angular2,Angular-cli,Spring Boot 1.4.0和jwt。当我登录我的Angular2客户端时,我无法获得jwt令牌。

我的安全配置是:

@Configuration
@Order(SecurityProperties.ACCESS_OVERRIDE_ORDER)
public class WebSecurityConfig extends WebSecurityConfigurerAdapter {

    @Override
    protected void configure(HttpSecurity http) throws Exception {

        http.csrf().disable() // disable csrf for our requests.
                .authorizeRequests()
                .antMatchers("/").permitAll()
                .antMatchers("/api/user/signup").permitAll()
                .antMatchers(HttpMethod.POST, "/api/user/login").permitAll()
                .anyRequest().authenticated()
                .and()
                // We filter the api/login requests
                .addFilterBefore(new JWTLoginFilter("/api/user/login", authenticationManager()), UsernamePasswordAuthenticationFilter.class)
                // And filter other requests to check the presence of JWT in header
                .addFilterBefore(new JWTAuthenticationFilter(), UsernamePasswordAuthenticationFilter.class);
               .permitAll().and().csrf().disable();
    }
}

我的TokenAuthenticationService是:

public class TokenAuthenticationService {

    private final long EXPIRATIONTIME = 1000 * 60 * 60 * 24 * 10; // 10 days
    private final String secret = "ThisIsASecret";
    private final String tokenPrefix = "Bearer";
    private final String headerString = "Authorization";
    public void addAuthentication(HttpServletResponse response, String username)
    {
        // We generate a token now.
        String JWT = Jwts.builder()
                    .setSubject(username)
                    .setExpiration(new Date(System.currentTimeMillis() + EXPIRATIONTIME))
                    .signWith(SignatureAlgorithm.HS512, secret)
                    .compact();
        response.addHeader("Access-Control-Allow-Origin", "*");
        response.setHeader(headerString, tokenPrefix + " "+ JWT);
        response.getHeaderNames().stream()
    .forEach(System.out::println);
    }
   }

当我向邮递员发送登录请求时,我收到这样的回复: enter image description here

但是我发送登录请求我的Angular2应用程序我无法接收名为“Authorization”自定义标头的响应头。我的回复对象是这样的: enter image description here

但我看浏览器控制台我看到我的costum标题“授权”。 enter image description here

我的Angular2代码是:

@Injectable()
export class LoginService {
  private authEvents: Subject<AuthEvent>;
  private cred: AccountCredentials;

  constructor(private http: JsonHttpService ){
    this.authEvents = new Subject<AuthEvent>();
    this.cred = new AccountCredentials();
  }


  login(email: string, password: string) {
    this.cred.password = password;
    this.cred.username = email;
    return this.http.post('http://localhost:9090/api/user/login', this.cred)
    .do((resp: Response) => {
      localStorage.setItem('jwt', resp.headers.get('Authorization'));
      this.authEvents.next(new DidLogin());
    });
  }

  logout(): void {
    localStorage.removeItem('jwt');
    this.authEvents.next(new DidLogout());
  }

  isSignedIn(): boolean {
    return localStorage.getItem('jwt') !== null;
  }
}

export class DidLogin {
}
export class DidLogout {
}

export type AuthEvent = DidLogin | DidLogout;

我的JsonHttpService是:

import { Injectable } from '@angular/core';
import { Observable } from 'rxjs/Observable';
import {
  Http,
  RequestOptionsArgs,
  RequestOptions,
  Response,
  Headers
} from '@angular/http';

const mergeAuthToken = (options: RequestOptionsArgs = {}) => {
  let newOptions = new RequestOptions({}).merge(options);
  let newHeaders = new Headers(newOptions.headers);
  const jwt = localStorage.getItem('jwt');

  if (jwt && jwt !== 'null') {
    newHeaders.set('Authorization', jwt);
  }
 newHeaders.set('content-type', 'application/x-www-form-urlencoded; charset=utf-8');

  // newHeaders.set('Access-Control-Allow-Origin', '*');
  newOptions.headers = newHeaders;
  return newOptions;
};

@Injectable()
export class JsonHttpService {

  constructor(private http: Http) { }


  get(url: string, options?: RequestOptionsArgs): Observable<Response> {
    return this.http.get(url, mergeAuthToken(options));
  }

  post(url: string, body: any, options?: RequestOptionsArgs): Observable<Response> {
    return this.http.post(url, body, mergeAuthToken(options));
  }

  put(url: string, body: any, options?: RequestOptionsArgs): Observable<Response> {
    return this.http.put(url, body, mergeAuthToken(options));
  }

  delete(url: string, options?: RequestOptionsArgs): Observable<Response> {
    return this.http.delete(url, mergeAuthToken(options));
  }

  patch(url: string, body: any, options?: RequestOptionsArgs): Observable<Response> {
    return this.http.patch(url, body, mergeAuthToken(options));
  }

  head(url: string, options?: RequestOptionsArgs): Observable<Response> {
    return this.http.head(url, mergeAuthToken(options));
  }


}

那么为什么我无法收到我的jwt令牌并添加我的浏览器localStorage?

4 个答案:

答案 0 :(得分:1)

默认情况下,浏览器不会向应用程序公开自定义标头。

您的Backend Cors配置中需要以下标题

'Access-Control-Expose-Headers' 'Authorization';

请注意,即使标头位于开发控制台中,如果服务器应用程序未公开它们,您的应用也无法读取它们。

答案 1 :(得分:0)

您是在另一个端口上运行Angular2应用程序和springboot吗?如果是这样,您是否在springboot应用程序中启用了CORS?

withCredentials: true添加到您的Angualr2帖子标题

this.http.post('http://localhost:9090/api/user/login', 
  { withCredentials: true },
  this.cred)

有关更多springboot JWT使用Angular,结帐Springboot JWT Starter

答案 2 :(得分:0)

解决问题的最佳方法是在应用程序中添加cors配置,如https://spring.io/blog/2015/06/08/cors-support-in-spring-framework所述。  您也可以按照以下方式执行此操作:

reinterpret_cast

答案 3 :(得分:0)

我在Angular 6中遇到了类似的问题,并且几天都找不到解决方案。经过谷歌搜索,沮丧,思考以及谁知道我还找到了答案:)

最后,我不得不切换到纯 javascript ,此解决方案对我有效:

http.open('POST', url, true);

http.setRequestHeader('Content-type', 'application/json');
http.setRequestHeader('Accept', 'application/json, text/plain, */*');

http.onreadystatechange = function() {
  if (http.readyState == 4 && http.status == 200) {
    console.log('xhr:', http.getAllResponseHeaders());
  }
}
http.send(params);

http.getAllResponseHeaders()返回类似于Web浏览器中的所有标头。 希望这也会对您有帮助。

我在https://www.html5rocks.com/en/tutorials/cors/

上找到了写得很好的有关CORS的帖子,该文章可能会引起麻烦。

就像@ evans-m一样,标头也必须公开

我仍然不确定Angular,浏览器甚至是弹簧是否有问题?!