To test my already deployed backend, I used Postman. Here I test the /auth
endpoint with email and password. We use JWT and this is what the request for Postman looks like:
URL : https://<api>/api/auth-service/auth
Body (raw/JSON) : {"email":"jelle@mail.com","password":"test"}
The response is a HTTP Status 200 OK with the Authorization
header containing the Bearer token. However, when I try (seemingly) the same with React using the fetch
command, it still receives the HTTP Status 200 OK, but without the Authorization
header.
static async handleSignIn(email, password) {
let result = null;
await fetch(process.env.REACT_APP_GATEWAY_URL + "/api/auth-service/auth", {
method: 'POST',
body: JSON.stringify({email: email, password: password}),
headers: {
"Content-Type": "application/json",
"accept": "*/*",
"Accept-Encoding": "gzip, deflate, br",
"Connection": "keep-alive",
}
})
.then((response) => {
if (response.headers.get("Authorization") != null) {
result = response.headers.get("Authorization");
}
})
.catch(error => {
console.log(error);
throw new Error(error.message)
});
return result;
}
The issue was the backend, I forgot to expose the Authorization header.
Access-Control-Expose-Headers: Authorization
In Java Spring Boot you can do that like this:
@Bean
CorsConfigurationSource corsConfigurationSource() {
final UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
final CorsConfiguration config = new CorsConfiguration();
config.setAllowCredentials(true);
config.addAllowedOrigin("*");
config.addAllowedHeader("*");
config.addExposedHeader("Authorization");
config.addAllowedMethod("OPTIONS");
config.addAllowedMethod("HEAD");
config.addAllowedMethod("GET");
config.addAllowedMethod("PUT");
config.addAllowedMethod("POST");
config.addAllowedMethod("DELETE");
config.addAllowedMethod("PATCH");
source.registerCorsConfiguration("/**", config);
return source;
}
NOTE: Allowing all origins and headers might not be the most secure way to go about doing this!
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.