1

I make an Angular/Java project and I can't get the JWT token that is in my response.

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;
});

this method calls the following method in my service

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

When I check the server response in my browser, I found the token in the header. Header response

But my token is null. It seems the "Authorization" attribute doesn't exist in my Angular result.

Or maybe a problem when I fix the CORS policy

@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;
    }
}
Mohammad Mirzaeyan
  • 845
  • 3
  • 11
  • 30
Jeff Gbeho
  • 21
  • 1
  • 2
  • have you set CORS responses to allow the client to read the appropriate response header? I think that's a "Access-Control-Expose-Headers" header - I think [this stack question](https://stackoverflow.com/questions/36968963/how-to-configure-cors-in-a-spring-boot-spring-security-application) may help - or maybe [this documentation](https://docs.spring.io/spring-framework/docs/4.3.7.RELEASE_to_4.3.8.RELEASE/Spring%20Framework%204.3.8.RELEASE/org/springframework/web/cors/CorsConfiguration.html#setAllowedHeaders-java.util.List-) – Jaromanda X Jun 29 '21 at 09:40

1 Answers1

0

Try with this library, it gets the token and also decodes it:

import jwt_decode from 'jwt-decode';

And then create a function returning this:

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

To get only the token:

private getToken() {
    return `${localStorage.getItem('token')}`;
  }
jps
  • 20,041
  • 15
  • 75
  • 79
Al Max
  • 1
  • 3
  • The problem is not to get the token from the localstorage but the method data.headers.get('Authorization') return null instead to return the token of the server response – Jeff Gbeho Jun 29 '21 at 11:10