How to use jwt token in axios request?

Viewed 436

I have a backend endpoint and whenever I send request via Postman, it is working and returning list of customers by using jwt token on postman.

But I want to get the list from a react app using axios get request but I can't.

I checked the answer on this question and applied.

Here is my code (I just hardcoded the token for test and the token is correct because I tried it on postman):

export async function getCustomerList() {

    let tok = "Bearer eyJhbGciOiJIUzUxMiJ9.eyJzdWIiOiJxcXFxIiwiZXhwIjoxNjUxMjcxNjk4LCJpYXQiOjE2NTEyNTM2OTh9.Fcjtz2_uCU0kybV1GX4TS6sbQ8E_TXNlih_bbxW0vCcQDRyU-F2rDbaOI7Iuog5VdoBU9_SM9gqtuCF5ZPzlzQ";

    return axios.get("http://localhost:8080/customer/list", {headers: {Authorization : tok}});
}

When I call this code, (I marked spring boot app endpoint controller class as @CrossOrigin to allow cors) the response from backend has 403 Forbidden and console log is CORS policy error as :

enter image description here

What am I missing here ? I though about headers but actually I am not sending any header via postman as well.

1 Answers

I solved it finally but actually it is not related to front-end. And react-axios code is working good. Even if I specified @CrossOrigin at spring boot side still need work to do. I have added http.cors() to backend configuration as:

@Override
    protected void configure(HttpSecurity http) throws Exception {
        http.csrf()
                .disable()
                .authorizeRequests()
                .antMatchers("/authenticate")
                .permitAll()
                .anyRequest()
                .authenticated()
                .and()
                .sessionManagement()
                .sessionCreationPolicy(SessionCreationPolicy.STATELESS);
        http.addFilterBefore(jwtFilter, UsernamePasswordAuthenticationFilter.class);
        http.cors();

    }
Related