Skip to content
Merged
Show file tree
Hide file tree
Changes from 1 commit
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
73 changes: 73 additions & 0 deletions src/main/java/com/example/loopitbe/config/SecurityConfig.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,73 @@
package com.example.loopitbe.config;

import com.example.loopitbe.jwt.JwtAuthenticationFilter;
import com.example.loopitbe.jwt.JwtProvider;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.HttpMethod;
import org.springframework.http.HttpStatus;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configurers.AbstractHttpConfigurer;
import org.springframework.security.config.http.SessionCreationPolicy;
import org.springframework.security.web.SecurityFilterChain;
import org.springframework.security.web.authentication.HttpStatusEntryPoint;
import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter;

@Configuration
@EnableWebSecurity
public class SecurityConfig {

private final JwtProvider jwtProvider;

public SecurityConfig(JwtProvider jwtProvider) {
this.jwtProvider = jwtProvider;
}

@Bean
public SecurityFilterChain filterChain(HttpSecurity http) throws Exception {

http
// 1. CSRF 비활성화 (JWT 사용)
.csrf(AbstractHttpConfigurer::disable)

// 2. 세션 사용 안 함
.sessionManagement(session ->
session.sessionCreationPolicy(SessionCreationPolicy.STATELESS)
)

// 3. Form Login, Basic Http 비활성화
.formLogin(AbstractHttpConfigurer::disable)
.httpBasic(AbstractHttpConfigurer::disable)

// 인증 실패 시 401(Unauthorized) 반환 설정
.exceptionHandling(exception -> exception
.authenticationEntryPoint(new HttpStatusEntryPoint(HttpStatus.UNAUTHORIZED))
)

// 4. 인증/인가 규칙
.authorizeHttpRequests(auth -> auth
// auth 관련 API는 허용
.requestMatchers(
"/kakao-callback.html", // 로컬 테스트용
"/auth/**",
"/swagger-ui/**",
"/v3/api-docs/**"
).permitAll()

// OPTIONS 요청 허용
.requestMatchers(HttpMethod.OPTIONS, "/**").permitAll()

// 나머지는 인증 필요
.anyRequest().authenticated()
)

// JWT 필터 등록
.addFilterBefore(
new JwtAuthenticationFilter(jwtProvider),
UsernamePasswordAuthenticationFilter.class
);

return http.build();
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,58 @@
package com.example.loopitbe.jwt;

import jakarta.servlet.FilterChain;
import jakarta.servlet.ServletException;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.util.StringUtils;
import org.springframework.web.filter.OncePerRequestFilter;

import java.io.IOException;
import java.util.List;

public class JwtAuthenticationFilter extends OncePerRequestFilter {

private final JwtProvider jwtProvider;

public JwtAuthenticationFilter(JwtProvider jwtProvider) {
this.jwtProvider = jwtProvider;
}

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

String accessToken = resolveToken(request);

if (accessToken != null && jwtProvider.validateToken(accessToken)) {
Long userId = jwtProvider.getUserId(accessToken);

UsernamePasswordAuthenticationToken authentication =
new UsernamePasswordAuthenticationToken(
userId, // principal
null,
List.of(new SimpleGrantedAuthority("ROLE_USER"))
);

SecurityContextHolder.getContext().setAuthentication(authentication);
}

filterChain.doFilter(request, response);
}

private String resolveToken(HttpServletRequest request) {
String bearerToken = request.getHeader("Authorization");

if (StringUtils.hasText(bearerToken) && bearerToken.startsWith("Bearer ")) {
return bearerToken.substring(7);
}

return null;
}
}
49 changes: 46 additions & 3 deletions src/main/java/com/example/loopitbe/jwt/JwtProvider.java
Original file line number Diff line number Diff line change
@@ -1,24 +1,43 @@
package com.example.loopitbe.jwt;

import io.jsonwebtoken.Claims;
import io.jsonwebtoken.JwtException;
import io.jsonwebtoken.*;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;
import io.jsonwebtoken.security.Keys;
import jakarta.annotation.PostConstruct;
import org.springframework.stereotype.Component;

import javax.crypto.SecretKey;
import java.nio.charset.StandardCharsets;
import java.util.Date;

@Component
public class JwtProvider {

private final String secretKey = System.getenv("JWT_TOKEN");
private final String secretKeyString = System.getenv("JWT_TOKEN");
private SecretKey secretKey;

private final long ACCESS_TOKEN_EXPIRE = 1000L * 60 * 30; // 30분
private final long REFRESH_TOKEN_EXPIRE = 1000L * 60 * 60 * 24 * 7; // 7일

@PostConstruct
public void init() {
// 환경변수가 비어있을 경우를 대비한 방어 로직 (선택사항)
if (secretKeyString == null || secretKeyString.length() < 32) {
throw new RuntimeException("JWT_TOKEN 환경변수가 설정되지 않았거나 32자(256bit) 미만입니다.");
}
// String -> Key 객체 변환 (UTF-8 바이트 처리)
this.secretKey = Keys.hmacShaKeyFor(secretKeyString.getBytes(StandardCharsets.UTF_8));
}

public String createAccessToken(Long userId) {
return Jwts.builder()
.setSubject(String.valueOf(userId))
.setIssuedAt(new Date())
.setExpiration(new Date(System.currentTimeMillis() + ACCESS_TOKEN_EXPIRE))
.signWith(SignatureAlgorithm.HS256, secretKey)
.signWith(secretKey, SignatureAlgorithm.HS256)
.compact();
}

Expand All @@ -27,7 +46,31 @@ public String createRefreshToken(Long userId) {
.setSubject(String.valueOf(userId))
.setIssuedAt(new Date())
.setExpiration(new Date(System.currentTimeMillis() + REFRESH_TOKEN_EXPIRE))
.signWith(SignatureAlgorithm.HS256, secretKey)
.signWith(secretKey, SignatureAlgorithm.HS256)
.compact();
}

// security
public boolean validateToken(String token) {
try {
Jwts.parserBuilder()
.setSigningKey(secretKey)
.build()
.parseClaimsJws(token);
return true;
} catch (JwtException | IllegalArgumentException e) {
System.out.println("JWT Validation Error: " + e.getMessage());
return false;
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

혹시 위 케이스에 대한 커스텀 예외처리하는 부분이 있을까요? 없다면 추가하는게 좋아보입니다!👍

}
}

public Long getUserId(String token) {
Claims claims = Jwts.parserBuilder()
.setSigningKey(secretKey)
.build()
.parseClaimsJws(token)
.getBody();

return Long.valueOf(claims.getSubject());
}
}