【问题标题】:How can I get my JWT from my header response?如何从我的标头响应中获取我的 JWT?
【发布时间】:2021-06-29 21:41:35
【问题描述】:

我创建了一个 Angular/Java 项目,但我无法获得响应中的 JWT 令牌。

onLoggedin()
  {
    this.authService.login(this.user).subscribe((data)=> {
      let jwToken = data.headers.get('Authorization');
      this.authService.saveToken(jwToken);
      this.router.navigate(['/']);
    },(err)=>{   this.err = 1;
});

此方法在我的服务中调用以下方法

login(user : User)
  {
    return this.http.post<User>(this.apiURL+'/login', user , {observe:'response'});
  }

当我在浏览器中检查服务器响应时,我在标头中找到了令牌。 Header response

但是我的令牌是空的。我的 Angular 结果中似乎不存在“授权”属性。

或者当我修复 CORS 策略时可能会出现问题

@EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter {

    @Autowired
    UserDetailsService userDetailsService;

    @Autowired
    BCryptPasswordEncoder bCryptPasswordEncoder;

    @Override
    protected void configure(AuthenticationManagerBuilder auth) throws Exception {
        auth.userDetailsService(userDetailsService).passwordEncoder(bCryptPasswordEncoder);
    }

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http.cors().configurationSource(corsConfigurationSource());
        http.csrf().disable();

        http.sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS);
        http.authorizeRequests().antMatchers("/login").permitAll();
        http.authorizeRequests().antMatchers("/all").hasAuthority("ADMIN");

        http.authorizeRequests().anyRequest().authenticated();
        http.addFilter(new JWTAuthenticationFilter(authenticationManager()));
        http.addFilterBefore(new JWTAuthorizationFilter(), UsernamePasswordAuthenticationFilter.class);
    }

    CorsConfigurationSource corsConfigurationSource() {
        CorsConfiguration configuration = new CorsConfiguration();
        configuration.setAllowedMethods(Arrays.asList("GET", "POST", "PUT", "DELETE"));

        UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
        source.registerCorsConfiguration("/**", configuration.applyPermitDefaultValues());
        return source;
    }
}

【问题讨论】:

  • 您是否设置了 CORS 响应以允许客户端读取相应的响应标头?我认为这是一个“Access-Control-Expose-Headers”标头 - 我认为 this stack question 可能会有所帮助 - 或者可能是 this documentation

标签: javascript java angular jwt response-headers


【解决方案1】:

试试这个库,它会获取令牌并对其进行解码:

import jwt_decode from 'jwt-decode';

然后创建一个返回这个的函数:

return jwt_decode(localStorage.getItem('token'))

仅获取令牌:

private getToken() {
    return `${localStorage.getItem('token')}`;
  }

【讨论】:

  • 问题不是从localstorage获取token而是方法data.headers.get('Authorization')返回null而不是返回服务器响应的token
猜你喜欢
  • 2021-04-20
  • 2019-12-25
  • 2020-11-16
  • 2020-11-30
  • 2013-05-28
  • 2016-12-21
  • 1970-01-01
  • 1970-01-01
  • 2020-07-05
相关资源
最近更新 更多