Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

dev-auth-refactoring #20

Merged
merged 3 commits into from
Dec 14, 2023
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@
import com.fasterxml.jackson.databind.ObjectMapper;
import java.io.IOException;
import javax.servlet.http.HttpServletResponse;
import org.springframework.http.HttpStatus;

public class JsonBinderUtil {

Expand All @@ -17,6 +18,18 @@ public static HttpServletResponse setResponseWithJson(HttpServletResponse respon
return response;
}


public static HttpServletResponse setRedirectURLWithPathVariableType(HttpServletResponse response, int status,
Object type) throws IOException {
response.setContentType("application/json");
response.setStatus(HttpStatus.PERMANENT_REDIRECT.value());
response.setCharacterEncoding("UTF-8");
response.getWriter().write(getJsonFromType(type));
response.sendRedirect("");
return response;
}


private static String getJsonFromType(Object type) throws JsonProcessingException {
ObjectMapper objectMapper = new ObjectMapper();
return objectMapper.writeValueAsString(type);
Expand Down
24 changes: 0 additions & 24 deletions src/main/java/com/bit/lot/flower/auth/oauth/OauthController.java

This file was deleted.

This file was deleted.

This file was deleted.

This file was deleted.

Original file line number Diff line number Diff line change
@@ -0,0 +1,39 @@
package com.bit.lot.flower.auth.oauth.util;

import java.util.Base64;
import javax.crypto.Cipher;
import javax.crypto.SecretKey;
import javax.crypto.SecretKeyFactory;
import javax.crypto.spec.DESKeySpec;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

@Component
public class EncryptionUtil {

@Value("${user.info.secret}")
private String SECRET_KEY;

public String encrypt(String data) throws Exception {
Cipher cipher = getCipher(Cipher.ENCRYPT_MODE);
byte[] encryptedBytes = cipher.doFinal(data.getBytes());
return Base64.getEncoder().encodeToString(encryptedBytes);
}

public String decrypt(String encryptedData) throws Exception {
byte[] encryptedBytes = Base64.getDecoder().decode(encryptedData);
Cipher cipher = getCipher(Cipher.DECRYPT_MODE);
byte[] decryptedBytes = cipher.doFinal(encryptedBytes);
return new String(decryptedBytes);
}

private Cipher getCipher(int mode) throws Exception {
DESKeySpec desKeySpec = new DESKeySpec(SECRET_KEY.getBytes());
SecretKeyFactory keyFactory = SecretKeyFactory.getInstance("DES");
SecretKey secretKey = keyFactory.generateSecret(desKeySpec);

Cipher cipher = Cipher.getInstance("DES");
cipher.init(mode, secretKey);
return cipher;
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,47 @@
package com.bit.lot.flower.auth.oauth.util;

import com.bit.lot.flower.auth.common.valueobject.AuthId;
import com.bit.lot.flower.auth.social.dto.command.SocialLoginRequestCommand;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Component;

@RequiredArgsConstructor
@Component
public class UserInfoCipherHelper {

private final EncryptionUtil encryptionUtil;

public String encrpyt(String oauthRedirectURL,
SocialLoginRequestCommand command) throws Exception {

StringBuilder sb = new StringBuilder();
sb.append(oauthRedirectURL)
.append("/")
.append(encryptionUtil.encrypt(command.getSocialId().toString()))
.append("/")
.append(encryptionUtil.encrypt(command.getNickname()))
.append("/")
.append(encryptionUtil.encrypt(command.getEmail()))
.append("/")
.append(command.getPhoneNumber());

return sb.toString();
}


public SocialLoginRequestCommand decrypt(SocialLoginRequestCommand command) throws Exception {
String phoneNumber =encryptionUtil.decrypt(command.getPhoneNumber());
String email = encryptionUtil.decrypt(command.getEmail());
String socialId = encryptionUtil.decrypt(command.getSocialId().getValue().toString());
String nickname = encryptionUtil.decrypt(command.getNickname());
return createDecryptDto(phoneNumber, email, new AuthId(Long.valueOf(socialId)), nickname);
}


private SocialLoginRequestCommand createDecryptDto(String phoneNumber, String email,
AuthId socialId, String nickName) {
return SocialLoginRequestCommand.builder().phoneNumber(phoneNumber)
.socialId(socialId).nickname(nickName).email(
email).build();
}
}

This file was deleted.

Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
package com.bit.lot.flower.auth.social.dto.command;

import com.bit.lot.flower.auth.common.valueobject.AuthId;
import javax.validation.constraints.NotNull;
import lombok.AllArgsConstructor;
import lombok.Builder;
import lombok.Getter;
Expand All @@ -11,8 +12,12 @@
@NoArgsConstructor
@Getter
public class SocialLoginRequestCommand {
@NotNull
private AuthId socialId;
@NotNull
private String email;
private String phoneNumber;
@NotNull
private String nickname;

}
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
package com.bit.lot.flower.auth.social.http.controller;

import com.bit.lot.flower.auth.common.util.AuthIdCreator;
import com.bit.lot.flower.auth.oauth.util.UserInfoCipherHelper;
import com.bit.lot.flower.auth.social.dto.command.SocialLoginRequestCommand;
import com.bit.lot.flower.auth.social.dto.response.UserFeignLoginResponse;
import com.bit.lot.flower.auth.social.http.helper.OauthLogoutFacadeHelper;
Expand All @@ -11,13 +12,15 @@
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import javax.servlet.http.HttpServletRequest;
import javax.validation.Valid;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.ResponseEntity;
import org.springframework.security.core.annotation.AuthenticationPrincipal;
import org.springframework.web.bind.annotation.DeleteMapping;
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.RestController;
@Slf4j
@RestController
Expand All @@ -28,14 +31,15 @@ public class SocialAuthRestController {
private final OauthLogoutFacadeHelper oauthLogoutFacadeHelper;
private final SocialAuthService<AuthId> socialAuthService;
private final LoginSocialUserRequest userDataRequest;
private final UserInfoCipherHelper userInfoCipherHelper;

@ApiOperation(value = "유저 로그인", notes = "Authroization: Bearer 토큰 생성, Refresh토큰"
+ "Redis에 생성, HttpOnlyCookie에 생성")
@PostMapping("/social/login")
public ResponseEntity<UserFeignLoginResponse> loginWithUserServiceResponse(
HttpServletRequest request) {
SocialLoginRequestCommand dto = (SocialLoginRequestCommand) request.getAttribute("command");
UserFeignLoginResponse userFeignLoginResponse = userDataRequest.request(dto);
@Valid @RequestBody SocialLoginRequestCommand command) throws Exception {
SocialLoginRequestCommand decryptCommand = userInfoCipherHelper.decrypt(command);
UserFeignLoginResponse userFeignLoginResponse = userDataRequest.request(decryptCommand);
return ResponseEntity.ok(userFeignLoginResponse);
}

Expand Down
Original file line number Diff line number Diff line change
@@ -1,14 +1,17 @@
package com.bit.lot.flower.auth.social.security;

import com.bit.lot.flower.auth.common.util.JsonBinderUtil;
import com.bit.lot.flower.auth.oauth.util.EncryptionUtil;
import com.bit.lot.flower.auth.oauth.util.UserInfoCipherHelper;
import com.bit.lot.flower.auth.social.dto.command.SocialLoginRequestCommand;

import com.bit.lot.flower.auth.social.exception.SocialAuthException;
import java.io.IOException;
import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import lombok.RequiredArgsConstructor;
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.AuthenticationSuccessHandler;
Expand All @@ -18,6 +21,9 @@
@RequiredArgsConstructor
public class OauthAuthenticationSuccessHandler implements AuthenticationSuccessHandler {

private final UserInfoCipherHelper userInfoCipherHelper;
@Value("${client.redirect.domain}")
private String oauthRedirectURL;
private final OauthUserInfoFacade oauthUserInfoFacade;

@Override
Expand All @@ -30,12 +36,20 @@ public void onAuthenticationSuccess(HttpServletRequest request, HttpServletRespo

@Override
public void onAuthenticationSuccess(HttpServletRequest request, HttpServletResponse response,
Authentication authentication) throws IOException {
Authentication authentication) {
DefaultOAuth2User defaultOAuth2User = (DefaultOAuth2User) authentication.getPrincipal();
SocialLoginRequestCommand command = oauthUserInfoFacade.getCommand(defaultOAuth2User);
JsonBinderUtil.setResponseWithJson(response, 200, command);
try {
response.sendRedirect(responseWithEncodedURL(oauthRedirectURL, command));
} catch (Exception e) {
throw new SocialAuthException("암호화를 진행할 수 없습니다.");
}
}

private String responseWithEncodedURL(String oauthRedirectURL, SocialLoginRequestCommand command)
throws Exception {
return userInfoCipherHelper.encrpyt(oauthRedirectURL, command);
}


}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -40,11 +40,16 @@ private SocialLoginRequestCommand getKakaoDto(DefaultOAuth2User oAuth2User) {
String email = kakaoAccount.get("email");
String phoneNumber = kakaoAccount.get("phone_number");
String nickname = properties.get("nickname");
return create(id, email, phoneNumber, nickname);

}

private SocialLoginRequestCommand create(String id, String email, String phoneNumber,
String nickname) {
return SocialLoginRequestCommand.builder().email(email).nickname(nickname)
.phoneNumber(OauthInfoConvertor.convertInternationalPhoneNumberToDomestic(phoneNumber))
.socialId(AuthId.builder().value(Long.valueOf(id)).build()).build();
}



}
14 changes: 12 additions & 2 deletions src/main/resources/application-local.yml
Original file line number Diff line number Diff line change
Expand Up @@ -28,7 +28,7 @@ spring:
client-id: 7f313aaa30b302cd7ae2b48cf2d2b7cd
client-secret: Wl5VDUbX9KsRymQW2S4MhoPvAPqdD7kC
client-authentication-method: client_secret_post
redirect-uri: http://localhost:9000/oauth/authorize
redirect-uri: http://localhost:8000/api/auth/oauth2/authorization/kakao
authorization-grant-type: authorization_code
admin-key: ffc238f9c4e55c2fa85f551f882eda68
client-name: kakao
Expand Down Expand Up @@ -86,4 +86,14 @@ management:
exposure:
include:
- "refresh"
- "bus-refresh"
- "bus-refresh"

client:
redirect:
domain: http://localhost:3000/login/oauth

user:
info:
secret: user-secret-user-secret-user-secret-user-secret-user-secret


Loading
Loading