Skip to content
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
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();
}
}
6 changes: 5 additions & 1 deletion src/main/java/com/example/loopitbe/exception/ErrorCode.java
Original file line number Diff line number Diff line change
Expand Up @@ -7,8 +7,12 @@ public enum ErrorCode {
DUPLICATED_NICKNAME(HttpStatus.CONFLICT, "중복된 닉네임 입니다."),
KAKAO_AUTHENTICATED_FAILED(HttpStatus.BAD_REQUEST, "카카오 인증에 실패하였습니다."),
JSON_PARSE_ERROR(HttpStatus.BAD_REQUEST, "OAuth 인증 중 Json 파싱에 실패하였습니다."),
INVALID_ACCESS_TOKEN(HttpStatus.UNAUTHORIZED, "유효하지 않은 액세스 토큰입니다."),
INVALID_REFRESH_TOKEN(HttpStatus.UNAUTHORIZED, "유효하지 않은 리프레시 토큰입니다."),
EXPIRED_REFRESH_TOKEN(HttpStatus.UNAUTHORIZED, "만료된 리프레시 토큰입니다.");
EXPIRED_ACCESS_TOKEN(HttpStatus.UNAUTHORIZED, "만료된 액세스 토큰입니다."),
EXPIRED_REFRESH_TOKEN(HttpStatus.UNAUTHORIZED, "만료된 리프레시 토큰입니다."),
UNSUPPORTED_JWT(HttpStatus.UNAUTHORIZED, "지원되지 않는 JWT 토큰입니다."),
EMPTY_JWT(HttpStatus.UNAUTHORIZED, "JWT 토큰이 비어있거나 잘못되었습니다.");

private final HttpStatus status;
private final String message;
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,64 @@
package com.example.loopitbe.jwt;

import com.example.loopitbe.exception.CustomException;
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);

try {
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);
}
} catch (CustomException e) {
SecurityContextHolder.clearContext(); // 401 에러 발생 유도
request.setAttribute("exception", e.getErrorCode()); // 에러코드 전달
}

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;
}
}
55 changes: 52 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,44 @@
package com.example.loopitbe.jwt;

import com.example.loopitbe.exception.CustomException;
import com.example.loopitbe.exception.ErrorCode;
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 객체 변환
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 +47,36 @@ 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 (io.jsonwebtoken.security.SecurityException | MalformedJwtException e) {
throw new CustomException(ErrorCode.INVALID_ACCESS_TOKEN);
} catch (ExpiredJwtException e) {
throw new CustomException(ErrorCode.EXPIRED_ACCESS_TOKEN);
} catch (UnsupportedJwtException e) {
throw new CustomException(ErrorCode.UNSUPPORTED_JWT);
} catch (IllegalArgumentException e) {
throw new CustomException(ErrorCode.EMPTY_JWT);
}
}

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

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