백엔드/spring
[springboot+react+jwt] jwt 인증 후 react에서 headers에 인증값이 없는 경우 해결 방법
첸첸
2022. 4. 11. 23:54
728x90
springboot에서 jwt 토큰 생성 후 아래의 코드 처럼 header에 값을 넣어서 보내주는데, react에서 받을 수 없었다.
@Override //attemptAuthentication가 실행이 된 후 인증이 정삳ㅇ적으로 된 경우 함수가 실행 -> jwt토큰 생성 후 사용자에게 리턴
protected void successfulAuthentication(HttpServletRequest request,
HttpServletResponse response,
FilterChain chain,
Authentication authResult) throws IOException, ServletException {
System.out.println("로그인 인증이 완료 됌");
PrincipalDetails principalDetails = (PrincipalDetails) authResult.getPrincipal();
//RSA 방식이 아닌 HASH 암호방식
String jwtToken = JWT.create()
.withSubject(principalDetails.getUsername())
.withExpiresAt(new Date(System.currentTimeMillis()+(1000*10*10*6))) //현재시간 + 1시간
.withClaim("id",principalDetails.getUser().getId()) //withClaim에는 넣고 싶은 값을 넣으면 된다.
.withClaim("username",principalDetails.getUser().getUsername())
.sign(Algorithm.HMAC512("mySecretKey"));
response.addHeader("Authorization", "Bearer " + jwtToken);
}
그러나 postman에서나, 개발자도구의 네트워크 상의 headers에서는 Authorization이라는 값을 찾을 수 있었다.
왜 또 내것만 이상한건데.... 왜...🤷🏻♀️
검색을 해보니 CORS 정책과 관련이 있는 문제였다. 관련 설정 파일에 Access-Control-Expose-Headers 값을 지정해주면 된다.
✨ SecurityConfig.java✨
@Bean
public CorsConfigurationSource corsConfigurationSource() {
CorsConfiguration configuration = new CorsConfiguration();
configuration.addAllowedOrigin("http://localhost:3000");
configuration.addAllowedHeader("*");
configuration.addAllowedMethod("*");
configuration.setAllowCredentials(true);
//exposed-headers 설정
configuration.setExposedHeaders(Arrays.asList("Access-Control-Allow-Headers", "Authorization, x-xsrf-token, Access-Control-Allow-Headers, Origin, Accept, X-Requested-With, " +
"Content-Type, Access-Control-Request-Method, Access-Control-Request-Headers"));
UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
source.registerCorsConfiguration("/**", configuration);
return source;
}
🌱 react
위에 CORS 정책을 변경해주면 아래에서 headers값을 가져올 수 있다.
const submit = () => {
axios
.post("http://localhost:8080/login", user)
.then((res) => {
console.log(res.headers);
})
};