我创建了一个 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;
}
}
答案 0 :(得分:0)
尝试使用这个库,它获取令牌并对其进行解码:
import jwt_decode from 'jwt-decode';
然后创建一个返回这个的函数:
return jwt_decode(localStorage.getItem('token'))
仅获取令牌:
private getToken() {
return `${localStorage.getItem('token')}`;
}