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?