고을마을 : 나의 코딩 이야기

항해99 38일차 TIL[CORS, JSESSIONID] 본문

항해99 7기/TIL(Today I Learned)

항해99 38일차 TIL[CORS, JSESSIONID]

고을마을 2022. 6. 16. 01:54

2022년 6월 15일. 항해 38일차.

요근래 너무 정신없는 하루를 보냈다.

주특기 학습을 끝내고 나서 미니프로젝트를 진행하게 됐다.

프론트 분들과 함께 작업을 하는데 에러와 에러의 연속이었다.

로그인 회원가입 기능을 무턱대고 맡아서 조원들이 내 작업이 끝날때까지 기능 확인을 하지 못했다ㅠㅠ

 

가장 큰 어려움은 스프링시큐리티, CORS와 JSESSIONID 문제였다.

 

@Bean
public CorsConfigurationSource corsConfigurationSource() {
    CorsConfiguration configuration = new CorsConfiguration();
    //configuration.addAllowedOrigin("http://firstreactproject.s3-website.ap-northeast-2.amazonaws.com");                               // local 테스트 시
    //configuration.addAllowedOrigin("http://localhost:3000");                                                                          // local 테스트 시
    configuration.addAllowedMethod("*");
    configuration.addAllowedHeader("*");
    configuration.addExposedHeader("Authorization");
    //configuration.addAllowedOriginPattern("http://localhost:3000"); // 배포 전 모두 허용
    configuration.addAllowedOriginPattern("http://localhost:3001"); // 배포 전 모두 허용
    configuration.setAllowCredentials(true);
    configuration.addExposedHeader("JSESSIONID");


    UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
    source.registerCorsConfiguration("/**", configuration);
    return source;
}

 

일요일에 CORS에 대한 공부를 했음에도 CORS를 열어주는데 애를 먹었던 것같다.

Allow-Origin만 알고었던 나는 addAllowedOriginPattern을 해주지 않아서 localhost:3000이 열리지 않았었다.

머리가 뜨끈해질 정도로 구글링을 해서 찾아낸 addAllowedOriginPattern 잊을 수가 없을 듯하다.

 

protected RestUsernamePasswordAuthenticationFilter getAuthenticationFilter(){
    RestUsernamePasswordAuthenticationFilter authFilter = new RestUsernamePasswordAuthenticationFilter();
    try{
        authFilter.setFilterProcessesUrl("/user/login"); // 로그인에 대한 POST 요청을 받을 url을 정의합니다. 해당 코드가 없으면 정상적으로 작동하지 않습니다.
        authFilter.setUsernameParameter("username");
        authFilter.setPasswordParameter("password");
        authFilter.setAuthenticationManager(this.authenticationManagerBean());
        authFilter.setAuthenticationSuccessHandler(successHandler());
        authFilter.setAuthenticationFailureHandler(failureHandler());

    } catch (Exception e){
        e.printStackTrace();
    }
    return authFilter;
}

 

스프링 시큐리티에서 /user/login 을 열어주고 username, password를 받아 로그인을 처리했다.

 

근데 로컬 상에서는 로그인과 동시에 sessionid가 함께 생성되었지만

서버에 올렸을땐 sessionid가 형성되지 않는 문제가 발생했다.

 

궁여지책으로 

 

public class RestLoginSuccessHandler implements AuthenticationSuccessHandler {
    @Autowired
    private UserRepository userRepository;
    @Autowired
    private HttpSession httpSession;

    @Override
    public void onAuthenticationSuccess(HttpServletRequest request, HttpServletResponse response, Authentication authentication) throws IOException {

        response.setContentType("application/json");
        response.setCharacterEncoding("utf-8");
        response.addHeader("JSESSIONID",httpSession.getId());
        response.setStatus(HttpServletResponse.SC_OK);

 

http 헤더에다가 jsessionid를 직접 넣어주고 

프론트 쪽에서 이걸 쿠키로 사용할수 있게 했다.

 

이 방법이 맞는 방법인지는 잘 모르겠다. 

구글에서도 나오지 않는 방법이기도 하고 보안에 취약할 것 같은 느낌이...ㅜㅜ

 

내일 기술매니저와 회고 시간을 갖게 되는데, 이 문제에 대해서 물어봐야겠다.