Skip to content

Commit

Permalink
refactor: JWT 토큰 서비스 관련 코드 수정 (#13)
Browse files Browse the repository at this point in the history
  • Loading branch information
pdohyung committed Nov 16, 2023
1 parent 705a36f commit 22c545f
Show file tree
Hide file tree
Showing 3 changed files with 47 additions and 45 deletions.
4 changes: 2 additions & 2 deletions build.gradle
Original file line number Diff line number Diff line change
Expand Up @@ -31,8 +31,8 @@ dependencies {
annotationProcessor 'org.projectlombok:lombok'
testImplementation 'org.springframework.boot:spring-boot-starter-test'
// jwt
implementation 'io.jsonwebtoken:jjwt:0.9.1'
implementation 'javax.xml.bind:jaxb-api:2.3.0'
implementation 'io.jsonwebtoken:jjwt-api:0.11.5'
runtimeOnly 'io.jsonwebtoken:jjwt-impl:0.11.5', 'io.jsonwebtoken:jjwt-jackson:0.11.5'
// spring security
implementation 'org.springframework.boot:spring-boot-starter-security'
// redis
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -29,19 +29,18 @@ protected void doFilterInternal(HttpServletRequest request, HttpServletResponse
FilterChain filterChain) throws ServletException, IOException {

String token = jwtProvider.extractToken(request)
.filter(inputToken -> !jwtProvider.isExpired(inputToken))
.filter(jwtProvider::isTokenValid)
.orElse(null);

log.info("토큰 : {}", token);
if (token != null) {
String username = jwtProvider.getUsernameFromToken(token);
log.info("토큰이 존재한다. username : {}", username);

try {
UserDetails userDetails = apiUserDetailsService.loadUserByUsername(username);

if (userDetails != null && SecurityContextHolder.getContext().getAuthentication() == null) {
UsernamePasswordAuthenticationToken authenticationToken = new UsernamePasswordAuthenticationToken(
userDetails, null, userDetails.getAuthorities());
UsernamePasswordAuthenticationToken authenticationToken =
new UsernamePasswordAuthenticationToken(userDetails, null, userDetails.getAuthorities());
authenticationToken.setDetails(new WebAuthenticationDetailsSource().buildDetails(request));

SecurityContextHolder.getContext().setAuthentication(authenticationToken);
Expand Down
79 changes: 41 additions & 38 deletions src/main/java/com/backend/jwt/service/JwtProvider.java
Original file line number Diff line number Diff line change
Expand Up @@ -6,38 +6,42 @@
import io.jsonwebtoken.Claims;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;
import io.jsonwebtoken.security.Keys;
import jakarta.servlet.http.HttpServletRequest;
import lombok.Getter;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import java.nio.charset.StandardCharsets;
import java.security.Key;
import java.util.Date;
import java.util.Optional;

@Slf4j
@Component
@Getter
public class JwtProvider {
@Value("${jwt.secretKey}")
private String secretKey;

@Value("${jwt.access.expiration}")
private Integer accessTokenExpirationPeriod;

@Value("${jwt.refresh.expiration}")
private Integer refreshTokenExpirationPeriod;

@Value("${jwt.access.header}")
private String accessHeader;

@Value("${jwt.refresh.header}")
private String refreshHeader;

private static final String ID_CLAIM = "email";
private static final String ROLE_CLAIM = "roles";
private final Key secretKey;
private final Long accessTokenExpirationPeriod;
private final String accessHeader;
private final Long refreshTokenExpirationPeriod;
private final String refreshHeader;
private static final String BEARER = "Bearer ";

public JwtProvider(@Value("${jwt.secretKey}") String secretKey,
@Value("${jwt.access.expiration}") Long accessTokenExpirationPeriod,
@Value("${jwt.access.header}") String accessHeader,
@Value("${jwt.refresh.expiration}") Long refreshTokenExpirationPeriod,
@Value("${jwt.refresh.header}") String refreshHeader) {

this.secretKey = Keys.hmacShaKeyFor(secretKey.getBytes(StandardCharsets.UTF_8));
this.accessTokenExpirationPeriod = accessTokenExpirationPeriod;
this.accessHeader = accessHeader;
this.refreshTokenExpirationPeriod = refreshTokenExpirationPeriod;
this.refreshHeader = refreshHeader;
}

public Token createToken(String email) {
AccessToken accessToken = AccessToken.builder()
.header(accessHeader)
Expand All @@ -55,50 +59,49 @@ public Token createToken(String email) {
}

public Optional<String> extractToken(HttpServletRequest request) {
log.info("엑세스 토큰 : {}", request.getHeader("Authorization"));
return Optional.ofNullable(request.getHeader(accessHeader))
.filter(token -> token.startsWith(BEARER))
.map(token -> token.replace(BEARER, ""));
}

public String getUsernameFromToken(String token) {
return Jwts.parser()
return Jwts.parserBuilder()
.setSigningKey(secretKey)
.build()
.parseClaimsJws(token)
.getBody()
.get(ID_CLAIM, String.class);
.getSubject();
}

public boolean isExpired(String token) {
return Jwts.parser()
.setSigningKey(secretKey)
.parseClaimsJws(token)
.getBody()
.getExpiration()
.before(new Date());
public boolean isTokenValid(String token) {
try {
Jwts.parserBuilder()
.setSigningKey(secretKey)
.build()
.parseClaimsJws(token)
.getBody();
return true;
} catch (Exception e) {
return false;
}
}

public String createAccessToken(String email) {
Claims claims = Jwts.claims();
claims.put(ID_CLAIM, email);

private String createAccessToken(String email) {
return Jwts.builder()
.setClaims(claims)
.setIssuedAt(new Date(System.currentTimeMillis()))
.setSubject(email)
.setExpiration(expireTime(accessTokenExpirationPeriod))
.signWith(SignatureAlgorithm.HS256, secretKey)
.signWith(secretKey)
.compact();
}

public String createRefreshToken() {
private String createRefreshToken() {
return Jwts.builder()
.setIssuedAt(new Date(System.currentTimeMillis()))
.setExpiration(expireTime(refreshTokenExpirationPeriod))
.signWith(SignatureAlgorithm.HS256, secretKey)
.signWith(secretKey)
.compact();
}

private Date expireTime(int expirationPeriod) {
private Date expireTime(Long expirationPeriod) {
return new Date(System.currentTimeMillis() + expirationPeriod);
}
}

0 comments on commit 22c545f

Please sign in to comment.