-
Notifications
You must be signed in to change notification settings - Fork 1
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
YEL-42 [feat] 소셜 로그인 API 및 Authorization 구현 #34
Merged
Merged
Changes from all commits
Commits
Show all changes
4 commits
Select commit
Hold shift + click to select a range
File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
99 changes: 99 additions & 0 deletions
99
src/main/java/com/yello/server/domain/authorization/JwtTokenProvider.java
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,99 @@ | ||
package com.yello.server.domain.authorization; | ||
|
||
import static io.jsonwebtoken.SignatureAlgorithm.HS256; | ||
import static java.time.Duration.ofDays; | ||
import static java.time.Duration.ofHours; | ||
|
||
import com.yello.server.domain.authorization.dto.ServiceTokenVO; | ||
import io.jsonwebtoken.Claims; | ||
import io.jsonwebtoken.Header; | ||
import io.jsonwebtoken.Jwts; | ||
import java.util.Date; | ||
import lombok.RequiredArgsConstructor; | ||
import lombok.extern.log4j.Log4j2; | ||
import org.springframework.beans.factory.annotation.Value; | ||
import org.springframework.stereotype.Component; | ||
|
||
@Log4j2 | ||
@Component | ||
@RequiredArgsConstructor | ||
public class JwtTokenProvider { | ||
|
||
private static final Long accessTokenValidTime = ofHours(4).toMillis(); | ||
private static final Long refreshTokenValidTime = ofDays(14).toMillis(); | ||
|
||
@Value("${spring.jwt.secret}") | ||
private static String secretKey; | ||
|
||
public Long getUserId(String token, String secretKey) { | ||
return Jwts.parser() | ||
.setSigningKey(secretKey) | ||
.parseClaimsJws(token) | ||
.getBody() | ||
.get("userId", Long.class); | ||
} | ||
|
||
public boolean isExpired(String token, String secretKey) { | ||
Claims claims = Jwts.parser() | ||
.setSigningKey(secretKey) | ||
.parseClaimsJws(token) | ||
.getBody(); | ||
return false; | ||
} | ||
|
||
public boolean isRefreshToken(String token, String secretKey) { | ||
Header header = Jwts.parser() | ||
.setSigningKey(secretKey) | ||
.parseClaimsJws(token) | ||
.getHeader(); | ||
|
||
if ("refreshtoken".equals(header.get("type").toString())) { | ||
return true; | ||
} | ||
return false; | ||
} | ||
|
||
// access 토큰 확인 | ||
public boolean isAccessToken(String token, String secretKey) { | ||
Header header = Jwts.parser() | ||
.setSigningKey(secretKey) | ||
.parseClaimsJws(token) | ||
.getHeader(); | ||
|
||
if ("accesstoken".equals(header.get("type").toString())) { | ||
return true; | ||
} | ||
return false; | ||
} | ||
|
||
// access 토큰 생성 | ||
public String createAccessToken(Long userId, String uuid) { | ||
return createJwt(userId, uuid, accessTokenValidTime); | ||
} | ||
|
||
// refresh 토큰 생성 | ||
public String createRefreshToken(Long userId, String uuid) { | ||
return createJwt(userId, uuid, refreshTokenValidTime); | ||
} | ||
|
||
// access, refresh 토큰 생성 | ||
public ServiceTokenVO createServiceToken(Long userId, String uuid) { | ||
return ServiceTokenVO.of( | ||
createAccessToken(userId, uuid), | ||
createRefreshToken(userId, uuid) | ||
); | ||
} | ||
|
||
public String createJwt(Long userId, String uuid, Long tokenValidTime) { | ||
Claims claims = Jwts.claims() | ||
.setSubject(uuid) | ||
.setId(String.valueOf(userId)); | ||
|
||
return Jwts.builder() | ||
.setClaims(claims) | ||
.setIssuedAt(new Date(System.currentTimeMillis())) | ||
.setExpiration(new Date(System.currentTimeMillis() + tokenValidTime)) | ||
.signWith(HS256, secretKey) | ||
.compact(); | ||
} | ||
} |
51 changes: 51 additions & 0 deletions
51
src/main/java/com/yello/server/domain/authorization/configuration/SecurityConfiguration.java
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,51 @@ | ||
package com.yello.server.domain.authorization.configuration; | ||
|
||
import static org.springframework.http.HttpMethod.GET; | ||
import static org.springframework.security.config.http.SessionCreationPolicy.STATELESS; | ||
|
||
import com.yello.server.domain.authorization.JwtTokenProvider; | ||
import com.yello.server.domain.authorization.exception.CustomAuthenticationEntryPoint; | ||
import com.yello.server.domain.authorization.filter.JwtExceptionFilter; | ||
import com.yello.server.domain.authorization.filter.JwtFilter; | ||
import com.yello.server.global.exception.ExceptionHandlerFilter; | ||
import lombok.RequiredArgsConstructor; | ||
import org.springframework.beans.factory.annotation.Value; | ||
import org.springframework.context.annotation.Bean; | ||
import org.springframework.context.annotation.Configuration; | ||
import org.springframework.security.config.annotation.web.builders.HttpSecurity; | ||
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity; | ||
import org.springframework.security.web.SecurityFilterChain; | ||
import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter; | ||
|
||
@Configuration | ||
@EnableWebSecurity | ||
@RequiredArgsConstructor | ||
public class SecurityConfiguration { | ||
|
||
private final CustomAuthenticationEntryPoint customAuthenticationEntryPoint; | ||
@Value("${spring.jwt.secret}") | ||
private String secretKey; | ||
|
||
@Bean | ||
public SecurityFilterChain securityFilterChain(HttpSecurity httpSecurity) throws Exception { | ||
return httpSecurity | ||
.httpBasic().disable() | ||
.csrf().disable() | ||
.cors().and() | ||
.authorizeRequests() | ||
.antMatchers("/api/v1/auth/oauth").permitAll() | ||
.antMatchers(GET, "/api/*").authenticated() | ||
.and() | ||
.sessionManagement() | ||
.sessionCreationPolicy(STATELESS) // jwt 사용하는 경우 사용 | ||
.and() | ||
.exceptionHandling() | ||
.authenticationEntryPoint(customAuthenticationEntryPoint) | ||
.and() | ||
.addFilterBefore(new ExceptionHandlerFilter(), UsernamePasswordAuthenticationFilter.class) | ||
.addFilterBefore(new JwtFilter(new JwtTokenProvider(), secretKey), | ||
UsernamePasswordAuthenticationFilter.class) | ||
.addFilterBefore(new JwtExceptionFilter(), JwtFilter.class) | ||
Comment on lines
+45
to
+48
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. 이렇게 되면 코드 순서대로 filter가 순서를 이루게 되나요? There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. 넴 맞슴다 |
||
.build(); | ||
} | ||
} |
36 changes: 36 additions & 0 deletions
36
src/main/java/com/yello/server/domain/authorization/controller/AuthController.java
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,36 @@ | ||
package com.yello.server.domain.authorization.controller; | ||
|
||
import com.yello.server.domain.authorization.dto.request.OAuthRequest; | ||
import com.yello.server.domain.authorization.dto.response.OAuthResponse; | ||
import com.yello.server.domain.authorization.service.AuthService; | ||
import com.yello.server.global.common.SuccessCode; | ||
import com.yello.server.global.common.dto.BaseResponse; | ||
import io.swagger.v3.oas.annotations.Operation; | ||
import io.swagger.v3.oas.annotations.media.Content; | ||
import io.swagger.v3.oas.annotations.media.Schema; | ||
import io.swagger.v3.oas.annotations.responses.ApiResponse; | ||
import lombok.RequiredArgsConstructor; | ||
import lombok.val; | ||
import org.springframework.web.bind.annotation.PostMapping; | ||
import org.springframework.web.bind.annotation.RequestBody; | ||
import org.springframework.web.bind.annotation.RequestMapping; | ||
import org.springframework.web.bind.annotation.RestController; | ||
|
||
@RestController | ||
@RequiredArgsConstructor | ||
@RequestMapping("/api/v1/auth") | ||
public class AuthController { | ||
|
||
private final AuthService authService; | ||
|
||
@Operation(summary = "소셜 로그인 API", responses = { | ||
@ApiResponse( | ||
responseCode = "201", | ||
content = @Content(mediaType = "application/json", schema = @Schema(implementation = OAuthResponse.class))), | ||
}) | ||
@PostMapping("/oauth") | ||
public BaseResponse<OAuthResponse> oauthLogin(@RequestBody OAuthRequest oAuthRequest) { | ||
val data = authService.oauthLogin(oAuthRequest); | ||
return BaseResponse.success(SuccessCode.LOGIN_SUCCESS, data); | ||
} | ||
} |
8 changes: 8 additions & 0 deletions
8
src/main/java/com/yello/server/domain/authorization/dto/KakaoTokenInfo.java
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,8 @@ | ||
package com.yello.server.domain.authorization.dto; | ||
|
||
public record KakaoTokenInfo( | ||
Long id, | ||
Integer expires_in | ||
) { | ||
|
||
} |
17 changes: 17 additions & 0 deletions
17
src/main/java/com/yello/server/domain/authorization/dto/ServiceTokenVO.java
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,17 @@ | ||
package com.yello.server.domain.authorization.dto; | ||
|
||
import lombok.Builder; | ||
|
||
@Builder | ||
public record ServiceTokenVO( | ||
String accessToken, | ||
String refreshToken | ||
) { | ||
|
||
public static ServiceTokenVO of(String accessToken, String refreshToken) { | ||
return ServiceTokenVO.builder() | ||
.accessToken(accessToken) | ||
.refreshToken(refreshToken) | ||
.build(); | ||
} | ||
} |
11 changes: 11 additions & 0 deletions
11
src/main/java/com/yello/server/domain/authorization/dto/request/OAuthRequest.java
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,11 @@ | ||
package com.yello.server.domain.authorization.dto.request; | ||
|
||
import lombok.Builder; | ||
|
||
@Builder | ||
public record OAuthRequest( | ||
String accessToken, | ||
String social | ||
) { | ||
|
||
} |
18 changes: 18 additions & 0 deletions
18
src/main/java/com/yello/server/domain/authorization/dto/response/OAuthResponse.java
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,18 @@ | ||
package com.yello.server.domain.authorization.dto.response; | ||
|
||
import com.yello.server.domain.authorization.dto.ServiceTokenVO; | ||
import lombok.Builder; | ||
|
||
@Builder | ||
public record OAuthResponse( | ||
String accessToken, | ||
String refreshToken | ||
) { | ||
|
||
public static OAuthResponse of(ServiceTokenVO tokens) { | ||
return OAuthResponse.builder() | ||
.accessToken(tokens.accessToken()) | ||
.refreshToken(tokens.refreshToken()) | ||
.build(); | ||
} | ||
} |
38 changes: 38 additions & 0 deletions
38
.../java/com/yello/server/domain/authorization/exception/CustomAuthenticationEntryPoint.java
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,38 @@ | ||
package com.yello.server.domain.authorization.exception; | ||
|
||
import static com.yello.server.global.common.ErrorCode.AUTHENTICATION_ERROR; | ||
import static org.springframework.http.MediaType.APPLICATION_JSON_VALUE; | ||
|
||
import com.fasterxml.jackson.databind.ObjectMapper; | ||
import com.yello.server.global.common.dto.BaseResponse; | ||
import java.io.IOException; | ||
import javax.servlet.ServletException; | ||
import javax.servlet.http.HttpServletRequest; | ||
import javax.servlet.http.HttpServletResponse; | ||
import lombok.extern.log4j.Log4j2; | ||
import org.springframework.security.core.AuthenticationException; | ||
import org.springframework.security.web.AuthenticationEntryPoint; | ||
import org.springframework.stereotype.Component; | ||
|
||
@Log4j2 | ||
@Component | ||
public class CustomAuthenticationEntryPoint implements AuthenticationEntryPoint { | ||
|
||
@Override | ||
public void commence( | ||
HttpServletRequest request, | ||
HttpServletResponse response, | ||
AuthenticationException authException) | ||
throws IOException, ServletException { | ||
ObjectMapper objectMapper = new ObjectMapper(); | ||
log.error("인증에 실패했습니다."); | ||
CustomAuthenticationException exception = new CustomAuthenticationException(AUTHENTICATION_ERROR); | ||
response.setStatus(exception.getHttpStatus()); | ||
response.setContentType(APPLICATION_JSON_VALUE); | ||
response.setCharacterEncoding("UTF-8"); | ||
objectMapper.writeValue( | ||
response.getWriter(), | ||
BaseResponse.error(exception.getError()) | ||
); | ||
} | ||
} |
13 changes: 13 additions & 0 deletions
13
...n/java/com/yello/server/domain/authorization/exception/CustomAuthenticationException.java
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,13 @@ | ||
package com.yello.server.domain.authorization.exception; | ||
|
||
import com.yello.server.global.common.ErrorCode; | ||
import com.yello.server.global.exception.CustomException; | ||
import lombok.Getter; | ||
|
||
@Getter | ||
public class CustomAuthenticationException extends CustomException { | ||
|
||
public CustomAuthenticationException(ErrorCode error) { | ||
super(error, "[CustomAuthenticationException] " + error.getMessage()); | ||
} | ||
} |
13 changes: 13 additions & 0 deletions
13
src/main/java/com/yello/server/domain/authorization/exception/ExpiredTokenException.java
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,13 @@ | ||
package com.yello.server.domain.authorization.exception; | ||
|
||
import com.yello.server.global.common.ErrorCode; | ||
import com.yello.server.global.exception.CustomException; | ||
import lombok.Getter; | ||
|
||
@Getter | ||
public class ExpiredTokenException extends CustomException { | ||
|
||
public ExpiredTokenException(ErrorCode error) { | ||
super(error, "[ExpiredTokenException] " + error.getMessage()); | ||
} | ||
} |
13 changes: 13 additions & 0 deletions
13
src/main/java/com/yello/server/domain/authorization/exception/InvalidTokenException.java
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,13 @@ | ||
package com.yello.server.domain.authorization.exception; | ||
|
||
import com.yello.server.global.common.ErrorCode; | ||
import com.yello.server.global.exception.CustomException; | ||
import lombok.Getter; | ||
|
||
@Getter | ||
public class InvalidTokenException extends CustomException { | ||
|
||
public InvalidTokenException(ErrorCode error) { | ||
super(error, "[InvalidTokenException] " + error.getMessage()); | ||
} | ||
} |
13 changes: 13 additions & 0 deletions
13
src/main/java/com/yello/server/domain/authorization/exception/NotSignedInException.java
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,13 @@ | ||
package com.yello.server.domain.authorization.exception; | ||
|
||
import com.yello.server.global.common.ErrorCode; | ||
import com.yello.server.global.exception.CustomException; | ||
import lombok.Getter; | ||
|
||
@Getter | ||
public class NotSignedInException extends CustomException { | ||
|
||
public NotSignedInException(ErrorCode error) { | ||
super(error, "[NotSignedInException] " + error.getMessage()); | ||
} | ||
} |
13 changes: 13 additions & 0 deletions
13
src/main/java/com/yello/server/domain/authorization/exception/OAuthException.java
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,13 @@ | ||
package com.yello.server.domain.authorization.exception; | ||
|
||
import com.yello.server.global.common.ErrorCode; | ||
import com.yello.server.global.exception.CustomException; | ||
import lombok.Getter; | ||
|
||
@Getter | ||
public class OAuthException extends CustomException { | ||
|
||
public OAuthException(ErrorCode error) { | ||
super(error, "[OAuthException] " + error.getMessage()); | ||
} | ||
} |
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
숫자는 static으로 선언한거 갖고오는게 어떤가요?