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차 세미나 과제 #12

Open
wants to merge 6 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
1 change: 1 addition & 0 deletions seminar/build.gradle
Original file line number Diff line number Diff line change
Expand Up @@ -35,6 +35,7 @@ dependencies {
implementation group: 'io.jsonwebtoken', name: 'jjwt-impl', version: '0.11.5'
implementation group: 'io.jsonwebtoken', name: 'jjwt-jackson', version: '0.11.5'
implementation 'org.springframework.boot:spring-boot-starter-security'
implementation 'org.springframework.boot:spring-boot-starter-data-redis:2.3.1.RELEASE'

//Multipart file
implementation("software.amazon.awssdk:bom:2.21.0")
Expand Down
Original file line number Diff line number Diff line change
@@ -1,9 +1,12 @@
package com.seminar.seminar.common.jwt;

import com.seminar.seminar.auth.UserAuthentication;
import com.seminar.seminar.repository.RedisTokenRepository;
import io.jsonwebtoken.*;
import io.jsonwebtoken.security.Keys;
import lombok.RequiredArgsConstructor;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.security.core.Authentication;
import org.springframework.stereotype.Component;

Expand All @@ -17,16 +20,22 @@ 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 * 3;
private static final Long REFRESH_TOKEN_EXPIRATION_TIME = 60 * 60 * 24 * 1000L * 14;
@Value("${jwt.secret}")
private String JWT_SECRET;

private final RedisTemplate<String, String> redisTemplate;
private final RedisTokenRepository redisTokenRepository;

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) {
final Date now = new Date();
Expand All @@ -41,6 +50,14 @@ public String generateToken(Authentication authentication, Long tokenExpirationT
.setClaims(claims) // Claim
.signWith(getSigningKey()) // Signature
.compact();

}

public String newAccessToken(String refreshToken){
final Claims claims = getBody(refreshToken);
Long userId = Long.valueOf(claims.get(USER_ID).toString());
Authentication authentication = UserAuthentication.createUserAuthentication(userId);
return issueAccessToken(authentication);
}

private SecretKey getSigningKey() {
Expand Down
34 changes: 34 additions & 0 deletions seminar/src/main/java/com/seminar/seminar/config/RedisConfig.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,34 @@
package com.seminar.seminar.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.setKeySerializer(new StringRedisSerializer());
redisTemplate.setValueSerializer(new StringRedisSerializer());
redisTemplate.setConnectionFactory(redisConnectionFactory());

return redisTemplate;
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -22,6 +22,15 @@ public class MemberController {
// public ResponseEntity createMember(@RequestBody MemberCreateDto memberCreate){
// return ResponseEntity.created(URI.create(memberService.createMember(memberCreate))).build();
// }
@PostMapping
public ResponseEntity<UserJoinResponse> postMember(
@RequestBody MemberCreateDto memberCreateDto
){
UserJoinResponse userJoinResponse = memberService.createMember(memberCreateDto);
return ResponseEntity.status(HttpStatus.CREATED)
.header("Location", userJoinResponse.userId())
.body(userJoinResponse);
}

@GetMapping("/{memberId}")
public ResponseEntity<MemberFindDto> findtMemberById(@PathVariable Long memberId){
Expand All @@ -39,13 +48,4 @@ public ResponseEntity deleteMember(@PathVariable Long memberId){
return ResponseEntity.noContent().build();
}

@PostMapping
public ResponseEntity<UserJoinResponse> postMember(
@RequestBody MemberCreateDto memberCreateDto
){
UserJoinResponse userJoinResponse = memberService.createMember(memberCreateDto);
return ResponseEntity.status(HttpStatus.CREATED)
.header("Location", userJoinResponse.userId())
.body(userJoinResponse);
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,24 @@
package com.seminar.seminar.controller;

import com.seminar.seminar.service.TokenService;
import com.seminar.seminar.service.dto.TokenDto;
import lombok.RequiredArgsConstructor;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestHeader;
import org.springframework.web.bind.annotation.RestController;

@RequiredArgsConstructor
@RestController("/api/v1/auth")
public class TokenController {
private final TokenService tokenService;
@PostMapping("/refreshToken")
public ResponseEntity<TokenDto> createNewAccessToken(
@RequestHeader String refreshToken
){
TokenDto tokenDto = tokenService.newAccessToken(refreshToken);
return ResponseEntity.status(HttpStatus.CREATED)
.body(tokenDto);
}
}
30 changes: 30 additions & 0 deletions seminar/src/main/java/com/seminar/seminar/domain/Token.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,30 @@
package com.seminar.seminar.domain;

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

@RedisHash(value = "", timeToLive = 60 * 60 * 24 * 1000L * 1)
@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
Expand Up @@ -12,7 +12,9 @@ public enum ErrorMessage {
BLOG_NOT_FOUND_BY_MEMBER_ID_EXCEPTION(HttpStatus.NOT_FOUND.value(), "해당 사용자의 블로그가 존재하지 않습니다."),
POST_NOT_FOUND_BY_BLOG_ID_EXCEPTION(HttpStatus.NOT_FOUND.value(),"해당 블로그에 게시물이 존재하지 않습니다."),
POST_NOT_FOUND_BY_ID_EXCEPTION(HttpStatus.NOT_FOUND.value(), "ID에 해당하는 게시글이 존재하지 않습니다."),
JWT_UNAUTHORIZED_EXCEPTION(HttpStatus.UNAUTHORIZED.value(), "사용자의 로그인 검증을 실패했습니다.")
JWT_UNAUTHORIZED_EXCEPTION(HttpStatus.UNAUTHORIZED.value(), "사용자의 로그인 검증을 실패했습니다."),
REFRESH_TOKEN_NOT_FOUND_EXCEPTION(HttpStatus.NOT_FOUND.value(), "해당 Refresh token이 존재하지 않습니다."),
JWT_EXPIRED_EXCEPTION(HttpStatus.UNAUTHORIZED.value(), "만료된 토큰입니다.")
;
private final int status;
private final String message;
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,11 @@
package com.seminar.seminar.repository;

import com.seminar.seminar.domain.Token;
import org.springframework.data.repository.CrudRepository;

import java.util.Optional;

public interface RedisTokenRepository extends CrudRepository<Token,Long> {
Optional<Token> findByRefreshToken(final String refreshToken);
Optional<Token> findById(final Long id);
}
Original file line number Diff line number Diff line change
Expand Up @@ -3,14 +3,17 @@
import com.seminar.seminar.auth.UserAuthentication;
import com.seminar.seminar.common.jwt.JwtTokenProvider;
import com.seminar.seminar.domain.Member;
import com.seminar.seminar.domain.Token;
import com.seminar.seminar.exception.ErrorMessage;
import com.seminar.seminar.exception.NotFoundException;
import com.seminar.seminar.repository.MemberRepository;
import com.seminar.seminar.repository.RedisTokenRepository;
import com.seminar.seminar.service.dto.MemberCreateDto;
import com.seminar.seminar.service.dto.MemberFindDto;
import com.seminar.seminar.service.dto.UserJoinResponse;
import jakarta.persistence.EntityNotFoundException;
import lombok.RequiredArgsConstructor;
import org.apache.catalina.User;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import java.util.List;
Expand All @@ -20,6 +23,7 @@
public class MemberService {
private final MemberRepository memberRepository;
private final JwtTokenProvider jwtTokenProvider;
private final RedisTokenRepository redisTokenRepository;

// @Transactional //영속성 context
// //final 붙이는 경우도 가능
Expand All @@ -37,7 +41,11 @@ public UserJoinResponse createMember(MemberCreateDto memberCreateDto){
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
Original file line number Diff line number Diff line change
@@ -0,0 +1,36 @@
package com.seminar.seminar.service;

import com.seminar.seminar.auth.UserAuthentication;
import com.seminar.seminar.common.jwt.JwtTokenProvider;
import com.seminar.seminar.common.jwt.JwtValidationType;
import com.seminar.seminar.domain.Token;
import com.seminar.seminar.exception.ErrorMessage;
import com.seminar.seminar.exception.NotFoundException;
import com.seminar.seminar.exception.UnauthorizedException;
import com.seminar.seminar.repository.RedisTokenRepository;
import com.seminar.seminar.service.dto.TokenDto;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

@RequiredArgsConstructor
@Transactional
@Service
public class TokenService {
private final RedisTokenRepository redisTokenRepository;
private final JwtTokenProvider jwtTokenProvider;

@Transactional
public TokenDto newAccessToken(String refreshToken){
Token token = redisTokenRepository.findByRefreshToken(refreshToken)
.orElseThrow(
() -> new NotFoundException(ErrorMessage.REFRESH_TOKEN_NOT_FOUND_EXCEPTION)
);
if (jwtTokenProvider.validateToken(token.getRefreshToken()) == JwtValidationType.EXPIRED_JWT_TOKEN)
throw new UnauthorizedException(ErrorMessage.JWT_UNAUTHORIZED_EXCEPTION);

String newToken = jwtTokenProvider.newAccessToken(token.getRefreshToken());
return TokenDto.of(newToken);
}

}
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
package com.seminar.seminar.service.dto;

public record TokenDto(
String accessToken
) {
public static TokenDto of(final String accessToken){
return new TokenDto(accessToken);
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -2,14 +2,17 @@

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

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

Expand Down