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

๐Ÿ”€ :: google oauth2 ๋กœ๊ทธ์ธ #6

Merged
merged 29 commits into from
Oct 12, 2024
Merged
Show file tree
Hide file tree
Changes from 26 commits
Commits
Show all changes
29 commits
Select commit Hold shift + click to select a range
1c3845c
update :: profile nullable true
ta2ye0n Oct 8, 2024
e6a3f19
add :: Oauth2, jwt ์˜์กด์„ฑ ์ถ”๊ฐ€
ta2ye0n Oct 8, 2024
81171ab
add :: Oauth2, jwt ์ถ”๊ฐ€
ta2ye0n Oct 8, 2024
91f94ff
add :: exception
ta2ye0n Oct 8, 2024
87fc2b2
add :: token exceptions
ta2ye0n Oct 8, 2024
91c8125
add :: UserNotFoundException
ta2ye0n Oct 8, 2024
90e8aff
add :: Oauth2 Service
ta2ye0n Oct 8, 2024
cacda95
add :: ExceptionFilter
ta2ye0n Oct 8, 2024
a2ab858
add :: JwtFilter
ta2ye0n Oct 8, 2024
1c37c82
add :: JwtAccessDeniedHandler
ta2ye0n Oct 8, 2024
92ef096
add :: JwtAuthenticationEntryPoint
ta2ye0n Oct 8, 2024
dd11ed4
add :: UserRepository
ta2ye0n Oct 8, 2024
b534bf8
add :: UserRoleRepository
ta2ye0n Oct 8, 2024
82159c3
add :: JwtTokenProvider
ta2ye0n Oct 8, 2024
521d117
add :: AuthDetails, AuthDetailsService
ta2ye0n Oct 8, 2024
6d1c0c5
add :: JwtSecurityConfig
ta2ye0n Oct 8, 2024
2a67fec
add :: SignInService
ta2ye0n Oct 8, 2024
f71bc22
add :: AuthController
ta2ye0n Oct 8, 2024
2164d2e
add :: SecurityConfig
ta2ye0n Oct 8, 2024
66605e0
update :: controller๋ช… ๋ณ€๊ฒฝ
ta2ye0n Oct 9, 2024
396b059
add :: JwtProperties
ta2ye0n Oct 9, 2024
31346bd
update :: Secret ๋ถ„๋ฆฌ
ta2ye0n Oct 9, 2024
c91aae5
update :: redis ํ™˜๊ฒฝ๋ณ€์ˆ˜
ta2ye0n Oct 11, 2024
5094a59
update :: record๋กœ ๋ณ€๊ฒฝ
ta2ye0n Oct 11, 2024
44d4f1c
add :: configuration ์˜์กด์„ฑ
ta2ye0n Oct 11, 2024
438abb9
update :: properties
ta2ye0n Oct 11, 2024
e06e043
update :: record ๋ณ€๊ฒฝ
ta2ye0n Oct 11, 2024
292e005
update :: record ๋ณ€๊ฒฝ
ta2ye0n Oct 11, 2024
3943c76
update :: ParameterizedTypeReference<>
ta2ye0n Oct 11, 2024
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
8 changes: 8 additions & 0 deletions build.gradle
Original file line number Diff line number Diff line change
Expand Up @@ -35,6 +35,14 @@ dependencies {
testImplementation 'org.springframework.boot:spring-boot-starter-test'
testImplementation 'org.springframework.security:spring-security-test'
testRuntimeOnly 'org.junit.platform:junit-platform-launcher'

implementation 'org.springframework.boot:spring-boot-starter-oauth2-client'

implementation 'io.jsonwebtoken:jjwt-api:0.11.5'
implementation 'io.jsonwebtoken:jjwt-impl:0.11.5'
implementation 'io.jsonwebtoken:jjwt-jackson:0.11.5'

annotationProcessor 'org.springframework.boot:spring-boot-configuration-processor'
}

tasks.named('test') {
Expand Down
2 changes: 2 additions & 0 deletions src/main/java/com/gcms/v3/GcmsServerV3Application.java
Original file line number Diff line number Diff line change
Expand Up @@ -2,8 +2,10 @@

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.context.properties.ConfigurationPropertiesScan;

@SpringBootApplication
@ConfigurationPropertiesScan
public class GcmsServerV3Application {

public static void main(String[] args) {
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,10 @@
package com.gcms.v3.domain.auth.exception;

import com.gcms.v3.global.error.BasicException;
import com.gcms.v3.global.error.ErrorCode;

public class UserNotFoundException extends BasicException {
public UserNotFoundException() {
super(ErrorCode.USER_NOT_FOUND);
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,22 @@
package com.gcms.v3.domain.auth.presentation;

import com.gcms.v3.domain.auth.presentation.data.request.SignInRequestDto;
import com.gcms.v3.domain.auth.presentation.data.response.TokenInfoResponseDto;
import com.gcms.v3.domain.auth.service.SignInService;
import lombok.RequiredArgsConstructor;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

@RequiredArgsConstructor
@RestController
@RequestMapping("/v3/auth")
public class AuthController {

private final SignInService signInService;

@PostMapping
public ResponseEntity<TokenInfoResponseDto> signIn (@RequestBody SignInRequestDto signInRequestDto) {
TokenInfoResponseDto res = signInService.execute(signInRequestDto);
return ResponseEntity.ok(res);
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
package com.gcms.v3.domain.auth.presentation.data.request;

public record SignInRequestDto (
String code
){
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,15 @@
package com.gcms.v3.domain.auth.presentation.data.response;

import lombok.Builder;
import lombok.Getter;

import java.time.LocalDateTime;

@Getter
@Builder
public class TokenInfoResponseDto {
private String accessToken;
private String refreshToken;
private LocalDateTime accessTokenExpiresIn;
private LocalDateTime refreshTokenExpiresIn;
}
Copy link

Choose a reason for hiding this comment

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

Dto๋ผ๊ณ  ํ–ˆ์œผ๋‹ˆ Response์—๋„ ๋˜‘๊ฐ™์ด ์ ์šฉํ•ด ์ฃผ์‹œ๋ฉด ๋  ๊ฒƒ ๊ฐ™์•„์š”!

Copy link
Contributor Author

Choose a reason for hiding this comment

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

e06e043

response ๋ถ€๋ถ„์€ ๊นŒ๋จน์—ˆ๋˜๊ฒƒ ๊ฐ™์•„์š” ์ˆ˜์ •ํ–ˆ์Šต๋‹ˆ๋‹ค

Original file line number Diff line number Diff line change
@@ -0,0 +1,8 @@
package com.gcms.v3.domain.auth.service;

import com.gcms.v3.domain.auth.presentation.data.request.SignInRequestDto;
import com.gcms.v3.domain.auth.presentation.data.response.TokenInfoResponseDto;

public interface SignInService {
TokenInfoResponseDto execute(SignInRequestDto signInRequestDto);
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,58 @@
package com.gcms.v3.domain.auth.service.impl;

import com.gcms.v3.domain.auth.presentation.data.request.SignInRequestDto;
import com.gcms.v3.domain.auth.presentation.data.response.TokenInfoResponseDto;
import com.gcms.v3.domain.auth.service.SignInService;
import com.gcms.v3.domain.user.domain.entity.User;
import com.gcms.v3.domain.user.domain.entity.UserRole;
import com.gcms.v3.domain.user.domain.enums.Authority;
import com.gcms.v3.domain.user.domain.repository.UserRepository;
import com.gcms.v3.domain.user.domain.repository.UserRoleRepository;
import com.gcms.v3.global.oauth2.GoogleOAuth2UserInfo;
import com.gcms.v3.global.oauth2.OAuth2Service;
import com.gcms.v3.global.security.jwt.JwtTokenProvider;
import jakarta.transaction.Transactional;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;

@Service
@Transactional(rollbackOn = Exception.class)
@RequiredArgsConstructor
public class SignInServiceImpl implements SignInService {

private final OAuth2Service oAuth2Service;
private final UserRepository userRepository;
private final JwtTokenProvider jwtTokenProvider;
private final UserRoleRepository userRoleRepository;

public TokenInfoResponseDto execute(SignInRequestDto signInRequestDto) {
String accessToken = oAuth2Service.requestAccessToken(signInRequestDto.code());
GoogleOAuth2UserInfo googleOAuth2UserInfo = oAuth2Service.requestUserInfo(accessToken);

User user = userRepository.findByEmail(googleOAuth2UserInfo.getEmail())
.orElseGet(() -> toEntity(googleOAuth2UserInfo));

return jwtTokenProvider.generateToken(user.getEmail());
}

private User toEntity(GoogleOAuth2UserInfo googleOAuth2UserInfo) {
User user = User.builder()
.name(googleOAuth2UserInfo.getName())
.email(googleOAuth2UserInfo.getEmail())
.build();

userRepository.save(user);
saveAuthority(user);
return user;
}

private void saveAuthority(User user) {
UserRole userRole = UserRole.builder()
.user(user)
.authority(Authority.ROLE_STUDENT)
.build();

userRoleRepository.save(userRole);
}

}
Original file line number Diff line number Diff line change
Expand Up @@ -29,6 +29,6 @@ public class User {
@Column(columnDefinition = "VARCHAR(20)", nullable = false)
private String email;

@Column(columnDefinition = "TEXT", nullable = false)
@Column(columnDefinition = "TEXT")
private String profileImg;
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,10 @@
package com.gcms.v3.domain.user.domain.repository;

import com.gcms.v3.domain.user.domain.entity.User;
import org.springframework.data.jpa.repository.JpaRepository;

import java.util.Optional;

public interface UserRepository extends JpaRepository<User, byte[]> {
Optional<User> findByEmail(String email);
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,11 @@
package com.gcms.v3.domain.user.domain.repository;

import com.gcms.v3.domain.user.domain.entity.User;
import com.gcms.v3.domain.user.domain.entity.UserRole;
import org.springframework.data.jpa.repository.JpaRepository;

import java.util.List;

public interface UserRoleRepository extends JpaRepository<UserRole, byte[]> {
List<UserRole> findByUser(User user);
}
10 changes: 10 additions & 0 deletions src/main/java/com/gcms/v3/global/error/BasicException.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,10 @@
package com.gcms.v3.global.error;

import lombok.AllArgsConstructor;
import lombok.Getter;

@AllArgsConstructor
@Getter
public class BasicException extends RuntimeException{
ErrorCode errorCode;
}
21 changes: 21 additions & 0 deletions src/main/java/com/gcms/v3/global/error/ErrorCode.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
package com.gcms.v3.global.error;

import lombok.AllArgsConstructor;
import lombok.Getter;
import org.springframework.http.HttpStatus;


@AllArgsConstructor
@Getter
public enum ErrorCode {

INVALID_AUTH_TOKEN(HttpStatus.UNAUTHORIZED, "๊ถŒํ•œ ์ •๋ณด๊ฐ€ ์—†๋Š” ํ† ํฐ์ž…๋‹ˆ๋‹ค."),
EXPIRED_TOKEN(HttpStatus.UNAUTHORIZED, "๋งŒ๋ฃŒ๋œ ํ† ํฐ์ž…๋‹ˆ๋‹ค."),
INVALID_TOKEN_TYPE(HttpStatus.UNAUTHORIZED, "์œ ํšจํ•˜์ง€ ์•Š์€ ํ† ํฐ ํƒ€์ž…์ž…๋‹ˆ๋‹ค."),
USER_NOT_FOUND(HttpStatus.NOT_FOUND, "ํ•ด๋‹น ์œ ์ €๋ฅผ ์ฐพ์„ ์ˆ˜ ์—†์Šต๋‹ˆ๋‹ค."),

INTERNAL_SERVER_ERROR(HttpStatus.INTERNAL_SERVER_ERROR, "์„œ๋ฒ„ ๋‚ด๋ถ€ ์—๋Ÿฌ");

private final HttpStatus httpStatus;
private final String message;
}
25 changes: 25 additions & 0 deletions src/main/java/com/gcms/v3/global/error/ErrorResponse.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,25 @@
package com.gcms.v3.global.error;

import lombok.AllArgsConstructor;
import lombok.Builder;
import lombok.Getter;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;

@Getter
@Builder
@AllArgsConstructor
public class ErrorResponse {
private HttpStatus status;
private String message;

public static ResponseEntity<ErrorResponse> toResponseEntity(ErrorCode e){
return ResponseEntity
.status(e.getHttpStatus())
.body(ErrorResponse.builder()
.status(e.getHttpStatus())
.message(e.getMessage())
.build()
);
}
}
Copy link

Choose a reason for hiding this comment

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

์—ฌ๊ธฐ๋„์š”

Copy link
Contributor Author

Choose a reason for hiding this comment

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

292e005

์ˆ˜์ •ํ–ˆ์Šต๋‹ˆ๋‹ค

Original file line number Diff line number Diff line change
@@ -0,0 +1,14 @@
package com.gcms.v3.global.error;

import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;

@ControllerAdvice
public class GlobalExceptionHandler {

@ExceptionHandler(BasicException.class)
protected ResponseEntity<ErrorResponse> handleCustomException(BasicException e) {
return ErrorResponse.toResponseEntity(e.getErrorCode());
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,31 @@
package com.gcms.v3.global.oauth2;

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

import java.util.Map;

@Getter
@JsonIgnoreProperties(ignoreUnknown = true)
@NoArgsConstructor
public class GoogleOAuth2UserInfo {

protected Map<String, Object> attributes;

public GoogleOAuth2UserInfo(Map<String, Object> attributes) {
this.attributes = attributes;
}

public String getId() {
return (String) attributes.get("sub");
}

public String getName() {
return (String) attributes.get("name");
}

public String getEmail() {
return (String) attributes.get("email");
}
}
26 changes: 26 additions & 0 deletions src/main/java/com/gcms/v3/global/oauth2/GoogleProperties.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,26 @@
package com.gcms.v3.global.oauth2;

import lombok.Getter;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

@Component
@Getter
public class GoogleProperties {
@Value("${spring.security.oauth2.client.provider.google.token-uri}")
private String tokenUri;

@Value("${spring.security.oauth2.client.registration.google.client-id}")
private String clientId;

@Value("${spring.security.oauth2.client.registration.google.client-secret}")
private String clientSecret;

@Value("${spring.security.oauth2.client.provider.google.user-info-uri}")
private String userInfoUri;

@Value("${spring.security.oauth2.client.registration.google.redirect-uri}")
private String redirectUri;

public static final String GRANT_TYPE = "authorization_code";
}
56 changes: 56 additions & 0 deletions src/main/java/com/gcms/v3/global/oauth2/OAuth2Service.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,56 @@
package com.gcms.v3.global.oauth2;

import lombok.RequiredArgsConstructor;
import org.springframework.http.*;
import org.springframework.stereotype.Service;
import org.springframework.util.LinkedMultiValueMap;
import org.springframework.util.MultiValueMap;
import org.springframework.web.client.RestTemplate;

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

import static com.gcms.v3.global.oauth2.GoogleProperties.GRANT_TYPE;

@Service
@RequiredArgsConstructor
public class OAuth2Service {

private final GoogleProperties config;
private final RestTemplate restTemplate;

public String requestAccessToken(String code) {
String decode = URLDecoder.decode(code, StandardCharsets.UTF_8);

HttpHeaders httpHeaders = new HttpHeaders();
httpHeaders.setContentType(MediaType.APPLICATION_FORM_URLENCODED);

MultiValueMap<String, String> body = new LinkedMultiValueMap<>();
body.add("client_id", config.getClientId());
body.add("client_secret", config.getClientSecret());
body.add("code", decode);
body.add("redirect_uri", config.getRedirectUri());
body.add("grant_type", GRANT_TYPE);

HttpEntity<?> request = new HttpEntity<>(body, httpHeaders);

ResponseEntity<Map> response = restTemplate.postForEntity(config.getTokenUri(), request, Map.class);
Copy link

Choose a reason for hiding this comment

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

์—ฌ๊ธฐ๋„ ๋˜‘๊ฐ™์ด ์ ์šฉํ•ด์ฃผ์‹œ๋ฉด ๋  ๊ฒƒ ๊ฐ™์•„์š”

return (String) response.getBody().get("access_token");
}


public GoogleOAuth2UserInfo requestUserInfo(String accessToken) {
HttpHeaders httpHeaders = new HttpHeaders();
httpHeaders.setContentType(MediaType.APPLICATION_JSON);
httpHeaders.setBearerAuth(accessToken);

MultiValueMap<String, String> body = new LinkedMultiValueMap<>();

HttpEntity<?> request = new HttpEntity<>(body, httpHeaders);

ResponseEntity<Map> response = restTemplate.exchange(config.getUserInfoUri(), HttpMethod.GET, request, Map.class);
Copy link

Choose a reason for hiding this comment

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

RestTemplate์—์„œ ๋ฐ˜ํ™˜๋ฐ›์€ ๊ฐ’์˜ ํƒ€์ž…์„ ์ง€์ •ํ•  ๋•Œ ์ œ๋„ค๋ฆญ์„ ์‚ฌ์šฉํ•˜๋ ค๋ฉด ParameterizedTypeReference<๋ฐ˜ํ™˜๋ฐ›์„ ๊ฐ’ ํƒ€์ž…>() {}๊ณผ ๊ฐ™์ด ์‚ฌ์šฉํ•ด์„œ ์ •ํ™•ํ•œ ํƒ€์ž…์„ ์ง€์ •ํ•  ์ˆ˜ ์žˆ์–ด์š”
์ด ์˜ˆ์‹œ์—์„œ๋Š” Map.class ๋Œ€์‹ ์— new ParameterizedTypeReference<Map<String, String>() {}๋ฅผ ์‚ฌ์šฉํ•˜๋ฉด ๋  ๊ฒƒ ๊ฐ™๋„ค์š”

Copy link
Contributor Author

Choose a reason for hiding this comment

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

3943c76

์ˆ˜์ •ํ–ˆ์–ด์š”


return new GoogleOAuth2UserInfo(response.getBody());
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,13 @@
package com.gcms.v3.global.oauth2.config;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.client.RestTemplate;

@Configuration
public class ClientConfig {
@Bean
public RestTemplate restTemplate() {
return new RestTemplate();
}
}
Loading
Loading