Skip to content

Commit

Permalink
로그인 param -> body 변경
Browse files Browse the repository at this point in the history
  • Loading branch information
duhwan05 committed Aug 6, 2024
1 parent 7d94769 commit 39d7057
Show file tree
Hide file tree
Showing 2 changed files with 47 additions and 47 deletions.
Original file line number Diff line number Diff line change
@@ -1,13 +1,13 @@
package com.example.healthylife.controller;

import com.example.healthylife.config.jwt.JwtUtil;
import com.example.healthylife.dto.LoginRequest;
import com.example.healthylife.entity.UserEntity;
import com.example.healthylife.service.JwtAuthService;
import com.fasterxml.jackson.databind.ObjectMapper;
import io.swagger.annotations.ApiOperation;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.security.authentication.AuthenticationManager;
Expand All @@ -31,78 +31,63 @@ public class JwtLoginAuthController {
private final JwtAuthService jwtAuthService;
private final ObjectMapper objectMapper;

@ApiOperation("로그인 컨트롤러")
@ApiOperation("로그인")
@PostMapping("/authenticate")
public ResponseEntity<String> authenticate(@RequestParam String username, @RequestParam String password){
public ResponseEntity<String> authenticate(@RequestBody LoginRequest loginRequest){
try {
//사용자 이름(아이디)과 비번으로 인증
// 사용자 이름(아이디)과 비밀번호로 인증
Authentication authentication = authenticationManager.authenticate(
new UsernamePasswordAuthenticationToken(username, password));
new UsernamePasswordAuthenticationToken(loginRequest.getUsername(), loginRequest.getPassword()));

//인증 성공하면 JWT 토큰 생성
//accessToken 생성
// 인증 성공하면 JWT 토큰 생성
String accessToken = jwtUtil.createAccessToken(UserEntity.builder()
.userId(authentication.getName())
.build());
//refreshToken 생성
String refreshToken = jwtUtil.createRefreshToken(UserEntity.builder()
.userId(authentication.getName())
.build());
jwtAuthService.addRefreshToken(refreshToken, username);
jwtAuthService.addRefreshToken(refreshToken, loginRequest.getUsername());

Map result = Map.of("access-token", accessToken,
Map<String, String> result = Map.of("access-token", accessToken,
"refresh-token", refreshToken);

//생성된 토큰을 ResponseEntity로 반환
return ResponseEntity.ok()
.body(objectMapper.writeValueAsString(result));
} catch (UsernameNotFoundException | BadCredentialsException exception){
//사용자 이름이나 비번이 다른 경우 예외 처리
return ResponseEntity.status(HttpStatus.UNAUTHORIZED)
.body("Invalid username or password");

//todo 아이디 or 비번 따로따로 바꾸고 싶으면 catch 하나 더 주기
.body("아이디/비밀번호가 맞지 않습니다.");
} catch (Exception e) {
log.error("authenticate failed! - username: {}, password: {}", username, password, e);
log.error("authenticate failed! - username: {}, password: {}", loginRequest.getUsername(), loginRequest.getPassword(), e);
return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR)
.body("Exception : " + e.getMessage());
}


}

@GetMapping("/refresh")
public ResponseEntity<String> refresh(@RequestParam("refresh-token") String refreshToken){
try {
String accessToken = jwtAuthService.refresh(refreshToken);
//사용자 이름(아이디)과 비번으로 인증

// 현재 사용하지 않음
// @GetMapping("/refresh")
// public ResponseEntity<String> refresh(@RequestParam("refresh-token") String refreshToken){
// try {
// String accessToken = jwtAuthService.refresh(refreshToken);
// //사용자 이름(아이디)과 비번으로 인증
//
//
// Map result = Map.of("access-token", accessToken,
// "refresh-token", refreshToken);
//
// //생성된 토큰을 ResponseEntity로 반환
// return ResponseEntity.ok()
// .body(objectMapper.writeValueAsString(result));
// } catch (Exception e) {
// log.error("refresh failed! - refresh-token: {}", refreshToken, e);
// return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR)
// .body("Exception : " + e.getMessage());
// }
//
//
// }

Map result = Map.of("access-token", accessToken,
"refresh-token", refreshToken);

//생성된 토큰을 ResponseEntity로 반환
return ResponseEntity.ok()
.body(objectMapper.writeValueAsString(result));
} catch (Exception e) {
log.error("refresh failed! - refresh-token: {}", refreshToken, e);
return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR)
.body("Exception : " + e.getMessage());
}


}

@ApiOperation("로그아웃 컨트롤러")
@GetMapping("/logout")
public ResponseEntity<String> logout(@RequestParam("username") String username) {
// 클라이언트 측에서 토큰을 삭제하도록 처리
// response.setHeader("Set-Cookie", "accessToken=; HttpOnly; Path=/; Max-Age=0");
// response.setHeader("Set-Cookie", "refreshToken=; HttpOnly; Path=/; Max-Age=0");
jwtAuthService.logout(username);

return ResponseEntity.ok().body("Logout Successful");
}



Expand Down
15 changes: 15 additions & 0 deletions src/main/java/com/example/healthylife/dto/LoginRequest.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,15 @@
package com.example.healthylife.dto;

import lombok.Data;
import lombok.Getter;
import lombok.Setter;

@Data
@Getter
@Setter
public class LoginRequest {
private String username;
private String password;


}

0 comments on commit 39d7057

Please sign in to comment.