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

[FEAT🛠️] JWT TOKEN 적용 #5

Merged
merged 7 commits into from
Feb 3, 2024
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
21 changes: 21 additions & 0 deletions build.gradle
Original file line number Diff line number Diff line change
Expand Up @@ -24,11 +24,32 @@ 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-security'
// https://mvnrepository.com/artifact/org.springdoc/springdoc-openapi-starter-webmvc-ui
implementation 'org.springdoc:springdoc-openapi-starter-webmvc-ui:2.3.0'
compileOnly 'org.projectlombok:lombok'
runtimeOnly 'com.h2database:h2'
runtimeOnly 'org.postgresql:postgresql'
annotationProcessor 'org.projectlombok:lombok'


// lombok 뒤에 위치 필요
implementation 'org.mapstruct:mapstruct:1.5.5.Final'
annotationProcessor 'org.mapstruct:mapstruct-processor:1.5.5.Final'

testImplementation 'org.springframework.boot:spring-boot-starter-test'
testImplementation 'org.springframework.security:spring-security-test'

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

// com.sun.xml.bind
implementation 'com.sun.xml.bind:jaxb-impl:4.0.1'
implementation 'com.sun.xml.bind:jaxb-core:4.0.1'
// javax.xml.bind
implementation 'javax.xml.bind:jaxb-api:2.4.0-b180830.0359'
}

tasks.named('test') {
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,13 @@
package com.bside.familyrecipes.common.message;

import lombok.AllArgsConstructor;
import lombok.Getter;

@AllArgsConstructor
@Getter
public enum ExceptionMessage {
/** auth **/
INVALID_TOKEN("유효하지 않은 토큰입니다.");

private final String message;
}
12 changes: 12 additions & 0 deletions src/main/java/com/bside/familyrecipes/config/AuthConfig.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,12 @@
package com.bside.familyrecipes.config;

import lombok.Getter;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Configuration;

@Getter
@Configuration
public class AuthConfig {
@Value("${jwt.secret}")
private String jwtSecretKey;
}
18 changes: 18 additions & 0 deletions src/main/java/com/bside/familyrecipes/config/WebConfig.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,18 @@
package com.bside.familyrecipes.config;

import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.CorsRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;

@Configuration
public class WebConfig implements WebMvcConfigurer {

@Override
public void addCorsMappings(CorsRegistry registry) {
registry.addMapping("/**")
.allowedOrigins("*")
.allowedMethods("GET", "POST", "PUT", "DELETE")
.allowedHeaders("*")
.maxAge(3600);
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,82 @@
package com.bside.familyrecipes.config.jwt;

import com.bside.familyrecipes.config.AuthConfig;
import io.jsonwebtoken.Claims;
import io.jsonwebtoken.ExpiredJwtException;
import com.bside.familyrecipes.common.message.ExceptionMessage;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;
import jakarta.security.auth.message.AuthException;
import lombok.RequiredArgsConstructor;
import lombok.val;
import org.springframework.stereotype.Service;

import javax.crypto.spec.SecretKeySpec;
import javax.xml.bind.DatatypeConverter;
import java.security.SignatureException;
import java.time.ZoneId;
import java.time.ZonedDateTime;
import java.util.Date;

@RequiredArgsConstructor
@Service
public class JwtTokenManager {
private final AuthConfig authConfig;
private final ZoneId KST = ZoneId.of("Asia/Seoul");

//AccessToken 발급
public String createAccessToken(Long userId) {
val signatureAlgorithm = SignatureAlgorithm.ES256;
val secretKeyBytes = DatatypeConverter.parseBase64Binary(authConfig.getJwtSecretKey());
val signingKey = new SecretKeySpec(secretKeyBytes, signatureAlgorithm.getJcaName());
val exp = ZonedDateTime.now(KST).toLocalDateTime().plusHours(6).atZone(KST).toInstant();

return Jwts.builder()
.setSubject(Long.toString(userId))
.setExpiration(Date.from(exp))
.signWith(signingKey, signatureAlgorithm)
.compact();
}

//RefreshToken 발급
public String createRefreshToken(Long userId) {
val signatureAlgorithm = SignatureAlgorithm.HS256;
val secretKeyBytes = DatatypeConverter.parseBase64Binary(authConfig.getJwtSecretKey());
val signingKey = new SecretKeySpec(secretKeyBytes, signatureAlgorithm.getJcaName());
val exp = ZonedDateTime.now(KST).toLocalDateTime().plusDays(14).atZone(KST).toInstant();

return Jwts.builder()
.setSubject(Long.toString(userId))
.setExpiration(Date.from(exp))
.signWith(signingKey, signatureAlgorithm)
.compact();
}

// JWT 토큰 검증
public boolean verifyAuthToken(String token) {
try {
getClaimsFromToken(token);
return true;
} catch ( SignatureException | ExpiredJwtException e ) {
return false;
}
}

// userId 조회
public String getUserIdFromAuthToken(String token) throws AuthException {
try{
val claims = getClaimsFromToken(token);
return claims.getSubject();
} catch ( SignatureException | ExpiredJwtException e) {
throw new AuthException(ExceptionMessage.INVALID_TOKEN.getMessage());
}
}

private Claims getClaimsFromToken(String token) throws SignatureException {
return Jwts.parserBuilder()
.setSigningKey(DatatypeConverter.parseBase64Binary(authConfig.getJwtSecretKey()))
.build()
.parseClaimsJws(token)
.getBody();
}
}
9 changes: 0 additions & 9 deletions src/main/resources/application.properties

This file was deleted.

9 changes: 9 additions & 0 deletions src/main/resources/application.yml
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
spring:
profiles:
active: prod

---

spring:
profiles:
active: dev