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

[week6] 6차 세미나 정규 과제 #11

Open
wants to merge 3 commits into
base: main
Choose a base branch
from
Open
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
2 changes: 1 addition & 1 deletion .idea/sukbum.iml

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

3 changes: 3 additions & 0 deletions spring/build.gradle
Original file line number Diff line number Diff line change
Expand Up @@ -47,6 +47,9 @@ dependencies {
//Multipart file
implementation("software.amazon.awssdk:bom:2.21.0")
implementation("software.amazon.awssdk:s3:2.21.0")

//Redis
implementation 'org.springframework.boot:spring-boot-starter-data-redis:2.3.1.RELEASE'
}

tasks.named('test') {
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,32 @@
package org.sopt.spring.common.auth.redis.config;

import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.connection.RedisConnectionFactory;
import org.springframework.data.redis.connection.lettuce.LettuceConnectionFactory;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.serializer.StringRedisSerializer;

@Configuration
public class RedisConfig {

@Value("${spring.data.redis.host}")
private String host;

@Value("${spring.data.redis.port}")
private int port;

@Bean
public RedisConnectionFactory redisConnectionFactory() {
return new LettuceConnectionFactory(host, port);
}
@Bean
public RedisTemplate<String, Object> redisTemplate() {
RedisTemplate<String, Object> redisTemplate = new RedisTemplate<>();
redisTemplate.setConnectionFactory(redisConnectionFactory());
redisTemplate.setKeySerializer(new StringRedisSerializer());
redisTemplate.setValueSerializer(new StringRedisSerializer());
return redisTemplate;
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,31 @@
package org.sopt.spring.common.auth.redis.domain;

import lombok.AllArgsConstructor;
import lombok.Builder;
import lombok.Getter;
import org.springframework.data.annotation.Id;
import org.springframework.data.redis.core.RedisHash;
import org.springframework.data.redis.core.index.Indexed;

@RedisHash(value = "", timeToLive = 60 * 60 * 24 * 1000L * 14)
@AllArgsConstructor
@Getter
@Builder
public class Token {

@Id
private Long id;

@Indexed
private String refreshToken;

public static Token of(
final Long id,
final String refreshToken
) {
return Token.builder()
.id(id)
.refreshToken(refreshToken)
.build();
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,11 @@
package org.sopt.spring.common.auth.redis.repository;

import org.sopt.spring.common.auth.redis.domain.Token;
import org.springframework.data.repository.CrudRepository;

import java.util.Optional;

public interface RedisTokenRepository extends CrudRepository<Token, String> {
Optional<Token> findByRefreshToken(final String refreshToken);
Optional<Token> findById(final Long id);
}
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,7 @@ public enum ErrorMessage {
BLOG_CANT_USE(HttpStatus.NOT_FOUND.value(), "사용자의 블로그가 아닙니다."),
POSTING_NOT_FOUND(HttpStatus.NOT_FOUND.value(), "ID에 해당하는 사용자가 존재하지 않습니다"),
JWT_UNAUTHORIZED_EXCEPTION(HttpStatus.UNAUTHORIZED.value(), "사용자의 로그인 검증을 실패했습니다."),
INVALID_REFRESH_TOKEN(HttpStatus.UNAUTHORIZED.value(), "리프레시 토큰이 만료되었습니다."),
;
private final int status;
private final String message;
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -17,7 +17,8 @@ public class JwtTokenProvider {

private static final String USER_ID = "userId";

private static final Long ACCESS_TOKEN_EXPIRATION_TIME = 24 * 60 * 60 * 1000L * 14;
private static final Long ACCESS_TOKEN_EXPIRATION_TIME = 24 * 60 * 60 * 1000L;
private static final Long REFRESH_TOKEN_EXPIRATION_TIME = 24 * 60 * 60 * 1000L * 14;

@Value("${jwt.secret}")
private String JWT_SECRET;
Expand All @@ -26,6 +27,9 @@ public class JwtTokenProvider {
public String issueAccessToken(final Authentication authentication) {
return generateToken(authentication, ACCESS_TOKEN_EXPIRATION_TIME);
}
public String issueRefreshToken(final Authentication authentication) {
return generateToken(authentication, REFRESH_TOKEN_EXPIRATION_TIME);
}


public String generateToken(Authentication authentication, Long tokenExpirationTime) {
Expand All @@ -43,6 +47,7 @@ public String generateToken(Authentication authentication, Long tokenExpirationT
.compact();
}


private SecretKey getSigningKey() {
String encodedKey = Base64.getEncoder().encodeToString(JWT_SECRET.getBytes()); //SecretKey 통해 서명 생성
return Keys.hmacShaKeyFor(encodedKey.getBytes()); //일반적으로 HMAC (Hash-based Message Authentication Code) 알고리즘 사용
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@


import lombok.RequiredArgsConstructor;
import org.sopt.spring.common.auth.PrincipalHandler;
import org.sopt.spring.member.service.MemberService;
import org.sopt.spring.member.dto.MemberCreateDto;
import org.sopt.spring.member.dto.MemberFindDto;
Expand All @@ -16,7 +17,6 @@
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.net.URI;
import java.util.List;

@RestController
Expand All @@ -25,6 +25,7 @@
public class MemberController {

private final MemberService memberService;
private final PrincipalHandler principalHandler;

@PostMapping
public ResponseEntity<UserJoinResponse> createMember(
Expand All @@ -38,13 +39,27 @@ public ResponseEntity<UserJoinResponse> createMember(
);
}

@PostMapping("/refresh")
public ResponseEntity<UserJoinResponse> refreshToken(){
UserJoinResponse userJoinResponse = memberService.refreshToken(
principalHandler.getUserIdFromPrincipal()
);
return ResponseEntity.status(HttpStatus.CREATED)
.header("Location", userJoinResponse.userId())
.body(
userJoinResponse
);
}

@GetMapping("/{memberId}")
public ResponseEntity<MemberFindDto> findMemberById(@PathVariable Long memberId) {
return ResponseEntity.ok(memberService.findMemberById(memberId));
}

@DeleteMapping("/{memberId}")
public ResponseEntity deleteMemberById(@PathVariable Long memberId){
public ResponseEntity deleteMemberById(
@PathVariable Long memberId
){
memberService.deleteMemberById(memberId);
return ResponseEntity.noContent().build();
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,10 @@
import jakarta.persistence.EntityNotFoundException;
import lombok.RequiredArgsConstructor;
import org.sopt.spring.common.auth.UserAuthentication;
import org.sopt.spring.common.auth.redis.domain.Token;
import org.sopt.spring.common.auth.redis.repository.RedisTokenRepository;
import org.sopt.spring.common.exception.ErrorMessage;
import org.sopt.spring.common.exception.UnauthorizedException;
import org.sopt.spring.common.jwt.JwtTokenProvider;
import org.sopt.spring.member.domain.Member;
import org.sopt.spring.common.exception.NotFoundException;
Expand All @@ -23,6 +26,7 @@ public class MemberService {

private final MemberRepository memberRepository;
private final JwtTokenProvider jwtTokenProvider;
private final RedisTokenRepository redisTokenRepository;

@Transactional
public UserJoinResponse createMember(
Expand All @@ -35,7 +39,13 @@ public UserJoinResponse createMember(
String accessToken = jwtTokenProvider.issueAccessToken(
UserAuthentication.createUserAuthentication(memberId)
);
return UserJoinResponse.of(accessToken, memberId.toString());
String refreshToken = jwtTokenProvider.issueRefreshToken(
UserAuthentication.createUserAuthentication(memberId)
);
//레디스에 저*장
redisTokenRepository.save(Token.of(memberId, refreshToken));

return UserJoinResponse.of(accessToken, refreshToken, memberId.toString());
}

public MemberFindDto findMemberById(Long memberId) {
Expand Down Expand Up @@ -63,4 +73,24 @@ public Member findById(Long memberId) {
() -> new NotFoundException(ErrorMessage.MEMBER_NOT_FOUND)
);
}

@Transactional
public UserJoinResponse refreshToken(Long memberId) {
//Refresh 토큰 만료: Redis에 해당 Refresh 토큰이 존재하지 않음
if(!redisTokenRepository.existsById(memberId.toString())){
throw new UnauthorizedException(ErrorMessage.INVALID_REFRESH_TOKEN);
}
//DB에 해당하는 유저 아이디가 있는지 확인
findById(memberId);

String accessToken = jwtTokenProvider.issueAccessToken(
UserAuthentication.createUserAuthentication(memberId)
);
String refreshToken = jwtTokenProvider.issueRefreshToken(
UserAuthentication.createUserAuthentication(memberId)
);
//레디스에 저*장
redisTokenRepository.save(Token.of(memberId, refreshToken));
return UserJoinResponse.of(accessToken, refreshToken, memberId.toString());
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -2,14 +2,16 @@

public record UserJoinResponse(
String accessToken,
String refreshToken,
String userId
) {

public static UserJoinResponse of(
String accessToken,
String refreshToken,
String userId
) {
return new UserJoinResponse(accessToken, userId);
return new UserJoinResponse(accessToken, refreshToken, userId);
}
}