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

[fix] 소셜 로그인 오류 수정 #47

Merged
merged 5 commits into from
Jul 11, 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
2 changes: 1 addition & 1 deletion server-yml
Original file line number Diff line number Diff line change
Expand Up @@ -51,12 +51,12 @@ public UserLoginResponse login(
return UserLoginResponse.of(issuedToken, isRegistered);
}

public void logOut(final long userId) {
public void logOut(final Long userId) {
UserInfo findUserInfo = userInfoFinder.getUserInfo(userId);
findUserInfo.updateRefreshToken(null);
}

public void withdraw(final long userId, final String code) {
public void withdraw(final Long userId, final String code) {
User user = userFinder.getUser(userId);
if (APPLE == user.getPlatform()){
try {
Expand All @@ -72,21 +72,26 @@ public void withdraw(final long userId, final String code) {

@Transactional(noRollbackFor = UnauthorizedException.class)
public UserReissueResponse reissue(final String refreshToken) {
long userId = jwtProvider.getSubject(refreshToken.substring(BEARER.length()));
Long userId = jwtProvider.getSubject(refreshToken.substring(BEARER.length()));
validateRefreshToken(refreshToken, userId);
UserInfo findUserInfo = userInfoFinder.getUserInfo(userId);
Token issuedTokens = jwtProvider.issueTokens(userId);
Token issuedTokens = jwtProvider.issueTokens(userId, getUserRole(userId));
findUserInfo.updateRefreshToken(issuedTokens.refreshToken());
return UserReissueResponse.of(issuedTokens);
}

private Token generateTokens(final long userId) {
Token issuedTokens = jwtProvider.issueTokens(userId);
private Token generateTokens(final Long userId) {
String role = userFinder.getUser(userId).getUserRole().getValue();
Token issuedTokens = jwtProvider.issueTokens(userId, getUserRole(userId));
UserInfo findUserInfo = userInfoFinder.getUserInfo(userId);
findUserInfo.updateRefreshToken(issuedTokens.refreshToken());
return issuedTokens;
}

private String getUserRole(Long userId) {
return userFinder.getUser(userId).getUserRole().getValue();
}

private SocialInfoDto getSocialInfo(
final String providerToken,
final Platform platform,
Expand Down Expand Up @@ -119,8 +124,7 @@ private User updateUserInfo(final User user) {
}

private String getRefreshToken(final Long userId) {
return userInfoFinder.getUserInfo(userId)
.getRefreshToken();
return userInfoFinder.getUserInfo(userId).getRefreshToken();
}

private void saveUserAndUserInfo(final User user) {
Expand All @@ -129,7 +133,7 @@ private void saveUserAndUserInfo(final User user) {
userInfoSaver.saveUserInfo(userInfo);
}

private void validateRefreshToken(final String refreshToken, final long userId) {
private void validateRefreshToken(final String refreshToken, final Long userId) {
try {
jwtValidator.validateRefreshToken(refreshToken);
String storedRefreshToken = getRefreshToken(userId);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -12,33 +12,25 @@
import org.springframework.stereotype.Component;

import java.io.IOException;
import java.io.PrintWriter;

@Component
public class JwtAuthenticationEntryPoint implements AuthenticationEntryPoint {

private final ObjectMapper objectMapper = new ObjectMapper();

@Override
public void commence(
HttpServletRequest request,
HttpServletResponse response,
AuthenticationException authException) throws IOException {
public void commence(HttpServletRequest request, HttpServletResponse response, AuthenticationException authException) throws IOException {
handleException(response);
}

private void handleException(HttpServletResponse response) throws IOException {
setResponse(response, HttpStatus.UNAUTHORIZED, AuthErrorCode.UNAUTHORIZED);
}

private void setResponse(
HttpServletResponse response,
HttpStatus httpStatus,
AuthErrorCode authErrorCode) throws IOException {
private void setResponse(HttpServletResponse response, HttpStatus httpStatus, AuthErrorCode authErrorCode) throws IOException {
response.setContentType(MediaType.APPLICATION_JSON_VALUE);
response.setCharacterEncoding("utf-8");
response.setStatus(httpStatus.value());
PrintWriter writer = response.getWriter();
writer.write(objectMapper.writeValueAsString(HankkiResponse.fail(authErrorCode)));
response.getWriter().write(objectMapper.writeValueAsString(HankkiResponse.fail(authErrorCode)));
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,7 @@
import org.hankki.hankkiserver.auth.jwt.JwtProvider;
import org.hankki.hankkiserver.auth.jwt.JwtValidator;
import org.hankki.hankkiserver.common.code.AuthErrorCode;
import org.hankki.hankkiserver.common.code.ErrorCode;
import org.hankki.hankkiserver.common.exception.UnauthorizedException;
import org.springframework.security.core.context.SecurityContext;
import org.springframework.security.core.context.SecurityContextHolder;
Expand All @@ -29,10 +30,7 @@ public class JwtAuthenticationFilter extends OncePerRequestFilter {
private final JwtProvider jwtProvider;

@Override
protected void doFilterInternal(
HttpServletRequest request,
HttpServletResponse response,
FilterChain filterChain) throws ServletException, IOException {
protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws ServletException, IOException {
final String accessToken = getAccessToken(request);
jwtValidator.validateAccessToken(accessToken);
doAuthentication(request, jwtProvider.getSubject(accessToken));
Expand Down
26 changes: 13 additions & 13 deletions src/main/java/org/hankki/hankkiserver/auth/jwt/JwtGenerator.java
Original file line number Diff line number Diff line change
@@ -1,9 +1,6 @@
package org.hankki.hankkiserver.auth.jwt;

import io.jsonwebtoken.Header;
import io.jsonwebtoken.JwtParser;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;
import io.jsonwebtoken.*;
import io.jsonwebtoken.security.Keys;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
Expand All @@ -22,12 +19,20 @@ public class JwtGenerator {
@Value("${jwt.refresh-token-expiration}")
private long REFRESH_TOKEN_EXPIRE_TIME;

public String generateToken(Long userId, boolean isAccessToken) {
public static final String USER_ROLE_CLAIM_NAME = "role";

public String generateToken(Long userId, String role, boolean isAccessToken) {
final Date now = generateNowDate();
final Date expiration = generateExpirationDate(isAccessToken, now);

Claims claims = Jwts.claims().setSubject(String.valueOf(userId));
if (isAccessToken) {
claims.put(USER_ROLE_CLAIM_NAME, role);
}

return Jwts.builder()
.setHeaderParam(Header.TYPE, Header.JWT_TYPE)
.setSubject(String.valueOf(userId))
.setClaims(claims)
.setIssuedAt(now)
.setExpiration(expiration)
.signWith(getSigningKey(), SignatureAlgorithm.HS256)
Expand All @@ -49,7 +54,8 @@ private Date generateExpirationDate(boolean isAccessToken, Date now) {
}

private Key getSigningKey() {
return Keys.hmacShaKeyFor(encodeSecretKey().getBytes());
byte[] keyBytes = Base64.getDecoder().decode(JWT_SECRET);
return Keys.hmacShaKeyFor(keyBytes);
}

private long calculateExpirationTime(boolean isAccessToken) {
Expand All @@ -58,10 +64,4 @@ private long calculateExpirationTime(boolean isAccessToken) {
}
return REFRESH_TOKEN_EXPIRE_TIME;
}

private String encodeSecretKey() {
return Base64.getEncoder()
.encodeToString(JWT_SECRET.getBytes());
}
}

Original file line number Diff line number Diff line change
Expand Up @@ -10,9 +10,9 @@ public class JwtProvider {

private final JwtGenerator jwtGenerator;

public Token issueTokens(Long userId) {
return Token.of(jwtGenerator.generateToken(userId, true),
jwtGenerator.generateToken(userId, false));
public Token issueTokens(Long userId, String role) {
return Token.of(jwtGenerator.generateToken(userId, role, true),
jwtGenerator.generateToken(userId, role, false));
}

public Long getSubject(String token) {
Expand Down
19 changes: 12 additions & 7 deletions src/main/java/org/hankki/hankkiserver/auth/jwt/JwtValidator.java
Original file line number Diff line number Diff line change
@@ -1,12 +1,14 @@
package org.hankki.hankkiserver.auth.jwt;

import io.jsonwebtoken.Claims;
import io.jsonwebtoken.ExpiredJwtException;
import io.jsonwebtoken.JwtParser;
import lombok.RequiredArgsConstructor;
import org.hankki.hankkiserver.common.code.AuthErrorCode;
import org.hankki.hankkiserver.common.exception.UnauthorizedException;
import org.springframework.stereotype.Component;

import java.net.URI;

import static org.hankki.hankkiserver.auth.filter.JwtAuthenticationFilter.BEARER;

@RequiredArgsConstructor
Expand All @@ -17,7 +19,10 @@ public class JwtValidator {

public void validateAccessToken(String accessToken) {
try {
parseToken(accessToken);
String role = parseToken(accessToken).get(JwtGenerator.USER_ROLE_CLAIM_NAME, String.class);
if (role == null) {
throw new UnauthorizedException(AuthErrorCode.INVALID_ACCESS_TOKEN_VALUE);
}
} catch (ExpiredJwtException e) {
throw new UnauthorizedException(AuthErrorCode.EXPIRED_ACCESS_TOKEN);
} catch (Exception e) {
Expand All @@ -27,6 +32,7 @@ public void validateAccessToken(String accessToken) {

public void validateRefreshToken(final String refreshToken) {
try {
System.out.println("refreshToken" + refreshToken);
parseToken(getToken(refreshToken));
} catch (ExpiredJwtException e) {
throw new UnauthorizedException(AuthErrorCode.EXPIRED_REFRESH_TOKEN);
Expand All @@ -43,15 +49,14 @@ public void equalsRefreshToken(
}
}

private void parseToken(String token) {
JwtParser jwtParser = jwtGenerator.getJwtParser();
jwtParser.parseClaimsJws(token);
}

private String getToken(final String refreshToken) {
if (refreshToken.startsWith(BEARER)) {
return refreshToken.substring(BEARER.length());
}
throw new UnauthorizedException(AuthErrorCode.MISSING_BEARER_PREFIX);
}

private Claims parseToken(final String token) {
return jwtGenerator.getJwtParser().parseClaimsJws(token).getBody();
}
}
Original file line number Diff line number Diff line change
@@ -1,7 +1,6 @@
package org.hankki.hankkiserver.common.exception;

import lombok.Getter;
import org.hankki.hankkiserver.common.code.AuthErrorCode;
import org.hankki.hankkiserver.common.code.ErrorCode;

@Getter
Expand All @@ -12,6 +11,5 @@ public UnauthorizedException(ErrorCode errorCode) {
super(errorCode.getMessage());
this.errorCode = errorCode;
}

}

Loading