Skip to content

Commit

Permalink
refactor: Security 관련 yml 환경 변수 분리
Browse files Browse the repository at this point in the history
  • Loading branch information
tjdtn0219 committed Jan 20, 2024
1 parent 63896b5 commit 672beec
Show file tree
Hide file tree
Showing 11 changed files with 54 additions and 16 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -25,8 +25,8 @@ public class EmailConfig {
public JavaMailSender mailSender() {
JavaMailSenderImpl mailSender = new JavaMailSenderImpl();
mailSender.setHost(host);
mailSender.setPort(port); //todo: 상수 분리
mailSender.setUsername(user); //todo: 상수 분리
mailSender.setPort(port);
mailSender.setUsername(user);
mailSender.setPassword(password);

Properties javaMailProperties = getMailProperties();
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -73,7 +73,7 @@ CorsConfigurationSource corsConfigurationSource() {
configuration.setAllowedMethods(List.of("*"));
configuration.setAllowedHeaders(List.of("*"));
configuration.addExposedHeader("Authorization");
configuration.setAllowCredentials(true); //todo : 쿠키를 포함한 크로스 도메인 요청을 허용? 확인필요
configuration.setAllowCredentials(true); //쿠키를 포함한 크로스 도메인 요청을 허용
configuration.setMaxAge(3600L);

UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
package kr.co.fastcampus.yanabada.common.exception;

import static kr.co.fastcampus.yanabada.common.response.ErrorCode.NOT_MATCHED_PROVIDER_NAME;

public class NotMatchedProviderNameException extends BaseException {
public NotMatchedProviderNameException() {
super(NOT_MATCHED_PROVIDER_NAME.getMessage());
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,7 @@
import kr.co.fastcampus.yanabada.common.exception.FcmAccessTokenGetFailedException;
import kr.co.fastcampus.yanabada.common.exception.FcmMessageSendFailedException;
import kr.co.fastcampus.yanabada.common.exception.JsonProcessFailedException;
import kr.co.fastcampus.yanabada.common.exception.NotMatchedProviderNameException;
import kr.co.fastcampus.yanabada.common.exception.OkHttp3RequestFailedException;
import kr.co.fastcampus.yanabada.common.exception.TokenExpiredException;
import kr.co.fastcampus.yanabada.common.jwt.dto.TokenExpiredResponse;
Expand Down Expand Up @@ -177,4 +178,13 @@ public ResponseBody<Void> fcmAccessTokenGetFailedException(
return ResponseBody.fail(e.getMessage());
}

@ExceptionHandler(NotMatchedProviderNameException.class)
@ResponseStatus(HttpStatus.INTERNAL_SERVER_ERROR)
public ResponseBody<Void> notMatchedProviderNameException(
NotMatchedProviderNameException e
) {
log.error("[NotMatchedProviderNameException] Message = {}", e.getMessage());
return ResponseBody.fail(e.getMessage());
}

}
Original file line number Diff line number Diff line change
Expand Up @@ -40,7 +40,7 @@ public class JwtAuthFilter extends OncePerRequestFilter {
protected boolean shouldNotFilter(HttpServletRequest request) throws ServletException {
/* 토큰 로그인, 회원가입 경우 해당 필터 실행 안됨 */
return request.getRequestURI().contains("/sign-up")
|| request.getRequestURI().contains("/login"); //todo: 로그아웃 추가 고민
|| request.getRequestURI().contains("/login");
}

@Override
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -51,7 +51,9 @@ public enum ErrorCode {

OKHTTP3_REQUEST_FAILED("okhttp3의 리퀘스트 생성이 실패하였습니다."),
FCM_MESSAGE_SEND_FAILED("FCM 메세지 전송이 실패하였습니다."),
FCM_ACCESS_TOKEN_GET_FAILED("FCM 엑세스 토큰을 발급 받는 데 실패하였습니다.")
FCM_ACCESS_TOKEN_GET_FAILED("FCM 엑세스 토큰을 발급 받는 데 실패하였습니다."),

NOT_MATCHED_PROVIDER_NAME("Provider 이름이 매칭이 안됩니다."),

;

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@

import java.util.HashMap;
import java.util.Map;
import kr.co.fastcampus.yanabada.common.exception.NotMatchedProviderNameException;
import lombok.AccessLevel;
import lombok.Builder;
import lombok.Getter;
Expand All @@ -28,7 +29,7 @@ static Oauth2Attribute of(
return ofKakao(KAKAO.name(), "email", attributes);
//todo: 다른 OAuth 구현 시 조건문 추가
}
throw new RuntimeException(); //todo: CustomEx
throw new NotMatchedProviderNameException();
}

private static Oauth2Attribute ofKakao(
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -5,20 +5,24 @@
import jakarta.servlet.http.HttpServletResponse;
import java.io.IOException;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.web.authentication.SimpleUrlAuthenticationFailureHandler;
import org.springframework.stereotype.Component;

@Slf4j
@Component
public class Oauth2LoginFailureHandler extends SimpleUrlAuthenticationFailureHandler {

@Value("${spring.login.root-url}")
String rootUrl;

@Override
public void onAuthenticationFailure(
HttpServletRequest request,
HttpServletResponse response,
AuthenticationException exception
) throws IOException, ServletException {
response.sendRedirect("http://localhost:8080/");
//todo: 환경 변수로 뺄 예정
) throws IOException {
response.sendRedirect(rootUrl);
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,7 @@
import kr.co.fastcampus.yanabada.domain.member.entity.ProviderType;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.security.core.Authentication;
import org.springframework.security.oauth2.core.user.DefaultOAuth2User;
import org.springframework.security.web.authentication.SimpleUrlAuthenticationSuccessHandler;
Expand All @@ -26,10 +27,14 @@
@RequiredArgsConstructor
public class Oauth2LoginSuccessHandler extends SimpleUrlAuthenticationSuccessHandler {

private final JwtProvider jwtProvider;
private final TokenService tokenService;
private final AuthService authService;
private final ObjectMapper objectMapper;
@Value("${spring.login.root-url}")
String rootUrl;
@Value("${spring.login.oauth2-redirect-url}")
String oauthRedirectUrl;
@Value("${spring.login.oauth2-password}")
String oauthPassword;

@Override
@Transactional
Expand All @@ -48,7 +53,6 @@ public void onAuthenticationSuccess(

if (isExist) {
/* 바로 로그인 */
String oauthPassword = "oauth-password"; //todo: 환경 변수 분리
LoginRequest loginRequest = new LoginRequest(email, oauthPassword);
LoginResponse loginResponse
= authService.loginOauth(loginRequest, ProviderType.valueOf(provider));
Expand All @@ -58,8 +62,9 @@ public void onAuthenticationSuccess(
response.getWriter().write(loginResponseJson);
} else {
/* 회원 가입 필요 */
//todo: url 변경 예정, 환경 변수(서버, 로컬) 분리 예정
String redirectUrl = "http://localhost:8080/redirect-url"
//todo: url 변경 예정
String redirectUrl = rootUrl
+ oauthRedirectUrl
+ "?email=" + attribute.get("email")
+ "&provider=" + attribute.get("provider");
response.sendRedirect(redirectUrl);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,7 @@
import kr.co.fastcampus.yanabada.domain.member.repository.MemberRepository;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.crypto.password.PasswordEncoder;
Expand All @@ -35,6 +36,8 @@ public class AuthService {
private final JwtProvider jwtProvider;
private final AuthenticationManagerBuilder authenticationManagerBuilder;
private final TokenService tokenService;
@Value("${spring.login.oauth2-password}")
String oauthPassword;

@Transactional
public Long signUp(SignUpRequest signUpRequest) {
Expand All @@ -59,8 +62,7 @@ public Long signUp(SignUpRequest signUpRequest) {
@Transactional
public Long oauthSignUp(OauthSignUpRequest signUpRequest) {

String encodedPassword = passwordEncoder.encode("oauth-password");
//todo: 패스워드 환경변수 분리
String encodedPassword = passwordEncoder.encode(oauthPassword);
Member member = Member.builder()
.email(signUpRequest.email())
.nickName(signUpRequest.nickName())
Expand Down
5 changes: 5 additions & 0 deletions src/main/resources/application.yml
Original file line number Diff line number Diff line change
Expand Up @@ -40,6 +40,11 @@ spring:
host: 127.0.0.1
port: 6379

login:
oauth2-password: oauth2-password
oauth2-redirect-url: /redirect_url
root-url: http://localhost:8080

jwt:
secretKey: yanabadaSecretKeyyanabadaSecretKeyyanabadaSecretKey

Expand Down

0 comments on commit 672beec

Please sign in to comment.