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

YEL-42 [feat] 소셜 로그인 API 및 Authorization 구현 #34

Merged
merged 4 commits into from
Jul 12, 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
7 changes: 5 additions & 2 deletions build.gradle
Original file line number Diff line number Diff line change
Expand Up @@ -50,17 +50,20 @@ dependencies {
implementation group: 'io.jsonwebtoken', name: 'jjwt-impl', version: '0.11.2'
implementation group: 'io.jsonwebtoken', name: 'jjwt-jackson', version: '0.11.2'

// S3 AWS
// implementation group: 'org.springframework.cloud', name: 'spring-cloud-starter-aws', version: '2.2.6.RELEASE'

// Swagger
implementation 'org.springdoc:springdoc-openapi-ui:1.6.11'

//
implementation 'com.github.gavlyukovskiy:p6spy-spring-boot-starter:1.5.7'

// Http
implementation 'org.springframework.boot:spring-boot-starter-webflux'

// Security
implementation 'org.springframework.boot:spring-boot-starter-security'
implementation 'io.netty:netty-resolver-dns-native-macos:4.1.79.Final:osx-aarch_64'


// QueryDSL
implementation "com.querydsl:querydsl-jpa:${queryDslVersion}"
Expand Down
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();

Comment on lines +22 to +24
Copy link
Member

Choose a reason for hiding this comment

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

숫자는 static으로 선언한거 갖고오는게 어떤가요?

@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();
}
}
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
Copy link
Member

Choose a reason for hiding this comment

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

이렇게 되면 코드 순서대로 filter가 순서를 이루게 되나요?

Copy link
Contributor Author

Choose a reason for hiding this comment

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

넴 맞슴다

.build();
}
}
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);
}
}
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
) {

}
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();
}
}
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
) {

}
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();
}
}
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())
);
}
}
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());
}
}
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());
}
}
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());
}
}
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());
}
}
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());
}
}
Loading