Skip to content
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
30 changes: 22 additions & 8 deletions build.gradle
Original file line number Diff line number Diff line change
Expand Up @@ -24,25 +24,39 @@ repositories {
}

dependencies {

implementation 'org.springframework.boot:spring-boot-starter-data-jpa'
implementation 'org.springframework.boot:spring-boot-starter-web'
implementation 'org.springframework.boot:spring-boot-starter-validation'
implementation 'org.springframework.boot:spring-boot-starter-security'
implementation 'org.springdoc:springdoc-openapi-starter-webmvc-ui:2.2.0'
developmentOnly 'org.springframework.boot:spring-boot-devtools'
compileOnly 'org.projectlombok:lombok'
annotationProcessor 'org.projectlombok:lombok'
testImplementation 'org.springframework.boot:spring-boot-starter-test'
testRuntimeOnly 'org.junit.platform:junit-platform-launcher'

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

// redis
implementation 'org.springframework.boot:spring-boot-starter-data-redis'
implementation 'org.springframework.boot:spring-boot-starter-data-redis-reactive'

// mail
implementation 'org.springframework.boot:spring-boot-starter-mail'

implementation 'org.springdoc:springdoc-openapi-starter-webmvc-ui:2.2.0'
// mysql
implementation 'org.flywaydb:flyway-core'
implementation 'org.flywaydb:flyway-mysql'
compileOnly 'org.projectlombok:lombok'
developmentOnly 'org.springframework.boot:spring-boot-devtools'
runtimeOnly 'com.mysql:mysql-connector-j'
annotationProcessor 'org.projectlombok:lombok'
testImplementation 'org.springframework.boot:spring-boot-starter-test'
testRuntimeOnly 'org.junit.platform:junit-platform-launcher'

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

// aws
implementation platform('software.amazon.awssdk:bom:2.20.0')
implementation 'software.amazon.awssdk:s3'
implementation 'software.amazon.awssdk:sts'
Expand Down
25 changes: 23 additions & 2 deletions docker-compose/docker-compose.local.yml
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,7 @@ services:
- database
ports:
- ${SPRING_PORT}:${SPRING_PORT}
restart: always
restart: "always"
networks:
- mosu-bridge

Expand All @@ -28,12 +28,33 @@ services:
- ${DB_PORT}
ports:
- ${DB_PORT}:${DB_PORT}
restart: no
restart: "no"
volumes:
- mosu-database:/var/lib/mysql
networks:
- mosu-bridge

velkey:
image: ghcr.io/valkey-io/valkey:7.2
container_name: mosu-velkey
command: [ "valkey-server", "--port", "${VELKEY_PORT}", "--requirepass","${REDIS_PASSWORD}"]
ports:
- ${VELKEY_PORT}:${VELKEY_PORT}
networks:
- mosu-bridge

redis-exporter:
image: oliver006/redis_exporter:v1.58.0
container_name: mosu-redis-exporter
environment:
REDIS_ADDR: redis://velkey:${VELKEY_PORT}
ports:
- ${REDIS_EXPORTER}:${REDIS_EXPORTER}
depends_on:
- velkey
networks:
- mosu-bridge

volumes:
mosu-database:

Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,19 @@
package life.mosu.mosuserver.applicaiton.auth;

import life.mosu.mosuserver.domain.user.UserJpaRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

@Service
public class AccessTokenService extends JwtTokenService {

@Autowired
public AccessTokenService(
@Value("${jwt.access-token.expire-time}") final Long expireTime,
@Value("${jwt.secret}") final String secretKey,
final UserJpaRepository userRepositoy
) {
super(expireTime, secretKey, "Access", "Authorization", userRepositoy);
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,37 @@
package life.mosu.mosuserver.applicaiton.auth;

import jakarta.servlet.http.HttpServletRequest;
import life.mosu.mosuserver.domain.user.UserJpaEntity;
import life.mosu.mosuserver.presentation.auth.dto.Token;
import lombok.RequiredArgsConstructor;
import org.springframework.security.core.Authentication;
import org.springframework.stereotype.Component;

@Component
@RequiredArgsConstructor
public class AuthTokenManager {

private final AccessTokenService accessTokenService;
private final RefreshTokenService refreshTokenService;

public Token generateAuthToken(final UserJpaEntity user) {
final String accessToken = accessTokenService.generateJwtToken(user);
final String refreshToken = refreshTokenService.generateJwtToken(user);

refreshTokenService.cacheRefreshToken(user.getId(), refreshToken);

return Token.of(JwtTokenService.BEARER_TYPE, accessToken, refreshToken);
}

public Token reissueAccessToken(final HttpServletRequest servletRequest) {
final String refreshTokenString = refreshTokenService.resolveToken(servletRequest);

final Authentication authentication = refreshTokenService.getAuthentication(refreshTokenString);
final PrincipalDetails principalDetails = (PrincipalDetails) authentication.getPrincipal();
final UserJpaEntity user = principalDetails.user();

refreshTokenService.deleteRefreshToken(user.getId());

return generateAuthToken(user);
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,146 @@
package life.mosu.mosuserver.applicaiton.auth;

import io.jsonwebtoken.*;
import io.jsonwebtoken.io.Decoders;
import io.jsonwebtoken.security.Keys;
import jakarta.servlet.http.HttpServletRequest;
import life.mosu.mosuserver.domain.user.OAuthUserJpaEntity;
import life.mosu.mosuserver.domain.user.UserJpaEntity;
import life.mosu.mosuserver.domain.user.UserJpaRepository;
import life.mosu.mosuserver.global.exception.CustomRuntimeException;
import life.mosu.mosuserver.global.exception.ErrorCode;
import lombok.extern.slf4j.Slf4j;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;

import java.security.Key;
import java.util.Date;

@Slf4j
public abstract class JwtTokenService {

protected static final String TOKEN_TYPE_KEY = "type";
protected static final String BEARER_TYPE = "Bearer";

protected final Long expireTime;
protected final Key key;
protected final String tokenType;
protected final String header;
protected final UserJpaRepository userRepository;

protected JwtTokenService(
final Long expireTime,
final String secretKey,
final String tokenType,
final String header,
final UserJpaRepository userJpaRepository
) {
this.expireTime = expireTime;
this.key = Keys.hmacShaKeyFor(Decoders.BASE64.decode(secretKey));
this.tokenType = tokenType;
this.header = header;
this.userRepository = userJpaRepository;
}

/**
* JWT 토큰을 생성한다.
*
* @param user 토큰을 생성할 회원
* @return 생성된 토큰
*/
public String generateJwtToken(final UserJpaEntity user) {
final long now = System.currentTimeMillis();
final Date expireTime = new Date(now + this.expireTime);

return Jwts.builder()
.setSubject(user.getLoginId())
.claim(TOKEN_TYPE_KEY, tokenType)
.setExpiration(expireTime)
.signWith(key, SignatureAlgorithm.HS256)
.compact();
}

/**
* JWT 토큰을 생성한다.
*
* @param user 토큰을 생성할 회원
* @return 생성된 토큰
*/
public String generateAccessToken(final OAuthUserJpaEntity user) {
final long now = System.currentTimeMillis();
final Date expireTime = new Date(now + this.expireTime);

return Jwts.builder()
.setSubject(user.getEmail())
.claim(TOKEN_TYPE_KEY, tokenType)
.setExpiration(expireTime)
.signWith(key, SignatureAlgorithm.HS256)
.compact();
}
Comment on lines +51 to +79
Copy link
Contributor

Choose a reason for hiding this comment

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

이 부분을 하나의 메소드로 접근하는데 인자라인으로 초기화 되는 경우를 구분하여 반복코드를 줄일 수 있을거 같아요!
JwtToken이라는 클래스 네이밍에서 AccessToken의 형태가 들어가면, 현재 구체적으로 분리되어있는 형식에서 좋지 않을 수도 있어요!

public interface JwtSubject {
    String getSubjectIdentifier();
}

라고 공통 인터페이스를 만들어서
User와 OAuthUser 에 implements 하고, 해당 부분에서 넘겨주는 형태로 구성하고 인자는 JwtSubject 이걸로 받으면 어떨까라는 생각이 들어요!


/**
* JWT 토큰을 파싱하여 Authentication 객체를 생성한다.
*
* @param token 토큰
* @return 생성된 Authentication
*/
public Authentication getAuthentication(final String token) {
final Claims claims = validateAndParseToken(token);
final String loginId = claims.getSubject();
final UserJpaEntity user = userRepository.findByLoginId(loginId)
.orElseThrow(() -> new IllegalArgumentException("존재하지 않는 사용자입니다."));
final PrincipalDetails principalDetails = new PrincipalDetails(user);

return new UsernamePasswordAuthenticationToken(principalDetails, "", principalDetails.getAuthorities());
}

private Claims parseClaims(String token) {
try {
return Jwts.parserBuilder()
.setSigningKey(key)
.build()
.parseClaimsJws(token)
.getBody();
} catch (ExpiredJwtException exception) {
return exception.getClaims();
}
}

/**
* 토큰 검증과 함께 파싱을 수행한다.
*
* @param token 토큰
* @return 파싱된 Claims
*/
protected Claims validateAndParseToken(final String token) {
try {
final Claims claims = parseClaims(token);

if (!claims.get(TOKEN_TYPE_KEY).equals(tokenType)) {
throw new CustomRuntimeException(ErrorCode.INVALID_TOKEN_TYPE);
}

if (claims.getExpiration().toInstant().isBefore(new Date().toInstant())) {
throw new CustomRuntimeException(ErrorCode.EXPIRED_TOKEN);
}
return claims;
} catch (JwtException | IllegalArgumentException exception) {
throw new CustomRuntimeException(ErrorCode.INVALID_TOKEN_TYPE);
}
}

/**
* HttpServletRequest에서 토큰을 추출한다. 토큰이 없는 경우 null을 반환한다.
*
* @param request HttpServletRequest
* @return 추출된 토큰
*/
public String resolveToken(final HttpServletRequest request) {
final String header = request.getHeader(this.header);

if (header != null && header.startsWith(BEARER_TYPE)) {
return header.replace(BEARER_TYPE, "").trim();
}
return null;
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,51 @@
package life.mosu.mosuserver.applicaiton.auth;

import life.mosu.mosuserver.domain.user.UserJpaEntity;
import lombok.Getter;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;

import java.util.ArrayList;
import java.util.Collection;
import java.util.List;

public record PrincipalDetails(@Getter UserJpaEntity user) implements UserDetails {

@Override
public Collection<? extends GrantedAuthority> getAuthorities() {
List<GrantedAuthority> authorities = new ArrayList<>();
authorities.add(new SimpleGrantedAuthority(user.getUserRole().name()));
return authorities;
}

@Override
public String getPassword() {
return user.getPassword();
}

@Override
public String getUsername() {
return user.getLoginId();
}

@Override
public boolean isAccountNonExpired() {
return UserDetails.super.isAccountNonExpired();
}

@Override
public boolean isAccountNonLocked() {
return UserDetails.super.isAccountNonLocked();
}

@Override
public boolean isCredentialsNonExpired() {
return UserDetails.super.isCredentialsNonExpired();
}

@Override
public boolean isEnabled() {
return UserDetails.super.isEnabled();
}
}
Loading