Skip to content

Commit

Permalink
#40 - Refactor: jwt 관련 코드 리팩토링
Browse files Browse the repository at this point in the history
  • Loading branch information
ahah525 committed Nov 10, 2022
1 parent ad7198d commit b6b1040
Show file tree
Hide file tree
Showing 4 changed files with 19 additions and 14 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -171,7 +171,7 @@ public String genAccessToken(Member member) {
if (StringUtils.hasLength(accessToken) == false) {
// 지금으로부터 100년간의 유효기간을 가지는 토큰을 생성, DB에 토큰 저장
Map<String, Object> claims = member.getAccessTokenClaims();
accessToken = jwtProvider.generateAccessToken(claims, 60L * 60 * 24 * 365 * 100);
accessToken = jwtProvider.generateAccessToken(claims);
member.setAccessToken(accessToken);
}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -26,8 +26,14 @@ public SecurityFilterChain apiFilterChain(HttpSecurity http) throws Exception {
// .exceptionHandling(exceptionHandling -> exceptionHandling
// .authenticationEntryPoint(authenticationEntryPoint)
// )
// jwt 사용 기본 설정
.httpBasic().disable()
.formLogin().disable()
.csrf().disable()
.sessionManagement(sessionManagement -> sessionManagement
.sessionCreationPolicy(STATELESS)
)
// cors 허용 설정
.cors(cors -> cors
.configurationSource(corsConfigurationSource())
)
Expand All @@ -38,10 +44,7 @@ public SecurityFilterChain apiFilterChain(HttpSecurity http) throws Exception {
.anyRequest()
.authenticated() // 최소자격 : 로그인
)
.sessionManagement(sessionManagement -> sessionManagement
.sessionCreationPolicy(STATELESS)
)
.formLogin().disable()
// 필터 설정
.addFilterBefore(
jwtAuthorizationFilter,
UsernamePasswordAuthenticationFilter.class
Expand All @@ -51,13 +54,14 @@ public SecurityFilterChain apiFilterChain(HttpSecurity http) throws Exception {
return http.build();
}

// cors 허용 정책 설정
@Bean
public CorsConfigurationSource corsConfigurationSource() {
CorsConfiguration corsConfiguration = new CorsConfiguration();

corsConfiguration.addAllowedOrigin("*");
corsConfiguration.addAllowedHeader("*");
corsConfiguration.addAllowedMethod("*");
corsConfiguration.addAllowedOrigin("*"); // 모든 URL 허용
corsConfiguration.addAllowedHeader("*"); // 모든 Header 허용
corsConfiguration.addAllowedMethod("*"); // 모든 HTTP METHOD 허용

UrlBasedCorsConfigurationSource urlBasedCorsConfigurationSource = new UrlBasedCorsConfigurationSource();
urlBasedCorsConfigurationSource.registerCorsConfiguration("/api/**", corsConfiguration);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -34,11 +34,11 @@ public class JwtAuthorizationFilter extends OncePerRequestFilter {

@Override
protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws ServletException, IOException {
String barerToken = request.getHeader("Authorization");
String bearerToken = request.getHeader("Authorization");
// 1. 1차 체크(정보가 변조되지 않았는지 검증)
if(barerToken != null) {
// accessToken에서 회원 정보 가져오려면 Authentication에서 Bearer 제거 필요
String token = barerToken.substring("Bearer ".length());
if(bearerToken != null) {
// accessToken 에서 회원 정보 가져오려면 Authorization 에서 Bearer 제거 필요
String token = bearerToken.split(" ")[1];
// 토큰이 유효하면 회원 정보 얻어서 강제 로그인 처리
if(jwtProvider.verify(token)) {
Map<String, Object> claims = jwtProvider.getClaims(token);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -19,15 +19,16 @@
@RequiredArgsConstructor
public class JwtProvider {
private final SecretKey jwtSecretKey; // 비밀키
private long ACCESS_TOKEN_VALIDATION_SECOND = 60 * 60 * 24 * 365 * 100L; // accessToken 유효시간(100년)

private SecretKey getSecretKey() {
return jwtSecretKey;
}

// JWT Access Token 발급
public String generateAccessToken(Map<String, Object> claims, long seconds) {
public String generateAccessToken(Map<String, Object> claims) {
long now = new Date().getTime();
Date accessTokenExpiresIn = new Date(now + 1000L * seconds);
Date accessTokenExpiresIn = new Date(now + 1000L * ACCESS_TOKEN_VALIDATION_SECOND);

return Jwts.builder()
.claim("body", Ut.json.toStr(claims)) // Claims 정보 설정
Expand Down

0 comments on commit b6b1040

Please sign in to comment.