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

refactor : 인가 코드 요청 및 토큰 요청 로직 #147

Merged
merged 9 commits into from
Apr 28, 2024
Original file line number Diff line number Diff line change
Expand Up @@ -7,11 +7,10 @@
import jakarta.validation.Valid;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import ohsoontaxi.backend.domain.credential.presentation.dto.request.OauthCodeRequest;
import ohsoontaxi.backend.domain.credential.presentation.dto.request.RegisterRequest;
import ohsoontaxi.backend.domain.credential.presentation.dto.request.TokenRefreshRequest;
import ohsoontaxi.backend.domain.credential.presentation.dto.response.AccessTokenDto;
import ohsoontaxi.backend.domain.credential.presentation.dto.response.AuthTokensResponse;
import ohsoontaxi.backend.domain.credential.presentation.dto.response.AvailableRegisterResponse;
import ohsoontaxi.backend.domain.credential.presentation.dto.response.*;
import ohsoontaxi.backend.domain.credential.service.CredentialService;
import ohsoontaxi.backend.domain.credential.service.OauthProvider;
import org.springframework.web.bind.annotation.*;
Expand All @@ -34,6 +33,30 @@ public AccessTokenDto login(@PathVariable("userId") Long userId){
return result;
}

@Operation(summary = "카카오 인가 코드 받기 (서버 테스트용)")
@GetMapping("/oauth/link/kakao")
public OauthLoginLinkResponse getKakaoOauthLink() {
return new OauthLoginLinkResponse(credentialService.getOauthLink(OauthProvider.KAKAO));
}

@Operation(summary = "카카오 accessToken, idToken 받기 (서버 테스트용)")
@GetMapping("/oauth/kakao")
public AfterOauthResponse kakaoAuth(OauthCodeRequest oauthCodeRequest) {
return credentialService.getTokenToCode(OauthProvider.KAKAO, oauthCodeRequest.getCode());
}

@Operation(summary = "구글 인가 코드 받기 (서버 테스트용)")
@GetMapping("/oauth/link/google")
public OauthLoginLinkResponse getGoogleOauthLink() {
return new OauthLoginLinkResponse(credentialService.getOauthLink(OauthProvider.GOOGLE));
}

@Operation(summary = "구글 accessToken, idToken 받기 (서버 테스트용)")
@GetMapping("/oauth/google")
public AfterOauthResponse googleAuth(OauthCodeRequest oauthCodeRequest) {
return credentialService.getTokenToCode(OauthProvider.GOOGLE, oauthCodeRequest.getCode());
}

@Operation(summary = "Id Token 검증")
@GetMapping("/oauth/valid/register")
@Parameters({
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,10 @@
package ohsoontaxi.backend.domain.credential.presentation.dto.request;

import lombok.AllArgsConstructor;
import lombok.Getter;

@Getter
@AllArgsConstructor
public class OauthCodeRequest {
private String code;
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,11 @@
package ohsoontaxi.backend.domain.credential.presentation.dto.response;

import lombok.AllArgsConstructor;
import lombok.Getter;

@Getter
@AllArgsConstructor
public class AfterOauthResponse {
private String idToken;
private String accessToken;
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,11 @@
package ohsoontaxi.backend.domain.credential.presentation.dto.response;

import lombok.AllArgsConstructor;
import lombok.Getter;

@Getter
@AllArgsConstructor
public class OauthLoginLinkResponse {

private String link;
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,11 @@
package ohsoontaxi.backend.domain.credential.presentation.dto.response;

import lombok.Builder;
import lombok.Getter;

@Getter
@Builder
public class OauthTokenInfoDto {
private String idToken;
private String accessToken;
}
Original file line number Diff line number Diff line change
Expand Up @@ -6,9 +6,7 @@
import ohsoontaxi.backend.domain.credential.domain.repository.RefreshTokenRedisEntityRepository;
import ohsoontaxi.backend.domain.credential.exception.RefreshTokenExpiredException;
import ohsoontaxi.backend.domain.credential.presentation.dto.request.RegisterRequest;
import ohsoontaxi.backend.domain.credential.presentation.dto.response.AccessTokenDto;
import ohsoontaxi.backend.domain.credential.presentation.dto.response.AuthTokensResponse;
import ohsoontaxi.backend.domain.credential.presentation.dto.response.AvailableRegisterResponse;
import ohsoontaxi.backend.domain.credential.presentation.dto.response.*;
import ohsoontaxi.backend.domain.email.domain.EmailMessage;
import ohsoontaxi.backend.domain.email.exception.NotEmailApprovedException;
import ohsoontaxi.backend.domain.email.service.EmailUtils;
Expand Down Expand Up @@ -48,25 +46,15 @@ public AccessTokenDto login(Long userId){
return new AccessTokenDto(accessToken);
}

private String generateRefreshToken(Long userId) {
String refreshToken = jwtTokenProvider.generateRefreshToken(userId);
Long tokenExpiredAt = jwtTokenProvider.getRefreshTokenTTlSecond();
RefreshTokenRedisEntity build =
RefreshTokenRedisEntity.builder()
.id(userId.toString())
.ttl(tokenExpiredAt)
.refreshToken(refreshToken)
.build();
refreshTokenRedisEntityRepository.save(build);
return refreshToken;
public String getOauthLink(OauthProvider oauthProvider) {
OauthStrategy oauthStrategy = oauthFactory.getOauthstrategy(oauthProvider);
return oauthStrategy.getOauthLink();
}

private Boolean checkUserCanRegister(
OIDCDecodePayload oidcDecodePayload, OauthProvider oauthProvider) {
Optional<User> user =
userRepository.findByOauthIdAndOauthProvider(
oidcDecodePayload.getSub(), oauthProvider.getValue());
return user.isEmpty();
public AfterOauthResponse getTokenToCode(OauthProvider oauthProvider, String code) {
OauthStrategy oauthStrategy = oauthFactory.getOauthstrategy(oauthProvider);
OauthTokenInfoDto oauthToken = oauthStrategy.getOauthToken(code);
return new AfterOauthResponse(oauthToken.getIdToken(),oauthToken.getAccessToken());
}

public AvailableRegisterResponse getUserAvailableRegister(String token, OauthProvider oauthProvider) throws NoSuchAlgorithmException, InvalidKeySpecException {
Expand Down Expand Up @@ -174,5 +162,25 @@ private String checkNullEmail(String email, String schEmail) {
return email != null ? email : schEmail;
}

private String generateRefreshToken(Long userId) {
String refreshToken = jwtTokenProvider.generateRefreshToken(userId);
Long tokenExpiredAt = jwtTokenProvider.getRefreshTokenTTlSecond();
RefreshTokenRedisEntity build =
RefreshTokenRedisEntity.builder()
.id(userId.toString())
.ttl(tokenExpiredAt)
.refreshToken(refreshToken)
.build();
refreshTokenRedisEntityRepository.save(build);
return refreshToken;
}

private Boolean checkUserCanRegister(
OIDCDecodePayload oidcDecodePayload, OauthProvider oauthProvider) {
Optional<User> user =
userRepository.findByOauthIdAndOauthProvider(
oidcDecodePayload.getSub(), oauthProvider.getValue());
return user.isEmpty();
}
}

Original file line number Diff line number Diff line change
@@ -1,11 +1,17 @@
package ohsoontaxi.backend.domain.credential.service;

import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import ohsoontaxi.backend.domain.credential.presentation.dto.response.OauthTokenInfoDto;
import ohsoontaxi.backend.global.api.client.GoogleAuthClient;
import ohsoontaxi.backend.global.api.dto.OIDCPublicKeysResponse;
import ohsoontaxi.backend.global.api.dto.OauthTokenResponse;
import ohsoontaxi.backend.global.property.OauthProperties;
import org.springframework.stereotype.Component;

import java.net.URLDecoder;
import java.nio.charset.StandardCharsets;

@AllArgsConstructor
@Component("GOOGLE")
public class GoogleOauthStrategy implements OauthStrategy{
Expand All @@ -14,12 +20,42 @@ public class GoogleOauthStrategy implements OauthStrategy{
private final GoogleAuthClient googleAuthClient;
private final OauthOIDCProvider oauthOIDCProvider;
private static final String ISSUER = "https://accounts.google.com";
private static final String QUERY_STRING =
"/o/oauth2/v2/auth?response_type=code&client_id=%s&scope=%s&redirect_uri=%s";
private static final String scope = "https://www.googleapis.com/auth/userinfo.email";

@Override
public String getOauthLink() {
return oauthProperties.getGoogleBaseUrl()
+ String.format(
QUERY_STRING,
oauthProperties.getGoogleAppId(),
scope,
oauthProperties.getGoogleRedirectUrl());
}

@Override
public OauthTokenInfoDto getOauthToken(String code) {
String decodedCode = URLDecoder.decode(code, StandardCharsets.UTF_8);
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

URLDecoder.decode를 사용하신 이유가 어떻게 되나요?

Copy link
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

인가 코드는 일회성으로 바로 보내게 되면 보안상 위험할 수 있습니다. 그래서 인가 코드를 한번 디코딩하여 보안성을 높였습니다.


OauthTokenResponse oauthTokenResponse = googleAuthClient
.googleAuth(
decodedCode,
oauthProperties.getGoogleAppId(),
oauthProperties.getGoogleClientSecret(),
oauthProperties.getGoogleRedirectUrl());

return OauthTokenInfoDto.builder()
.idToken(oauthTokenResponse.getIdToken())
.accessToken(oauthTokenResponse.getAccessToken())
.build();
}

@Override
public OIDCDecodePayload getOIDCDecodePayload(String token) {
OIDCPublicKeysResponse oidcPublicKeysResponse = googleAuthClient.getGoogleOIDCOpenKeys();
return oauthOIDCProvider.getPayloadFromIdToken(
token, ISSUER, oauthProperties.getGoogleAppId(), oidcPublicKeysResponse);
}

}

Original file line number Diff line number Diff line change
Expand Up @@ -2,8 +2,10 @@

import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import ohsoontaxi.backend.domain.credential.presentation.dto.response.OauthTokenInfoDto;
import ohsoontaxi.backend.global.api.client.KakaoOauthClient;
import ohsoontaxi.backend.global.api.dto.OIDCPublicKeysResponse;
import ohsoontaxi.backend.global.api.dto.OauthTokenResponse;
import ohsoontaxi.backend.global.property.OauthProperties;
import org.springframework.stereotype.Component;

Expand All @@ -16,10 +18,34 @@ public class KaKaoOauthStrategy implements OauthStrategy{
private final KakaoOauthClient kakaoOauthClient;
private final OauthOIDCProvider oauthOIDCProvider;
private static final String ISSUER = "https://kauth.kakao.com";
private static final String QUERY_STRING = "/oauth/authorize?client_id=%s&redirect_uri=%s&response_type=code";

@Override
public String getOauthLink() {
return oauthProperties.getKakaoBaseUrl()
+ String.format(
QUERY_STRING,
oauthProperties.getKakaoClientId(),
oauthProperties.getKakaoRedirectUrl());
}

@Override
public OauthTokenInfoDto getOauthToken(String code) {
OauthTokenResponse oauthTokenResponse = kakaoOauthClient
.kakaoAuth(
oauthProperties.getKakaoClientId(),
oauthProperties.getKakaoRedirectUrl(),
code);
return OauthTokenInfoDto.builder()
.idToken(oauthTokenResponse.getIdToken())
.accessToken(oauthTokenResponse.getAccessToken())
.build();
}

@Override
public OIDCDecodePayload getOIDCDecodePayload(String token) {
OIDCPublicKeysResponse oidcPublicKeysResponse = kakaoOauthClient.getKakaoOIDCOpenKeys(); //@feign을 이용해서 공개키 배열 가져오기(keys 리스트)
OIDCPublicKeysResponse oidcPublicKeysResponse = kakaoOauthClient.getKakaoOIDCOpenKeys();
return oauthOIDCProvider.getPayloadFromIdToken(
token, ISSUER, oauthProperties.getKakaoAppId(), oidcPublicKeysResponse); //id token 검증
token, ISSUER, oauthProperties.getKakaoAppId(), oidcPublicKeysResponse);
}
}
Original file line number Diff line number Diff line change
@@ -1,8 +1,14 @@
package ohsoontaxi.backend.domain.credential.service;

import ohsoontaxi.backend.domain.credential.presentation.dto.response.OauthTokenInfoDto;

import java.security.NoSuchAlgorithmException;
import java.security.spec.InvalidKeySpecException;

public interface OauthStrategy {
String getOauthLink();

OauthTokenInfoDto getOauthToken(String code);

OIDCDecodePayload getOIDCDecodePayload(String token) throws NoSuchAlgorithmException, InvalidKeySpecException;
}
Original file line number Diff line number Diff line change
@@ -1,15 +1,28 @@
package ohsoontaxi.backend.global.api.client;

import feign.Headers;
import ohsoontaxi.backend.global.api.dto.OIDCPublicKeysResponse;
import ohsoontaxi.backend.global.api.dto.OauthTokenResponse;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.cloud.openfeign.FeignClient;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;

@FeignClient(name = "GoogleAuthClient", url = "https://www.googleapis.com/oauth2")
public interface GoogleAuthClient {

@Cacheable(cacheNames = "GoogleOICD", cacheManager = "oidcCacheManager")
@GetMapping("/v3/certs")
OIDCPublicKeysResponse getGoogleOIDCOpenKeys();

@Headers("Content-type: application/x-www-form-urlencoded;charset=utf-8")
@PostMapping(
"/v4/token?code={CODE}&client_id={CLIENT_ID}&client_secret={CLIENT_SECRET}&redirect_uri={REDIRECT_URI}&grant_type=authorization_code")
OauthTokenResponse googleAuth(
@PathVariable("CODE") String code,
@PathVariable("CLIENT_ID") String clientId,
@PathVariable("CLIENT_SECRET") String client_secret,
@PathVariable("REDIRECT_URI") String redirectUri);
}

Original file line number Diff line number Diff line change
@@ -1,14 +1,26 @@
package ohsoontaxi.backend.global.api.client;

import feign.Headers;
import ohsoontaxi.backend.global.api.dto.OIDCPublicKeysResponse;
import ohsoontaxi.backend.global.api.dto.OauthTokenResponse;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.cloud.openfeign.FeignClient;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;

@FeignClient(name = "KakaoAuthClient", url = "https://kauth.kakao.com")
public interface KakaoOauthClient {

@Cacheable(cacheNames = "KakaoOICD", cacheManager = "oidcCacheManager")
@GetMapping("/.well-known/jwks.json")
OIDCPublicKeysResponse getKakaoOIDCOpenKeys();

@Headers("Content-type: application/x-www-form-urlencoded;charset=utf-8")
@PostMapping(
"/oauth/token?grant_type=authorization_code&client_id={CLIENT_ID}&redirect_uri={REDIRECT_URI}&code={CODE}")
OauthTokenResponse kakaoAuth(
@PathVariable("CLIENT_ID") String clientId,
@PathVariable("REDIRECT_URI") String redirectUri,
@PathVariable("CODE") String code);
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,15 @@
package ohsoontaxi.backend.global.api.dto;

import com.fasterxml.jackson.annotation.JsonProperty;
import lombok.Getter;
import lombok.NoArgsConstructor;

@Getter
@NoArgsConstructor
public class OauthTokenResponse {
@JsonProperty("id_token")
private String idToken;

@JsonProperty("access_token")
private String accessToken;
}
6 changes: 6 additions & 0 deletions src/main/resources/application.yml
Original file line number Diff line number Diff line change
Expand Up @@ -56,9 +56,15 @@ auth:
oauth:
kakao:
app-id: ${KAKAO_APP_ID}
client-id: ${KAKAO_CLIENT_ID}
redirect-url: ${KAKAO_REDIRECT_URL}
base-url: ${KAKAO_BASE_URL}

google:
app-id: ${GOOGLE_APP_ID}
redirect-url: ${GOOGLE_REDIRECT_URL}
base-url: ${GOOGLE_BASE_URL}
client-secret : ${GOOGLE_CLIENT_SECRET}

fcm:
value: firebase_service_key.json
Expand Down
Loading