如何从我的标头响应中获取JWT



我做了一个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'});
}

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

但我的代币是空的。似乎";授权";属性在我的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;
}
}

尝试使用此库,它会获取令牌并对其进行解码:

import jwt_decode from 'jwt-decode';

然后创建一个返回以下内容的函数:

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

只获取令牌:

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

最新更新