【发布时间】: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