简体   繁体   中英

How to get JWT token from response header?

I created my first REST API in Spring Boot and used JWT token. When I send a POST request to my API, I get status OK and in the browser network option I can see a header with JWT token like on the picture. jwt 令牌

But I don't know how to get this token from the Response Headers and save it in for example local storage. I was trying a lot of things, but nothing works.

This is my POST request:

fetch('http://localhost:8080/login', {
    method: 'POST',
    headers: {
        'Content-Type': 'application/json',
    },
    body: JSON.stringify({
    username: 'linda',
    password: 'password'
    })
});

There is soultion if someone has the same problem. You have to add to ur config class this bean:

    @Bean
public CorsConfigurationSource corsConfigurationSource() {
    CorsConfiguration configuration = new CorsConfiguration();
    configuration.setAllowedOrigins(Arrays.asList("*"));
    configuration.setAllowedMethods(Arrays.asList("GET", "POST", "PUT", "PATCH", "DELETE", "OPTIONS"));
    configuration.setAllowedHeaders(Arrays.asList("Authorization", "content-type", "x-auth-token"));
    configuration.setExposedHeaders(Arrays.asList("x-auth-token","Authorization"));
    UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
    source.registerCorsConfiguration("/**", configuration);
    return source;
}

You'll have to use response.headers

fetch('http://localhost:8080/login', {
    method: 'POST',
    headers: {
        'Content-Type': 'application/json',
    },
    body: JSON.stringify({
        username: 'linda',
        password: 'password'
    })
}).then(response => {
    console.log(response.headers.get('Authorization'))
});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM