-
Notifications
You must be signed in to change notification settings - Fork 1
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
- Loading branch information
Showing
9 changed files
with
292 additions
and
12 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
61 changes: 61 additions & 0 deletions
61
main/src/main/java/org/sopt/makers/crew/main/common/config/SecurityConfig.java
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,61 @@ | ||
package org.sopt.makers.crew.main.common.config; | ||
|
||
import lombok.RequiredArgsConstructor; | ||
import org.sopt.makers.crew.main.common.config.jwt.JwtAuthenticationEntryPoint; | ||
import org.sopt.makers.crew.main.common.config.jwt.JwtAuthenticationFilter; | ||
import org.sopt.makers.crew.main.common.config.jwt.JwtTokenProvider; | ||
import org.springframework.context.annotation.Bean; | ||
import org.springframework.context.annotation.Configuration; | ||
import org.springframework.context.annotation.Profile; | ||
import org.springframework.security.config.annotation.web.builders.HttpSecurity; | ||
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity; | ||
import org.springframework.security.config.http.SessionCreationPolicy; | ||
import org.springframework.security.web.SecurityFilterChain; | ||
import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter; | ||
|
||
@Configuration | ||
@RequiredArgsConstructor | ||
@EnableWebSecurity | ||
public class SecurityConfig { | ||
|
||
private final JwtTokenProvider jwtTokenProvider; | ||
private final JwtAuthenticationEntryPoint jwtAuthenticationEntryPoint; | ||
|
||
private static final String[] SWAGGER_URL = { | ||
"/swagger-resources/**", | ||
"/favicon.ico", | ||
"/api-docs/**", | ||
"/swagger-ui/**", | ||
"/swagger-ui.html", | ||
"/swagger-ui/index.html", | ||
"/docs/swagger-ui/index.html", | ||
"/swagger-ui/swagger-ui.css", | ||
}; | ||
|
||
private static final String[] AUTH_WHITELIST = { | ||
"/health" | ||
}; | ||
|
||
@Bean | ||
@Profile("dev") | ||
SecurityFilterChain prodSecurityFilterChain(HttpSecurity http) throws Exception { | ||
return http.csrf((csrfConfig) -> | ||
csrfConfig.disable() | ||
) | ||
.sessionManagement((sessionManagement) -> | ||
sessionManagement.sessionCreationPolicy(SessionCreationPolicy.STATELESS) | ||
) | ||
.authorizeHttpRequests( | ||
authorize -> authorize.requestMatchers(AUTH_WHITELIST).permitAll() | ||
.requestMatchers(SWAGGER_URL).permitAll() | ||
.anyRequest().authenticated() | ||
) | ||
.addFilterBefore(new JwtAuthenticationFilter(jwtTokenProvider, jwtAuthenticationEntryPoint), | ||
UsernamePasswordAuthenticationFilter.class) | ||
.exceptionHandling(exceptionHandling -> | ||
exceptionHandling.authenticationEntryPoint(jwtAuthenticationEntryPoint) | ||
) | ||
.build(); | ||
} | ||
|
||
} |
33 changes: 33 additions & 0 deletions
33
...rc/main/java/org/sopt/makers/crew/main/common/config/jwt/JwtAuthenticationEntryPoint.java
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,33 @@ | ||
package org.sopt.makers.crew.main.common.config.jwt; | ||
|
||
import com.fasterxml.jackson.databind.ObjectMapper; | ||
import jakarta.servlet.http.HttpServletRequest; | ||
import jakarta.servlet.http.HttpServletResponse; | ||
import java.io.IOException; | ||
import org.sopt.makers.crew.main.common.response.CommonResponseDto; | ||
import org.sopt.makers.crew.main.common.response.ErrorStatus; | ||
import org.springframework.security.core.AuthenticationException; | ||
import org.springframework.security.web.AuthenticationEntryPoint; | ||
import org.springframework.stereotype.Component; | ||
|
||
@Component | ||
public class JwtAuthenticationEntryPoint implements AuthenticationEntryPoint { | ||
|
||
private final ObjectMapper mapper = new ObjectMapper(); | ||
|
||
@Override | ||
public void commence(HttpServletRequest request, HttpServletResponse response, | ||
AuthenticationException authException) throws IOException { | ||
setResponse(response, ErrorStatus.UNAUTHORIZED_TOKEN); | ||
} | ||
|
||
|
||
public void setResponse(HttpServletResponse response, ErrorStatus status) throws IOException { | ||
response.setContentType("application/json;charset=UTF-8"); | ||
response.setStatus(HttpServletResponse.SC_UNAUTHORIZED); | ||
|
||
CommonResponseDto apiResponse = CommonResponseDto.fail(status.getErrorCode()); | ||
response.getWriter().println(mapper.writeValueAsString(apiResponse)); | ||
} | ||
|
||
} |
49 changes: 49 additions & 0 deletions
49
main/src/main/java/org/sopt/makers/crew/main/common/config/jwt/JwtAuthenticationFilter.java
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,49 @@ | ||
package org.sopt.makers.crew.main.common.config.jwt; | ||
|
||
import static org.sopt.makers.crew.main.common.config.jwt.JwtExceptionType.VALID_JWT_TOKEN; | ||
|
||
import jakarta.servlet.FilterChain; | ||
import jakarta.servlet.ServletException; | ||
import jakarta.servlet.http.HttpServletRequest; | ||
import jakarta.servlet.http.HttpServletResponse; | ||
import java.io.IOException; | ||
import lombok.RequiredArgsConstructor; | ||
import org.sopt.makers.crew.main.common.response.ErrorStatus; | ||
import org.springframework.security.core.AuthenticationException; | ||
import org.springframework.security.core.context.SecurityContextHolder; | ||
import org.springframework.security.web.authentication.WebAuthenticationDetailsSource; | ||
import org.springframework.stereotype.Component; | ||
import org.springframework.web.filter.OncePerRequestFilter; | ||
|
||
@Component | ||
@RequiredArgsConstructor | ||
public class JwtAuthenticationFilter extends OncePerRequestFilter { | ||
|
||
private final JwtTokenProvider jwtTokenProvider; | ||
private final JwtAuthenticationEntryPoint jwtAuthenticationEntryPoint; | ||
|
||
@Override | ||
protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, | ||
FilterChain chain) throws ServletException, IOException { | ||
String accessToken = jwtTokenProvider.resolveToken(request); | ||
|
||
if (accessToken != null) { | ||
// 토큰 검증 | ||
if (jwtTokenProvider.validateToken(accessToken) | ||
== VALID_JWT_TOKEN) { // 토큰이 존재하고 유효한 토큰일 때만 | ||
Integer userId = jwtTokenProvider.getAccessTokenPayload(accessToken); | ||
UserAuthentication authentication = new UserAuthentication(userId, null, | ||
null); //사용자 객체 생성 | ||
authentication.setDetails(new WebAuthenticationDetailsSource().buildDetails( | ||
request)); // request 정보로 사용자 객체 디테일 설정 | ||
SecurityContextHolder.getContext().setAuthentication(authentication); | ||
} else { | ||
jwtAuthenticationEntryPoint.commence(request, response, | ||
new AuthenticationException(ErrorStatus.UNAUTHORIZED_TOKEN.getErrorCode()) { | ||
}); | ||
return; | ||
} | ||
} | ||
chain.doFilter(request, response); | ||
} | ||
} |
10 changes: 10 additions & 0 deletions
10
main/src/main/java/org/sopt/makers/crew/main/common/config/jwt/JwtExceptionType.java
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,10 @@ | ||
package org.sopt.makers.crew.main.common.config.jwt; | ||
|
||
public enum JwtExceptionType { | ||
VALID_JWT_TOKEN, // 유효한 JWT | ||
INVALID_JWT_SIGNATURE, // 유효하지 않은 서명 | ||
INVALID_JWT_TOKEN, // 유효하지 않은 토큰 | ||
EXPIRED_JWT_TOKEN, // 만료된 토큰 | ||
UNSUPPORTED_JWT_TOKEN, // 지원하지 않는 형식의 토큰 | ||
EMPTY_JWT // 빈 JWT | ||
} |
98 changes: 98 additions & 0 deletions
98
main/src/main/java/org/sopt/makers/crew/main/common/config/jwt/JwtTokenProvider.java
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,98 @@ | ||
package org.sopt.makers.crew.main.common.config.jwt; | ||
|
||
import io.jsonwebtoken.Claims; | ||
import io.jsonwebtoken.ExpiredJwtException; | ||
import io.jsonwebtoken.Header; | ||
import io.jsonwebtoken.Jwts; | ||
import io.jsonwebtoken.MalformedJwtException; | ||
import io.jsonwebtoken.SignatureAlgorithm; | ||
import io.jsonwebtoken.UnsupportedJwtException; | ||
import jakarta.servlet.http.HttpServletRequest; | ||
import java.nio.charset.StandardCharsets; | ||
import java.security.Key; | ||
import java.util.Date; | ||
import javax.crypto.spec.SecretKeySpec; | ||
import lombok.RequiredArgsConstructor; | ||
import lombok.extern.slf4j.Slf4j; | ||
import org.sopt.makers.crew.main.entity.user.UserRepository; | ||
import org.springframework.beans.factory.annotation.Value; | ||
import org.springframework.security.core.Authentication; | ||
import org.springframework.stereotype.Component; | ||
|
||
@Slf4j | ||
@Component | ||
@RequiredArgsConstructor | ||
public class JwtTokenProvider { | ||
|
||
private final UserRepository userRepository; | ||
|
||
@Value("${JWT_SECRET}") | ||
private String secretKey; | ||
|
||
@Value("${ACCESS_TOKEN_EXPIRED_TIME}") | ||
private Long accessTokenExpireLength; | ||
|
||
private static final String AUTHORIZATION_HEADER = "Authorization"; | ||
|
||
public String generateAccessToken(Authentication authentication) { | ||
Date now = new Date(); | ||
Date expiration = new Date(now.getTime() + accessTokenExpireLength); | ||
|
||
final Claims claims = Jwts.claims() | ||
.setIssuedAt(now) | ||
.setExpiration(expiration); | ||
|
||
claims.put("id", authentication.getPrincipal()); | ||
|
||
return Jwts.builder() | ||
.setHeaderParam(Header.TYPE, Header.JWT_TYPE) | ||
.setClaims(claims) | ||
.signWith(getSignKey(), SignatureAlgorithm.HS256) | ||
.compact(); | ||
} | ||
|
||
public Integer getAccessTokenPayload(String token) { | ||
return Integer.parseInt( | ||
Jwts.parserBuilder().setSigningKey(getSignKey()).build().parseClaimsJws(token) | ||
.getBody().get("id").toString()); | ||
} | ||
|
||
public String resolveToken(HttpServletRequest request) { | ||
|
||
String header = request.getHeader(AUTHORIZATION_HEADER); | ||
|
||
if (header == null || !header.startsWith("Bearer ")) { | ||
return null; | ||
} else { | ||
return header.split(" ")[1]; | ||
} | ||
} | ||
|
||
public JwtExceptionType validateToken(String token) { | ||
try { | ||
Jwts.parserBuilder().setSigningKey(getSignKey()).build().parseClaimsJws(token) | ||
.getBody(); | ||
return JwtExceptionType.VALID_JWT_TOKEN; | ||
} catch (io.jsonwebtoken.security.SignatureException exception) { | ||
log.error("잘못된 JWT 서명을 가진 토큰입니다."); | ||
return JwtExceptionType.INVALID_JWT_SIGNATURE; | ||
} catch (MalformedJwtException exception) { | ||
log.error("잘못된 JWT 토큰입니다."); | ||
return JwtExceptionType.INVALID_JWT_TOKEN; | ||
} catch (ExpiredJwtException exception) { | ||
log.error("만료된 JWT 토큰입니다."); | ||
return JwtExceptionType.EXPIRED_JWT_TOKEN; | ||
} catch (UnsupportedJwtException exception) { | ||
log.error("지원하지 않는 JWT 토큰입니다."); | ||
return JwtExceptionType.UNSUPPORTED_JWT_TOKEN; | ||
} catch (IllegalArgumentException exception) { | ||
log.error("JWT Claims가 비어있습니다."); | ||
return JwtExceptionType.EMPTY_JWT; | ||
} | ||
} | ||
|
||
private Key getSignKey() { | ||
byte[] keyBytes = secretKey.getBytes(StandardCharsets.UTF_8); | ||
return new SecretKeySpec(keyBytes, "HmacSHA256"); | ||
} | ||
} |
16 changes: 16 additions & 0 deletions
16
main/src/main/java/org/sopt/makers/crew/main/common/config/jwt/UserAuthentication.java
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,16 @@ | ||
package org.sopt.makers.crew.main.common.config.jwt; | ||
|
||
|
||
import java.util.Collection; | ||
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken; | ||
import org.springframework.security.core.GrantedAuthority; | ||
|
||
// UsernamePasswordAuthenticationToken: 사용자의 인증 정보 저장하고 전달 | ||
public class UserAuthentication extends UsernamePasswordAuthenticationToken { | ||
|
||
// 사용자 인증 객체 생성 | ||
public UserAuthentication(Object principal, Object credentials, | ||
Collection<? extends GrantedAuthority> authorities) { | ||
super(principal, credentials, authorities); | ||
} | ||
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters