Skip to content

Commit

Permalink
Merge pull request #147 from BOOK-TALK/#146-fix-jwt
Browse files Browse the repository at this point in the history
#146 [fix, feat] 토큰 예외처리 오류 해결 및 개발용 토큰 발급 API 추가
  • Loading branch information
chanwoo7 authored Sep 11, 2024
2 parents 2805d8d + aaf0156 commit 1eb22fe
Show file tree
Hide file tree
Showing 4 changed files with 63 additions and 6 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -55,7 +55,7 @@ public ResponseEntity<?> deleteAccount(HttpServletRequest request) {
description = LoginSuccessResponseDto.description)})
@PostMapping("/kakaoLogin")
public ResponseEntity<?> kakaoLogin(@RequestParam String idToken) {
LoginSuccessResponseDto loginSuccessResponseDto = OAuthService.oAuthLogin(Provider.KAKAO, idToken);
LoginSuccessResponseDto loginSuccessResponseDto = OAuthService.oAuthLogin(Provider.KAKAO, idToken, false);

return responseTemplate.success(loginSuccessResponseDto, HttpStatus.OK);
}
Expand All @@ -68,7 +68,33 @@ public ResponseEntity<?> kakaoLogin(@RequestParam String idToken) {
description = LoginSuccessResponseDto.description)})
@PostMapping("/appleLogin")
public ResponseEntity<?> appleLogin(@RequestParam String idToken) {
LoginSuccessResponseDto loginSuccessResponseDto = OAuthService.oAuthLogin(Provider.APPLE, idToken);
LoginSuccessResponseDto loginSuccessResponseDto = OAuthService.oAuthLogin(Provider.APPLE, idToken, false);

return responseTemplate.success(loginSuccessResponseDto, HttpStatus.OK);
}

@Operation(summary = "카카오 로그인 (테스트용)", description = "테스트용 카카오 로그인 API입니다. 만료기한이 3분인 엑세스 토큰을 반환합니다.",
parameters = {
@Parameter(name = "idToken", description = "id_token 값")
},
responses = {@ApiResponse(responseCode = "200", content = @Content(schema = @Schema(implementation = LoginSuccessResponseDto.class)),
description = LoginSuccessResponseDto.description)})
@PostMapping("/testKakaoLogin")
public ResponseEntity<?> customKakaoLogin(@RequestParam String idToken) {
LoginSuccessResponseDto loginSuccessResponseDto = OAuthService.oAuthLogin(Provider.KAKAO, idToken, true);

return responseTemplate.success(loginSuccessResponseDto, HttpStatus.OK);
}

@Operation(summary = "애플 로그인 (테스트용)", description = "테스트용 애플 로그인 API입니다. 만료기한이 3분인 엑세스 토큰을 반환합니다.",
parameters = {
@Parameter(name = "idToken", description = "id_token 값")
},
responses = {@ApiResponse(responseCode = "200", content = @Content(schema = @Schema(implementation = LoginSuccessResponseDto.class)),
description = LoginSuccessResponseDto.description)})
@PostMapping("/testAppleLogin")
public ResponseEntity<?> customAppleLogin(@RequestParam String idToken) {
LoginSuccessResponseDto loginSuccessResponseDto = OAuthService.oAuthLogin(Provider.APPLE, idToken, true);

return responseTemplate.success(loginSuccessResponseDto, HttpStatus.OK);
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -33,9 +33,9 @@ public class OAuthService {
private final JwtUtil jwtUtil;
private final OidcProviderFactory oidcProviderFactory;

// 카카오 로그인
// 소셜 로그인
@Transactional
public LoginSuccessResponseDto oAuthLogin(Provider provider, String idToken) {
public LoginSuccessResponseDto oAuthLogin(Provider provider, String idToken, Boolean isCustom) { // isCustom: 개발용
log.trace("OAuthService > oAuthLogin()");

if (idToken == null || idToken.isEmpty()){
Expand Down Expand Up @@ -67,7 +67,14 @@ public LoginSuccessResponseDto oAuthLogin(Provider provider, String idToken) {

// UserDetailsService를 사용하여 UserDetails 객체 생성
UserDetails userDetails = userDetailsService.loadUserByUsername(providerId);
JwtTokenDto jwtTokenDto = jwtUtil.generateToken(userDetails);

// 개발용
JwtTokenDto jwtTokenDto;
if (isCustom != null && isCustom) {
jwtTokenDto = jwtUtil.generateCustomToken(userDetails);
} else {
jwtTokenDto = jwtUtil.generateToken(userDetails);
}

// 사용자 인증 정보 생성 및 SecurityContext에 저장
Authentication authentication = new UsernamePasswordAuthenticationToken(userDetails, null, userDetails.getAuthorities());
Expand Down
3 changes: 2 additions & 1 deletion src/main/java/com/book/backend/global/SecurityConfig.java
Original file line number Diff line number Diff line change
Expand Up @@ -39,7 +39,8 @@ SecurityFilterChain securityFilterChain(HttpSecurity http) throws Exception {
.authorizeHttpRequests((authorize) -> authorize
.requestMatchers("/swagger-ui/**", "/v3/api-docs/**").permitAll() // Swagger 관련 경로
.requestMatchers("/login/oauth2/**").permitAll() // OAuth2 Callback 경로
.requestMatchers("/api/auth/signup", "/api/auth/login", "/api/auth/kakaoLogin", "/api/auth/appleLogin", "/api/auth/reissueToken").permitAll() // 회원가입, 로그인 경로
.requestMatchers("/api/auth/signup", "/api/auth/login", "/api/auth/kakaoLogin", "/api/auth/appleLogin", "/api/auth/reissueToken").permitAll() // 로그인 경로
.requestMatchers("/api/auth/testKakaoLogin", "/api/auth/testAppleLogin").permitAll() // 테스트용 로그인 경로 (개발용)
.requestMatchers("/.well-known/**").permitAll()
.requestMatchers("/ws-stomp/**").permitAll() // stomp 통신
// .requestMatchers("/**").permitAll() // 모든 API에 대한 인증 비활성화 (개발용)
Expand Down
23 changes: 23 additions & 0 deletions src/main/java/com/book/backend/util/JwtUtil.java
Original file line number Diff line number Diff line change
Expand Up @@ -43,6 +43,17 @@ public JwtTokenDto generateToken(UserDetails userDetails) {
.build();
}

// 개발용, 커스텀 유효기간 토큰 생성
public JwtTokenDto generateCustomToken(UserDetails userDetails) {
Claims claims = Jwts.claims();
claims.put("username", userDetails.getUsername());

return JwtTokenDto.builder()
.accessToken(createCustomAccessToken(claims))
.refreshToken(createRefreshToken(claims))
.build();
}

private String createAccessToken(Claims claims) {
return Jwts.builder()
.setClaims(claims)
Expand All @@ -52,6 +63,18 @@ private String createAccessToken(Claims claims) {
.compact();
}

// 개발용, 커스텀 엑세스 토큰 생성
private String createCustomAccessToken(Claims claims) {
// 개발용, 커스텀 유효기간
long customAccessTokenExpireTime = 180000L;
return Jwts.builder()
.setClaims(claims)
.setIssuedAt(new Date(System.currentTimeMillis()))
.setExpiration(new Date(System.currentTimeMillis() + customAccessTokenExpireTime))
.signWith(SignatureAlgorithm.HS256, secret)
.compact();
}

private String createRefreshToken(Claims claims) {
return Jwts.builder()
.setClaims(claims)
Expand Down

0 comments on commit 1eb22fe

Please sign in to comment.