Skip to content

Commit

Permalink
fix: ExpiredJwtException.class
Browse files Browse the repository at this point in the history
  • Loading branch information
downfa11 committed Jul 4, 2024
1 parent 5e7daca commit 20cb7d8
Show file tree
Hide file tree
Showing 9 changed files with 115 additions and 67 deletions.
5 changes: 5 additions & 0 deletions business-service/build.gradle
Original file line number Diff line number Diff line change
Expand Up @@ -36,6 +36,11 @@ dependencies {

implementation 'org.springframework.boot:spring-boot-starter-data-jpa'
runtimeOnly 'com.mysql:mysql-connector-j'

//jwt
implementation 'io.jsonwebtoken:jjwt-api:0.11.2'
implementation 'io.jsonwebtoken:jjwt-impl:0.11.2'
implementation 'io.jsonwebtoken:jjwt-jackson:0.11.2'
}

tasks.named('test') {
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,17 @@
package com.ns.business;

import io.jsonwebtoken.ExpiredJwtException;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

@RestControllerAdvice
public class JwtExceptionHandler {

@ExceptionHandler(ExpiredJwtException.class)
public ResponseEntity<String> handleExpiredJwtException(ExpiredJwtException ex) {
return ResponseEntity.status(HttpStatus.UNAUTHORIZED)
.body("JWT token has expired");
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -124,11 +124,11 @@ private SubTask Register(SubTask subTask){
new UserData.UserDurability(10)
);

log.info(jpaEntity.getUserId()+"번 사용자를 생성했습니다.");
log.info(jpaEntity.getUserId()+"번 데이터인 "+membershipId+" 사용자를 생성했습니다.");
if(jpaEntity!=null)
subTask.setStatus("success");

}catch(RuntimeException e){
} catch(RuntimeException e){
log.error("Error processing subatsk : "+e.getMessage());
subTask.setData(null);
subTask.setStatus("fail");
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@

import com.ns.business.adpater.in.web.dto.ModifyUserDataRequest;
import com.ns.business.adpater.in.web.dto.RegisterUserDataRequest;
import com.ns.business.adpater.out.JwtTokenProvider;
import com.ns.business.application.port.in.FindUserDataUseCase;
import com.ns.business.application.port.in.ModifyUserDataUseCase;
import com.ns.business.application.port.in.RegisterUserDataUseCase;
Expand All @@ -21,9 +22,12 @@ public class UserDataController {
private final RegisterUserDataUseCase registerUserDataUseCase;
private final ModifyUserDataUseCase modifyUserDataUseCase;
private final FindUserDataUseCase findUserDataUseCase;
private final JwtTokenProvider jwtTokenProvider;

@PostMapping(path = "/register")
ResponseEntity<UserData> registerUserData(@RequestBody RegisterUserDataRequest request){
Long memberId = jwtTokenProvider.getMembershipIdbyToken();

RegisterUserDataCommand command = RegisterUserDataCommand.builder()
.userId(request.getUserId())
.name(request.getName())
Expand All @@ -46,6 +50,8 @@ ResponseEntity<UserData> registerUserData(@RequestBody RegisterUserDataRequest r

@PostMapping(path="/update")
ResponseEntity<UserData> modifyUserDataByUserId(@RequestBody ModifyUserDataRequest request){
Long memberId = jwtTokenProvider.getMembershipIdbyToken();

ModifyUserDataCommand command = ModifyUserDataCommand.builder()
.userId(request.getUserId())
.gold(request.getGold())
Expand All @@ -67,6 +73,8 @@ ResponseEntity<UserData> modifyUserDataByUserId(@RequestBody ModifyUserDataReque

@GetMapping(path="/{userId}")
ResponseEntity<UserData> findUserDataByUserId(@PathVariable Long userId){
Long memberId = jwtTokenProvider.getMembershipIdbyToken();

FindUserDataCommand command = FindUserDataCommand.builder()
.userId(userId)
.build();
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,45 @@
package com.ns.business.adpater.out;

import io.jsonwebtoken.*;
import jakarta.servlet.http.HttpServletRequest;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;


@Component
public class JwtTokenProvider {

private String jwtSecret; // secret key

public JwtTokenProvider(){
this.jwtSecret="NYd4nEtyLtcU7cpS/1HTFVmQJd7MmrP+HafWoXZjWNOL7qKccOOUfQNEx5yvG6dfdpuBeyMs9eEbRmdBrPQCNg==";
}

public String getJwtToken(){
HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.currentRequestAttributes()).getRequest();
return request.getHeader("Authorization");
}

public Long getMembershipIdbyToken() {
String accessToken = getJwtToken();
if(accessToken == null || accessToken.length() == 0){
throw new RuntimeException("JwtToken is Invalid.");
}

try {
String token = accessToken.replace("Bearer ", "");
Claims claims = Jwts.parserBuilder()
.setSigningKey(jwtSecret)
.build()
.parseClaimsJws(token)
.getBody();

String membershipIdString = claims.get("sub", String.class);
return Long.parseLong(membershipIdString);
} catch (ExpiredJwtException ex) {
throw ex;
}
}

}
Original file line number Diff line number Diff line change
@@ -0,0 +1,17 @@
package com.ns.dedicated;

import io.jsonwebtoken.ExpiredJwtException;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

@RestControllerAdvice
public class JwtExceptionHandler {

@ExceptionHandler(ExpiredJwtException.class)
public ResponseEntity<String> handleExpiredJwtException(ExpiredJwtException ex) {
return ResponseEntity.status(HttpStatus.UNAUTHORIZED)
.body("JWT token has expired");
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -35,6 +35,8 @@ public class BoardController {

@PostMapping("/add")
public Board add(@RequestBody AddBoardRequest request) {
Long memberId = jwtTokenProvider.getMembershipIdbyToken();

RegisterBoardCommand command = RegisterBoardCommand.builder()
.title(request.getTitle())
.contents(request.getContents())
Expand All @@ -45,6 +47,7 @@ public Board add(@RequestBody AddBoardRequest request) {

@PostMapping("/add/temp")
public Board addTemp() {
Long memberId = jwtTokenProvider.getMembershipIdbyToken();
Random random = new Random();

RegisterBoardCommand command = RegisterBoardCommand.builder()
Expand All @@ -57,6 +60,8 @@ public Board addTemp() {

@PatchMapping("/update")
public ResponseEntity<Board> updateBoard(@RequestBody UpdateBoardRequest request) {
Long memberId = jwtTokenProvider.getMembershipIdbyToken();

ModifyBoardCommand command = ModifyBoardCommand.builder()
.boardId(request.getBoardId())
.title(request.getTitle())
Expand Down Expand Up @@ -90,6 +95,8 @@ public ResponseEntity<BoardList> getBoardsAll(@PathVariable Long offset) {

@DeleteMapping("{boardId}")
void deleteBoardByBoardId(@PathVariable Long boardId){
Long memberId = jwtTokenProvider.getMembershipIdbyToken();

DeleteBoardCommand command = DeleteBoardCommand.builder()
.boardId(boardId).build();

Expand All @@ -98,7 +105,7 @@ void deleteBoardByBoardId(@PathVariable Long boardId){

@GetMapping("/polling")
public ResponseEntity<String> PostPolling(){
Long memberId = jwtTokenProvider.getMembershipIdbyToken();

return ResponseEntity.ok().body(findBoardUseCase.findLatestPostTimeStamp());
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -7,90 +7,39 @@
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import java.util.Date;

@Component
public class JwtTokenProvider {

private String jwtSecret; // secret key
private long jwtExpirationInMs;
private long refreshTokenExpirationInMs;

public JwtTokenProvider(){
this.jwtSecret="NYd4nEtyLtcU7cpS/1HTFVmQJd7MmrP+HafWoXZjWNOL7qKccOOUfQNEx5yvG6dfdpuBeyMs9eEbRmdBrPQCNg==";
this.jwtExpirationInMs= 1000L * 300;
this.refreshTokenExpirationInMs = 1000L * 360;
}

public String getJwtToken(){
HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.currentRequestAttributes()).getRequest();
return request.getHeader("Authorization");
}

public Long getMembershipIdbyToken() {
String accessToken = getJwtToken();
if(accessToken == null || accessToken.length() == 0){
throw new RuntimeException("JwtToken is Invalid.");
}

String token = accessToken.replace("Bearer ", "");
Claims claims = Jwts.parserBuilder()
.setSigningKey(jwtSecret)
.build()
.parseClaimsJws(token)
.getBody();

String membershipIdString = claims.get("sub", String.class);
Long membershipId = Long.parseLong(membershipIdString);
return membershipId;
}

public String generateJwtToken(String membershipId) {
Date now = new Date();
Date expiryDate = new Date(now.getTime() + jwtExpirationInMs);

String token = Jwts.builder()
.setSubject(membershipId.toString())
.setHeaderParam("type", "jwt")
.claim("id", membershipId)
.setIssuedAt(now)
.setExpiration(expiryDate)
.signWith(SignatureAlgorithm.HS256, jwtSecret)
.compact();

return "Bearer " + token;
}

public String generateRefreshToken(String membershipId) {
Date now = new Date();
Date expiryDate = new Date(now.getTime() + refreshTokenExpirationInMs);

return Jwts.builder()
.setSubject(membershipId.toString())
.setIssuedAt(now)
.setExpiration(expiryDate)
.signWith(SignatureAlgorithm.HS512, jwtSecret)
.compact();
}


public boolean validateJwtToken(String token) {
try {
Jwts.parser().setSigningKey(jwtSecret).parseClaimsJws(token);
return true;
} catch (MalformedJwtException ex) {
// Invalid JWT token: 유효하지 않은 JWT 토큰일 때 발생하는 예외
String token = accessToken.replace("Bearer ", "");
Claims claims = Jwts.parserBuilder()
.setSigningKey(jwtSecret)
.build()
.parseClaimsJws(token)
.getBody();

String membershipIdString = claims.get("sub", String.class);
return Long.parseLong(membershipIdString);
} catch (ExpiredJwtException ex) {
// Expired JWT token: 토큰의 유효기간이 만료된 경우 발생하는 예외
} catch (UnsupportedJwtException ex) {
// Unsupported JWT token: 지원하지 않는 JWT 토큰일 때 발생하는 예외
} catch (IllegalArgumentException ex) {
// JWT claims string is empty: JWT 토큰이 비어있을 때 발생하는 예외
throw ex;
}
return false;
}

public String parseMembershipIdFromToken(String token) {
Claims claims = Jwts.parser().setSigningKey(jwtSecret).parseClaimsJws(token).getBody();
return claims.getSubject();
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -11,9 +11,9 @@ public class CorsConfig implements WebMvcConfigurer {
@Override
public void addCorsMappings(CorsRegistry registry) {
registry.addMapping("/**")
.allowedOrigins("*")
.allowedOrigins("http://localhost:8085")
.allowedMethods("GET", "POST", "PUT", "DELETE")
.allowedHeaders("*")
.allowCredentials(false);
.allowCredentials(true);
}
}

0 comments on commit 20cb7d8

Please sign in to comment.