-1

I am using a spring boot as backend and react frontend to create a website and I am encountering an error when fetching a user profile using browser from the backend.After login i managed to generate and set JWT token but i failed to get user profile detail

BACK_END

 @Bean
    SecurityFilterChain defaultSecurityFilterChain(HttpSecurity http) throws Exception {
        http.csrf(AbstractHttpConfigurer::disable)
                .cors(Customizer.withDefaults())
                .authorizeHttpRequests((requests) -> {
            requests.requestMatchers("/roles/**").permitAll();
            requests.requestMatchers("/auth/**").permitAll();
            requests.requestMatchers("/jobs/**").hasAnyRole("APPLICANT");
            requests.requestMatchers("/applications/**").permitAll();
            requests.requestMatchers("/users/**").hasAnyRole("APPLICANT");
            requests.anyRequest().authenticated();
        });
        http.formLogin(Customizer.withDefaults());
        http.httpBasic(Customizer.withDefaults());
        http.addFilterBefore(jwtAuthFilter, UsernamePasswordAuthenticationFilter.class);
        http.exceptionHandling(exception->exception.authenticationEntryPoint(jwtAuthEntry));
        return http.build();
    }
 @GetMapping("profile")
    public ResponseEntity<User> getProfile(){
        User userDto=userService.profile();
        return ResponseEntity.ok(userDto);
    }

FRONT_END

const API_BASE_URL='http://localhost:8080/users';

export const getUserProfile=(token)=>fetch(API_BASE_URL+'/profile',{
    method:'GET',
    headers:{
     'Authorizations':token
    }
}).then(res=>res.text()).catch(error=>console.error(error))
 const getProfile=()=>{
    const token=localStorage.getItem('token')
    console.log(token)
    getUserProfile().then(res=>{
    setUsers(res)
    console.log(res.token)
     console.log(res.token)
   })
    }

although whenever I try to render the list, it gives me GET http://localhost:8080/users/profile 401 (Unauthorized)

is there a problem with my code? or is there an easier way to do this?

1 Answer 1

1

The name of the header you are looking for is Authorization, not Authorizations.

Also the Authorization header requires the Bearer auth scheme, so your front end code should look more like:

const API_BASE_URL='http://localhost:8080/users';

export const getUserProfile = (token) => 
    fetch(API_BASE_URL + '/profile', {
        method:'GET',
        headers: {
            'Authorization': `Bearer ${token}`
        }
    })
        .then(res => res.text())
        .catch(error => console.error(error));
Sign up to request clarification or add additional context in comments.

2 Comments

Thanks @Matt Schlosser when i tried to save those changes i get this error at the backendio.jsonwebtoken.MalformedJwtException: Invalid compact JWT string: Compact JWSs must contain exactly 2 period characters, and compact JWEs must contain exactly 4. Found: 0
According to your code above you are calling getUserProfile().then(...), which would need to be getUserProfile(token).then(...), otherwise you are not passing any value for the function parameter.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.