I'm developing an application using Spring Boot on backend and React on frontend. I'm having some issues with CORS and authorization: in particular, when I make a request from the frontend I put the Authorization header which contains the JWT token for authentication. Here an example from the code:
async function getUserInfo (username) {
const url = baseURL + "/users/" + username
const jwt = sessionStorage.getItem('token')
let [err, response] = await to(fetch(url), {
method: 'GET',
headers: {
'Authorization': 'Bearer ' + jwt,
'Content-Type': 'application/json'
}
})
...
}
When the request arrives to the backend, this header is missing and authentication fails. To configure CORS on Spring Boot, I use the @CrossOrigin annotation:
@CrossOrigin(origins = ["*"], allowedHeaders = ["*"], exposedHeaders = ["*"])
@RestController
class UserController (
val userDetailsService: UserDetailsServiceImpl,
val authenticationManager: AuthenticationManager,
val jwtUtils: JwtUtils
) {
...
}
The Security configuration is the following:
override fun configure(http: HttpSecurity) {
//csrf is enable by default
http.cors().and().csrf().disable()
.exceptionHandling().authenticationEntryPoint(authEntryPoint)
.and()
.sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS)
.and()
.authorizeRequests()
.antMatchers("/auth/**")
.permitAll()
.and()
.authorizeRequests()
.antMatchers("/users/{username}/**")
.hasAuthority("ADMIN")
.and()
.authorizeRequests()
.antMatchers("/**")
.hasAuthority("CUSTOMER")
.and()
.logout()
.permitAll()
http.addFilterBefore(JwtAuthenticationTokenFilter(jwtUtils),
UsernamePasswordAuthenticationFilter::class.java)
}
The requests are made using an ADMIN user on the endpoint /users/{username}, as shown in the frontend code.
How can I solve this problem?