본문 바로가기
웹개발/스프링부트

ResponseEntity에 header (httpOnly, secure, cookie ) 세팅하고 json 응답 리턴하기

by 어컴띵 2021. 3. 18.

jwt 구현중에 refreshToken은 httpOnly쿠키로 셋팅하고 accessToken은 json으로 응답을 리턴하는 코드

 

@RequestMapping(value = "/api/v1/authenticate", method = RequestMethod.POST)
    public ResponseEntity<?> createAuthenticationToken(@RequestBody JwtRequest authenticationRequest, HttpServletResponse response) throws Exception{
        authenticate(authenticationRequest.getUsername(),authenticationRequest.getPassword());
        final UserDetails userDetails = userDetailService
                .loadUserByUsername(authenticationRequest.getUsername());
        final String token = jwtTokenUtil.generateToken(userDetails);
        ApiResponse apiResponse = new ApiResponse();
        apiResponse.setData(token);
        ResponseCookie responseCookie = ResponseCookie.from("refreshToken",refreshToken)
                .httpOnly(true)
                .secure(true)
                .path("/")
                .maxAge(60)
                .domain("yourdomain.net")
                .build();
        return ResponseEntity.ok()
                .header(HttpHeaders.SET_COOKIE, responseCookie.toString())
                .body(apiResponse);
       
    }