Skip to content

Commit

Permalink
[Feat] JwtAuthenticationFilter 분리
Browse files Browse the repository at this point in the history
  • Loading branch information
sjk4618 committed May 27, 2024
1 parent 76e4c89 commit e4d1f5a
Show file tree
Hide file tree
Showing 3 changed files with 43 additions and 26 deletions.
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
package org.sopt.springFirstSeminar.common;

public class Constant {
public static final String AUTHORIZATION = "Authorization";
public static final String BEARER = "Bearer ";
}
Original file line number Diff line number Diff line change
@@ -1,9 +1,6 @@
package org.sopt.springFirstSeminar.common.jwt;

import io.jsonwebtoken.Claims;
import io.jsonwebtoken.Header;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;
import io.jsonwebtoken.*;
import io.jsonwebtoken.security.Keys;
import org.sopt.springFirstSeminar.common.jwt.dto.TokenResponse;
import org.springframework.beans.factory.annotation.Value;
Expand Down Expand Up @@ -36,6 +33,12 @@ public String generateToken(final Long userId, boolean isAccessToken) {
.compact();
}

public JwtParser getJwtParser() {
return Jwts.parserBuilder()
.setSigningKey(getSigningKey())
.build();
}

private Date generateExpireDataByToken(final boolean isAccessToken, Date presentDate) {
return new Date(presentDate.getTime() + setExpireTimeByToken(isAccessToken));
}
Expand All @@ -53,5 +56,4 @@ public SecretKey getSigningKey() {
String encodedKey = Base64.getEncoder().encodeToString(secretKey.getBytes()); //SecretKey 통해 서명 생성
return Keys.hmacShaKeyFor(encodedKey.getBytes()); //일반적으로 HMAC (Hash-based Message Authentication Code) 알고리즘 사용
}

}
Original file line number Diff line number Diff line change
Expand Up @@ -6,20 +6,23 @@
import jakarta.servlet.http.HttpServletResponse;
import lombok.NonNull;
import lombok.RequiredArgsConstructor;
import org.sopt.springFirstSeminar.common.Constant;
import org.sopt.springFirstSeminar.common.dto.ErrorMessage;
import org.sopt.springFirstSeminar.common.jwt.JwtTokenProvider;
import org.sopt.springFirstSeminar.common.jwt.JwtTokenValidator;
import org.sopt.springFirstSeminar.common.jwt.UserAuthentication;
import org.sopt.springFirstSeminar.exception.UnauthorizedException;
import org.springframework.security.core.context.SecurityContext;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.web.authentication.WebAuthenticationDetails;
import org.springframework.security.web.authentication.WebAuthenticationDetailsSource;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import org.springframework.web.filter.OncePerRequestFilter;

import java.io.IOException;

import static org.sopt.springFirstSeminar.common.jwt.JwtValidationType.VALID_JWT;
import static org.sopt.springFirstSeminar.common.jwt.UserAuthentication.createUserAuthentication;

@Component
@RequiredArgsConstructor
Expand All @@ -28,29 +31,35 @@ public class JwtAuthenticationFilter extends OncePerRequestFilter {
private final JwtTokenProvider jwtTokenProvider;
private final JwtTokenValidator jwtTokenValidator;


@Override
protected void doFilterInternal(@NonNull HttpServletRequest request,
@NonNull HttpServletResponse response,
@NonNull FilterChain filterChain) throws ServletException, IOException {
try {
final String token = getJwtFromRequest(request);
if (jwtTokenValidator.validateToken(token) == VALID_JWT) {
Long memberId = jwtTokenProvider.getUserFromJwt(token);
UserAuthentication authentication = UserAuthentication.createUserAuthentication(memberId);
authentication.setDetails(new WebAuthenticationDetailsSource().buildDetails(request));
SecurityContextHolder.getContext().setAuthentication(authentication);
}
} catch (Exception exception) {
throw new UnauthorizedException(ErrorMessage.JWT_UNAUTHORIZED_EXCEPTION);
}
protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws ServletException, IOException {
final String accessToken = getAccessToken(request);
jwtTokenValidator.validateAccessToken(accessToken);
doAuthentication(request, jwtTokenProvider.getSubject(accessToken));
filterChain.doFilter(request, response);
}

private String getJwtFromRequest(HttpServletRequest request) {
String bearerToken = request.getHeader("Authorization");
if (StringUtils.hasText(bearerToken) && bearerToken.startsWith("Bearer ")) {
return bearerToken.substring("Bearer ".length());
//userId로 UserAuthentication 객체 생성
private void doAuthentication(HttpServletRequest request, Long userId) {
UserAuthentication authentication = createUserAuthentication(userId);
createAndSetWebAuthenticationDetails(request, authentication);
SecurityContext securityContext = SecurityContextHolder.getContext();
securityContext.setAuthentication(authentication);
}

private void createAndSetWebAuthenticationDetails(HttpServletRequest request, UserAuthentication authentication) {
WebAuthenticationDetailsSource webAuthenticationDetailsSource = new WebAuthenticationDetailsSource();
WebAuthenticationDetails webAuthenticationDetails = webAuthenticationDetailsSource.buildDetails(request);
authentication.setDetails(webAuthenticationDetails);
}

//accessToken 가져오기
private String getAccessToken(final HttpServletRequest request) {
String accessToken = request.getHeader(Constant.AUTHORIZATION);
if (StringUtils.hasText(accessToken) && accessToken.startsWith(Constant.BEARER)) {
return accessToken.substring(Constant.BEARER.length());
}
return null;
throw new UnauthorizedException(ErrorMessage.INVALID_ACCESS_TOKEN);
}
}
}

0 comments on commit e4d1f5a

Please sign in to comment.