ํ ํ๋ก์ ํธ๋ก ๋ก๊ทธ์ธ ๋ก๊ทธ์์ ๋ฐ ๊ธฐํ๋ฅผ ๋ด๋นํ๊ฒ ๋์๋ค.
์คํ๋ง ์ํ๋ฆฌํฐ๋ฅผ ํตํด์ ์ ์์ ํ๋ ค๊ณ ํ๋๋ฐ ์ด๋ ค์ด ๋ถ๋ถ์ด ๋ง์ ๋ค์๊ธฐํ์ ๊ณต๋ถ๋ฅผ ํ๊ณ ๋ค์ ์๋ํด๋ณด๋ ค๊ณ ํ๋ค.๐
๊ทธ๋์ ์ด๋ฒ์๋ ๋ก๊ทธ์ธ ์ฒ๋ฆฌ ๋ฐ ๋ก๊ทธ์์ ์ฒ๋ฆฌ๋ฅผ ์๋น์ค ํํ๋ก ์ ์ํ์๋ค.
๋ก๊ทธ์ธ์ JWT ํ ํฐ์ ์ฟ ํคํํ๋ก ์ ์ํด์ ๋ง๋ค์ด ์๋ตํ๊ณ ๋ก๊ทธ์์์ ์ฟ ํค ํค๋๋ฅผ ์์ ๋ ์์
์ ์๋ํ์๋ค.
// AuthController
@RequiredArgsConstructor
@RestController
@RequestMapping("/auth")
public class AuthController {
private final AuthService authService;
@PostMapping("/login")
public ResponseEntity<ResponseDto> login(@RequestBody LoginUserDto loginUserDto,
HttpServletResponse response){
return ResponseEntity.status(HttpStatus.OK).body(authService.login(loginUserDto,response));
}
@PostMapping("/logout")
public ResponseEntity<ResponseDto> logout(HttpServletRequest request,
HttpServletResponse response){
return ResponseEntity.status(HttpStatus.OK).body(authService.logout(request,response));
}
}
// AuthService
@RequiredArgsConstructor
@Service
public class AuthService {
private final AuthenticationManager authenticationManager;
private final JwtUtil jwtUtil;
public ResponseDto login(LoginUserDto loginUserDto,
HttpServletResponse response){
Authentication authentication = authenticationManager.authenticate(
new UsernamePasswordAuthenticationToken(loginUserDto.getUserId(),loginUserDto.getPassword()));
UserDetails userDetails = (UserDetails) authentication.getPrincipal();
String token = jwtUtil.createToken(userDetails.getUsername());
Cookie cookie = new Cookie(JwtUtil.AUTHORIZATION_HEADER,token);
cookie.setMaxAge((int)jwtUtil.TOKEN_TIME);
cookie.setHttpOnly(true);
cookie.setPath("/");
response.addCookie(cookie);
return new ResponseDto(HttpStatus.OK.value(),"๋ก๊ทธ์ธ ์ฑ๊ณต");
}
public ResponseDto logout(HttpServletRequest request,
HttpServletResponse response){
Cookie cookie = new Cookie(JwtUtil.AUTHORIZATION_HEADER,null);
cookie.setMaxAge(0);
cookie.setPath("/");
response.addCookie(cookie);
return new ResponseDto(HttpStatus.OK.value(),"๋ก๊ทธ์์ ์ฑ๊ณต");
}
}