Skip to content

Commit

Permalink
Merge pull request #138 from ttakkeun/refac
Browse files Browse the repository at this point in the history
[Refac]application 환경변수명 수정
  • Loading branch information
do-dop authored Oct 24, 2024
2 parents 12e0ba6 + 1a3c12c commit 5f984c9
Show file tree
Hide file tree
Showing 5 changed files with 29 additions and 31 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -40,7 +40,8 @@ public WebSecurityCustomizer webSecurityCustomizer(){
"/api/diagnose/result/**", "/test/diagnose/**", "/api/ChatGPT/**");
}

@Bean AuthenticationManager authenticationManager(AuthenticationConfiguration authConfiguration) throws Exception
@Bean
AuthenticationManager authenticationManager(AuthenticationConfiguration authConfiguration) throws Exception
{ return authConfiguration.getAuthenticationManager(); }

@Bean
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@
import org.springframework.cloud.openfeign.FeignClient;
import org.springframework.web.bind.annotation.GetMapping;

@FeignClient(name = "appleClient1", url = "https://appleid.apple.com/auth/keys")
@FeignClient(name = "appleClient", url = "https://appleid.apple.com/auth/keys")
public interface AppleAuthClient {
@GetMapping
ApplePublicKeyResponse getAppleAuthPublicKey();
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -26,41 +26,39 @@

@Slf4j
public class JwtAuthenticationFilter extends BasicAuthenticationFilter{
public static final String AUTHORIZATION_HEADER = "Authorization";

private JwtService jwtService;

public JwtAuthenticationFilter(AuthenticationManager authenticationManager, JwtService jwtService) {
super(authenticationManager);
this.jwtService =jwtService;

}


@Override
protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain chain) throws IOException, ServletException {

// 헤더에서 토큰 가져오기
String token = jwtService.resolveToken(request);
String requestURI = request.getRequestURI();
//String requestURI = request.getRequestURI();

// 토큰이 존재 여부 및 토큰 검증
// 토큰 존재 여부 및 토큰 검증
if (StringUtils.isNotEmpty(token)) {
if (jwtService.validateTokenBoolean(token)) {
logger.info("토큰 검증");

//유효한 토큰을 통해 사용자 정보 추출
Authentication authentication = jwtService.getAuthentication(token);

// Security 세션에 등록
//SecurityContext에 인증 정보 저장
SecurityContextHolder.getContext().setAuthentication(authentication);
request.setAttribute("username", authentication.getName());
logger.info("Security Context에 인증 정보를 저장했습니다, uri: {}");
logger.info("SecurityContext에 인증 정보를 저장했습니다");
} else {
logger.info("유효한 JWT 토큰이 없습니다, uri: {}");
// 유효하지 않은 토큰 처리
throw new ExpiredJwtException(null, null, "유효하지 않은 Access Token입니다.");
throw new ExpiredJwtException(null, null, "유효하지 않은 AccessToken 입니다.");
}
} else {
logger.warn("Authorization 헤더가 없거나 비어 있습니다, uri: {}");
logger.warn("Authorization 헤더가 없거나 비어 있습니다");
}

chain.doFilter(request, response);
Expand Down
22 changes: 11 additions & 11 deletions src/main/java/ttakkeun/ttakkeun_server/service/JwtService.java
Original file line number Diff line number Diff line change
Expand Up @@ -41,12 +41,14 @@ public class JwtService {
@Value("${jwt.secretKey}") //application.yml에 저장된 시크릿키
private String JWT_SECRET;

public static final String AUTHORIZATION_HEADER = "Authorization";


private final UserDetailServiceImpl userDetailService;
private static final String IDENTITY_TOKEN_VALUE_DELIMITER = "\\.";
private static final int HEADER_INDEX = 0;

private final ObjectMapper objectMapper;
//private final UserDetailServiceImpl userDetailService;

private Long accesstokenValidTime = 1000L * 60 * 60 * 24; // 1d
private Long refreshTokenValidTime = 1000L * 60 * 60 * 24 * 7; // 7d
Expand All @@ -65,15 +67,15 @@ private Key getKeyFromBase64EncodedKey(String base64EncodedSecretKey) {
// access token 생성
public String generateAccessToken(Long memberId) {
Date now = new Date();
String base64EncodedSecretKey = encodeBase64SecretKey("" + JWT_SECRET);
Key key = getKeyFromBase64EncodedKey(base64EncodedSecretKey);
String base64EncodedSecretKey = encodeBase64SecretKey("" + JWT_SECRET); //사용자 설정 secret 키 인코딩
Key key = getKeyFromBase64EncodedKey(base64EncodedSecretKey); //JWT 서명에 사용할 키 생성

return Jwts.builder()
.setHeaderParam(Header.TYPE, Header.JWT_TYPE) // JWT 헤더 설정, "typ" : "JWT"
.setIssuer("ttakkeun") // 발행자 설정
.setIssuedAt(now) // JWT 발행 일자 설정
.setSubject(String.valueOf(memberId)) // JWT 제목 설정
.setExpiration(new Date(now.getTime() + accesstokenValidTime)) // JWT 만료 일자 설정
.setSubject(String.valueOf(memberId)) // JWT sub 설정
.setExpiration(new Date(now.getTime() + accesstokenValidTime)) // JWT 만료 일자 설정(1d)
.claim("memberId", memberId) // 커스텀 클레임 설정
.signWith(key) // 서명을 위한 Key 객체 설정
.compact(); // JWT 생성 및 직렬화
Expand All @@ -89,7 +91,7 @@ public String generateRefreshToken(Long memberId) {
.setIssuedAt(now)
.setSubject(memberId.toString())
.setExpiration(new Date(now.getTime() + refreshTokenValidTime))
.claim("memberId", memberId) //payload에 들어갈 내용
.claim("memberId", memberId)
.signWith(key)
.compact();
}
Expand All @@ -111,9 +113,9 @@ public Long getMemberIdFromJwtToken(String token) {
}
}

// Autorization : Bearer에서 token 추출 (refreshToken, accessToken 포함)
// token 추출
public String resolveToken(HttpServletRequest request) {
String bearerToken = request.getHeader("Authorization");
String bearerToken = request.getHeader(AUTHORIZATION_HEADER);
if (bearerToken != null && bearerToken.startsWith("Bearer ")) {
return bearerToken.substring(7);
}
Expand Down Expand Up @@ -141,8 +143,6 @@ public Boolean validateTokenBoolean(String token) {

//JWT 토큰 인증 정보 조회 (토큰 복호화)
public Authentication getAuthentication(String token) {
System.out.println(this.getMemberIdFromJwtToken(token));

UserDetails userDetails = userDetailService.loadUserByUsername(this.getMemberIdFromJwtToken(token).toString());
return new UsernamePasswordAuthenticationToken(userDetails, token, userDetails.getAuthorities());
}
Expand All @@ -153,7 +153,7 @@ public Map<String, String> parseHeader(final String appleToken) {
final String decodedHeader = new String(Base64.getUrlDecoder().decode(encodedHeader));
return objectMapper.readValue(decodedHeader, Map.class);
} catch (JsonMappingException e) {
throw new RuntimeException("appleToken 값이 jwt 형식인지, 값이 정상적인지 확인해주세요.");
throw new RuntimeException("apple token 값이 jwt 형식인지, 값이 정상적인지 확인해주세요.");
} catch (JsonProcessingException e) {
throw new ExceptionHandler(ErrorStatus.INVALID_APPLE_ID_TOKEN);
}
Expand Down
15 changes: 7 additions & 8 deletions src/main/resources/application.yml
Original file line number Diff line number Diff line change
Expand Up @@ -23,12 +23,11 @@ spring:
provider:
apple:
redirect-uri: https://ttakkeun.app.com/apple/callback/
grant-type: authorization_code
client-id: ttakkeun.app.com
key-id: ${apple_key_id}
team-id: ${apple_team_id}
client-id: ${APPLE_CLIENT_ID}
key-id: ${APPLE_KEY_ID}
team-id: ${APPLE_TEAM_ID}
audience: https://appleid.apple.com
private-key: ${APPLE_Secret}
private-key: ${APPLE_SECRET}
servlet:
multipart:
max-file-size: 50MB
Expand All @@ -37,7 +36,7 @@ spring:
jackson:
time-zone: Asia/Seoul
jwt:
secretKey: ${JWT_Secret}
secretKey: ${JWT_SECRET}

server:
port: 8080
Expand All @@ -49,8 +48,8 @@ naverApi:
cloud:
aws:
credentials:
access-key: ${aws_access}
secret-key: ${aws_secret}
access-key: ${AWS_ACCESS}
secret-key: ${AWS_SECRET}
region:
static: ap-northeast-2
# 리전 서울로 설정
Expand Down

0 comments on commit 5f984c9

Please sign in to comment.