Skip to content

Commit

Permalink
refactor: orgin 성공시 cookie로 전달
Browse files Browse the repository at this point in the history
  • Loading branch information
Hoya324 committed Nov 28, 2024
1 parent 258abaa commit 34204a3
Show file tree
Hide file tree
Showing 4 changed files with 2 additions and 71 deletions.
56 changes: 0 additions & 56 deletions src/main/java/org/findy/findy_be/auth/api/AuthController.java
Original file line number Diff line number Diff line change
Expand Up @@ -3,8 +3,6 @@
import java.util.Date;

import org.findy.findy_be.auth.api.swagger.AuthAPIPresentation;
import org.findy.findy_be.auth.dto.request.AuthRequestModel;
import org.findy.findy_be.auth.oauth.domain.UserPrincipal;
import org.findy.findy_be.auth.oauth.token.AuthToken;
import org.findy.findy_be.auth.oauth.token.AuthTokenProvider;
import org.findy.findy_be.common.config.AppProperties;
Expand All @@ -13,15 +11,9 @@
import org.findy.findy_be.user.domain.RoleType;
import org.findy.findy_be.user.domain.UserRefreshToken;
import org.findy.findy_be.user.repository.UserRefreshTokenRepository;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestParam;

import io.jsonwebtoken.Claims;
Expand All @@ -36,7 +28,6 @@ public class AuthController implements AuthAPIPresentation {

private final AppProperties appProperties;
private final AuthTokenProvider tokenProvider;
private final AuthenticationManager authenticationManager;
private final UserRefreshTokenRepository userRefreshTokenRepository;

private final static long THREE_DAYS_MSEC = 259200000;
Expand All @@ -52,53 +43,6 @@ public String oauth(@PathVariable("app") String app) {
return "redirect:/oauth2/authorization/" + app;
}

@PostMapping("/api/auth/login")
public String login(
HttpServletRequest request,
HttpServletResponse response,
@RequestBody AuthRequestModel authRequestModel
) {
Authentication authentication = authenticationManager.authenticate(
new UsernamePasswordAuthenticationToken(
authRequestModel.getId(),
authRequestModel.getPassword()
)
);

String userId = authRequestModel.getId();
SecurityContextHolder.getContext().setAuthentication(authentication);

Date now = new Date();
AuthToken accessToken = tokenProvider.createAuthToken(
userId,
((UserPrincipal)authentication.getPrincipal()).getRoleType().getCode(),
new Date(now.getTime() + appProperties.getAuth().getTokenExpiry())
);

long refreshTokenExpiry = appProperties.getAuth().getRefreshTokenExpiry();
AuthToken refreshToken = tokenProvider.createAuthToken(
appProperties.getAuth().getTokenSecret(),
new Date(now.getTime() + refreshTokenExpiry)
);

// userId refresh token 으로 DB 확인
UserRefreshToken userRefreshToken = userRefreshTokenRepository.findByUserId(userId);
if (userRefreshToken == null) {
// 없는 경우 새로 등록
userRefreshToken = new UserRefreshToken(userId, refreshToken.getToken());
userRefreshTokenRepository.saveAndFlush(userRefreshToken);
} else {
// DB에 refresh 토큰 업데이트
userRefreshToken.setRefreshToken(refreshToken.getToken());
}

int cookieMaxAge = (int)refreshTokenExpiry / 60;
CookieUtil.deleteCookie(request, response, REFRESH_TOKEN);
CookieUtil.addCookie(response, REFRESH_TOKEN, refreshToken.getToken(), cookieMaxAge);

return accessToken.getToken();
}

@GetMapping("/api/auth/refresh")
public void refreshToken(HttpServletRequest request, HttpServletResponse response) {
// access token 확인
Expand Down
Original file line number Diff line number Diff line change
@@ -1,26 +1,16 @@
package org.findy.findy_be.auth.api.swagger;

import org.findy.findy_be.auth.dto.request.AuthRequestModel;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;

import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.responses.ApiResponse;
import io.swagger.v3.oas.annotations.tags.Tag;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import jakarta.validation.Valid;

@Tag(name = "Authentication API", description = "OAuth2 및 일반 로그인 관련 인증 API입니다.")
public interface AuthAPIPresentation {

@Operation(summary = "일반 로그인", description = "사용자 ID와 비밀번호를 통해 로그인을 처리합니다.", responses = {
@ApiResponse(responseCode = "200", description = "성공적으로 로그인 및 토큰 발급"),
@ApiResponse(responseCode = "401", description = "인증 실패")
})
String login(HttpServletRequest request, HttpServletResponse response,
@Valid @RequestBody AuthRequestModel authRequestModel);

@Operation(summary = "액세스 토큰 갱신", description = "Refresh Token을 사용하여 만료된 액세스 토큰을 갱신합니다.", responses = {
@ApiResponse(responseCode = "200", description = "성공적으로 토큰 갱신됨"),
@ApiResponse(responseCode = "401", description = "인증 실패 - 잘못된 또는 만료된 토큰")
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -40,9 +40,6 @@ public class OAuth2AuthenticationSuccessHandler extends SimpleUrlAuthenticationS
@Value("${jwt.access.header}")
private String accessHeader;

@Value("${jwt.access.frontUrl}")
private String frontUrl;

private static final String BEARER = "Bearer ";
private static final String LOCAL_URL = "http://localhost:5173";

Expand Down Expand Up @@ -71,8 +68,7 @@ public void onAuthenticationSuccess(HttpServletRequest request, HttpServletRespo
int cookieMaxAge =
(int)new Date(System.currentTimeMillis() + appProperties.getAuth().getTokenExpiry()).getTime() / 60;

CookieUtil.addCookie(response, "access_token", accessToken.getToken(), cookieMaxAge);

CookieUtil.addCookie(response, ACCESS_TOKEN, accessToken.getToken(), cookieMaxAge);
response.setHeader(accessHeader, BEARER + accessToken.getToken());

// clearAuthenticationAttributes(request, response);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,7 @@ public class OAuth2AuthorizationRequestBasedOnCookieRepository
public final static String OAUTH2_AUTHORIZATION_REQUEST_COOKIE_NAME = "oauth2_auth_request";
public final static String REDIRECT_URI_PARAM_COOKIE_NAME = "redirect_uri";
public final static String REFRESH_TOKEN = "refresh_token";
public final static String ACCESS_TOKEN = "token";
private final static int cookieExpireSeconds = 180;

@Override
Expand Down

0 comments on commit 34204a3

Please sign in to comment.