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
22 changes: 13 additions & 9 deletions src/main/java/com/somemore/auth/jwt/filter/JwtAuthFilter.java
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,8 @@
import jakarta.servlet.ServletException;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.List;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.security.core.Authentication;
Expand All @@ -17,9 +19,6 @@
import org.springframework.stereotype.Component;
import org.springframework.web.filter.OncePerRequestFilter;

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

@RequiredArgsConstructor
@Slf4j
@Component
Expand All @@ -29,12 +28,13 @@ public class JwtAuthFilter extends OncePerRequestFilter {

@Override
protected boolean shouldNotFilter(HttpServletRequest request) {
return true; // 개발 중 모든 요청 허용
// return httpServletRequest.getRequestURI().contains("token");
String token = request.getHeader("Authorization");
return token == null || token.isEmpty();
}

@Override
protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws ServletException, IOException {
protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response,
FilterChain filterChain) throws ServletException, IOException {
EncodedToken accessToken = getAccessToken(request);
jwtUseCase.processAccessToken(accessToken, response);

Expand All @@ -47,15 +47,19 @@ protected void doFilterInternal(HttpServletRequest request, HttpServletResponse

private EncodedToken getAccessToken(HttpServletRequest request) {
String accessToken = request.getHeader("Authorization");
if (accessToken == null || accessToken.isEmpty()) {
if (!accessToken.startsWith("Bearer ")) {
throw new JwtException(JwtErrorType.MISSING_TOKEN);
}

accessToken = accessToken.substring(7);

return new EncodedToken(accessToken);
Comment on lines +50 to 56
Copy link
Collaborator

Choose a reason for hiding this comment

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

이 부분은 제가 더 직관적으로 수정해보겠습니다! 그대로 올려주셔도 무방합니다.

}

private JwtAuthenticationToken createAuthenticationToken(Claims claims, EncodedToken accessToken) {
private JwtAuthenticationToken createAuthenticationToken(Claims claims,
EncodedToken accessToken) {
String userId = claims.get("id", String.class);
UserRole role = claims.get("role", UserRole.class);
UserRole role = UserRole.valueOf(claims.get("role", String.class));

return new JwtAuthenticationToken(
userId,
Expand Down
99 changes: 99 additions & 0 deletions src/main/java/com/somemore/auth/util/DevAccountSetUpConfig.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,99 @@
package com.somemore.auth.util;

import static com.somemore.auth.oauth.OAuthProvider.NAVER;

import com.somemore.auth.jwt.domain.EncodedToken;
import com.somemore.auth.jwt.domain.TokenType;
import com.somemore.auth.jwt.domain.UserRole;
import com.somemore.auth.jwt.generator.JwtGenerator;
import com.somemore.auth.jwt.refresh.domain.RefreshToken;
import com.somemore.auth.jwt.refresh.manager.RefreshTokenManager;
import com.somemore.center.domain.Center;
import com.somemore.center.repository.CenterJpaRepository;
import com.somemore.volunteer.domain.Volunteer;
import com.somemore.volunteer.repository.VolunteerJpaRepository;
import jakarta.annotation.PostConstruct;
import jakarta.annotation.PreDestroy;
import java.util.UUID;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

@Slf4j
@RequiredArgsConstructor
@Component
public class DevAccountSetUpConfig {

private final VolunteerJpaRepository volunteerRepository;
private final CenterJpaRepository centerRepository;
private final JwtGenerator jwtGenerator;
private final RefreshTokenManager refreshTokenManager;

private Volunteer volunteer;
private Center center;

@Value("${app.develop.mode:false}")
private boolean developMode;

@PostConstruct
public void generateAccessTokenForDev() {
if (!developMode) {
return; // 개발 모드에서만 실행
}

volunteer = Volunteer.createDefault(NAVER, "bongdari");
center = Center.create(
"봉다리 자원봉사센터",
"02-1234-5678",
"",
"봉다리 기관 테스트 계정입니다.",
"https://somemore.bongdari.com",
"bongdari",
"1234"
);

volunteer = volunteerRepository.findByOauthId(volunteer.getOauthId())
.orElseGet(() -> volunteerRepository.save(volunteer));

center = centerRepository.findByName(center.getName())
.orElseGet(() -> centerRepository.save(center));

EncodedToken volunteerToken = saveRefreshTokenAndReturnAccessToken(volunteer.getId(),
UserRole.VOLUNTEER);
EncodedToken centerToken = saveRefreshTokenAndReturnAccessToken(center.getId(),
UserRole.CENTER);

log.info("테스트용 봉사자 AccessToken: {}", volunteerToken.value());
log.info("테스트용 기관 AccessToken: {}", centerToken.value());
}

@PreDestroy
public void cleanup() {
if (volunteer != null) {
refreshTokenManager.removeRefreshToken(volunteer.getId().toString());
log.info("테스트용 AccessToken 제거, 봉사자 ID: {}", volunteer.getId());
}
if (center != null) {
refreshTokenManager.removeRefreshToken(center.getId().toString());
log.info("테스트용 AccessToken 제거, 기관 ID: {}", center.getId());
}
}

private EncodedToken saveRefreshTokenAndReturnAccessToken(UUID id, UserRole role) {
EncodedToken accessToken = generateToken(id, role, TokenType.ACCESS);
RefreshToken refreshToken = generateRefreshToken(id, role, accessToken);
refreshTokenManager.save(refreshToken);
return accessToken;
}

private EncodedToken generateToken(UUID id, UserRole role, TokenType tokenType) {
return jwtGenerator.generateToken(id.toString(), role.name(), tokenType);
}

private RefreshToken generateRefreshToken(UUID id, UserRole role, EncodedToken accessToken) {
return new RefreshToken(id.toString(), accessToken,
generateToken(id, role, TokenType.REFRESH));
}
}

Original file line number Diff line number Diff line change
Expand Up @@ -9,4 +9,5 @@
public interface CenterJpaRepository extends JpaRepository<Center, Long> {
boolean existsById(UUID id);
Optional<Center> findCenterById(UUID id);
Optional<Center> findByName(String name);
}
36 changes: 36 additions & 0 deletions src/main/java/com/somemore/global/configure/SwaggerConfig.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,36 @@
package com.somemore.global.configure;

import io.swagger.v3.oas.models.Components;
import io.swagger.v3.oas.models.OpenAPI;
import io.swagger.v3.oas.models.info.Info;
import io.swagger.v3.oas.models.security.SecurityRequirement;
import io.swagger.v3.oas.models.security.SecurityScheme;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

@Configuration
public class SwaggerConfig {

@Bean
public OpenAPI customOpenAPI() {
SecurityScheme securityScheme = new SecurityScheme()
.type(SecurityScheme.Type.HTTP)
.scheme("bearer")
.bearerFormat("JWT")
.description("JWT 토큰을 이용한 인증");

SecurityRequirement securityRequirement = new SecurityRequirement()
.addList("AccessToken");

return new OpenAPI()
.info(new Info()
.title("Somemore API")
.version("1.0")
.description("Somemore swagger-ui 화면입니다.")
)
.components(new Components()
.addSecuritySchemes("AccessToken", securityScheme)
)
.addSecurityItem(securityRequirement);
}
}
2 changes: 2 additions & 0 deletions src/main/resources/application.yml
Original file line number Diff line number Diff line change
@@ -1,6 +1,8 @@
app:
front-url: ${FRONT_URL}
back-url: ${BACK_URL}
develop:
mode: ${APP_DEVELOP_MODE}

# AWS S3
cloud:
Expand Down
2 changes: 2 additions & 0 deletions src/test/resources/application-test.yml
Original file line number Diff line number Diff line change
@@ -1,6 +1,8 @@
app:
front-url: "http://localhost:3000"
back-url: "http://localhost:8080"
develop:
mode: false

spring:
config:
Expand Down