Skip to content
Merged
Show file tree
Hide file tree
Changes from 13 commits
Commits
Show all changes
38 commits
Select commit Hold shift + click to select a range
483f11b
feat: 시큐리티 메인, getCurrentUserId() 유틸 구현 (#25)
kimyw1018 Jul 21, 2026
cf73e51
feat: 시큐리티 전용 userdetails 및 service 구현 (#25)
kimyw1018 Jul 23, 2026
60fb0e8
feat: jwt 토큰 생성 및 유효성 검증 유틸리티 구현 (#25)
kimyw1018 Jul 23, 2026
7c67b37
feat: http 요청 토큰 검증을 위한 jwt 인증 필터 구현 (#25)
kimyw1018 Jul 23, 2026
e1e71c2
feat: hjwt 인증 실패 및 권한 부족 예외 핸들러 구현 (#25)
kimyw1018 Jul 23, 2026
346270b
feat: securityconfig 내 jwt 필터 및 예외 핸들러 체인 등록 (#25)
kimyw1018 Jul 23, 2026
17e5f51
feat: 소셜 로그인 api 및 비즈니스 로직 뼈대 구현(#25)
kimyw1018 Jul 23, 2026
ff23e22
Merge branch 'develop' of https://github.com/Musereview/BE into feat/…
kimyw1018 Jul 23, 2026
e48ba51
feat: 코드 스타일 정리 (#25)
kimyw1018 Jul 23, 2026
bd65765
feat: CommonStatus 내 UNAUTHORIZED, FORBIDDEN 상수 추가 (#25)
kimyw1018 Jul 23, 2026
7ba95bb
feat: 예외 코드 변경 (#25)
kimyw1018 Jul 23, 2026
da3a472
feat: 액세스, 리프레시 토근 구분 (#25)
kimyw1018 Jul 23, 2026
0b6a6bd
feat: 액세스토큰 검증 함수 명확히 (#25)
kimyw1018 Jul 23, 2026
4926638
feat: email속성 제거 (#25)
kimyw1018 Jul 24, 2026
a636bb4
feat: 유저 엔티티 연결 (#25)
kimyw1018 Jul 24, 2026
6613435
feat: 주석 처리 (#25)
kimyw1018 Jul 24, 2026
879730a
feat: 다음 작업 분리 (#25)
kimyw1018 Jul 24, 2026
3bfaaaa
feat: Base64 기준으로 수정 (#25)
kimyw1018 Jul 24, 2026
809047b
feat: 소셜 로그인 구현 전 방어 (#25)
kimyw1018 Jul 24, 2026
1ffca71
feat: jwt 키 형식 체크 (#25)
kimyw1018 Jul 24, 2026
6119db5
feat: 500대신 401처리로 감싸기 (#25)
kimyw1018 Jul 24, 2026
bc04e7c
feat: 유저 역할 임의 부여 제거 (#25)
kimyw1018 Jul 24, 2026
678eb4e
feat: 이메일 속성 삭제 (#25)
kimyw1018 Jul 24, 2026
0ed59e6
feat: 타입 캐스팅 로직 수정 (#25)
kimyw1018 Jul 24, 2026
76ee530
feat: 토큰 유효성 private, jwt프로퍼티 반영 , 예외 처리(#25)
kimyw1018 Jul 24, 2026
8120ae7
feat: resolveToken 하드코딩 제거 (#25)
kimyw1018 Jul 24, 2026
f19f57c
feat: 앤드포인트 컨밴션 (#25)
kimyw1018 Jul 24, 2026
8c45bc1
feat: 비인증 허용 api 수정 (#25)
kimyw1018 Jul 24, 2026
5b69e50
feat: cors 추가 (#25)
kimyw1018 Jul 24, 2026
65967dc
feat: ObjectMapper주입 (#25)
kimyw1018 Jul 24, 2026
c0e7b86
feat: 유저 role 이넘 생성 (#25)
kimyw1018 Jul 24, 2026
f609452
feat: 유저 role 이넘관련 로직 추가 (#25)
kimyw1018 Jul 24, 2026
3754aa3
feat: jwt 토큰 응답 세분화 (#25)
kimyw1018 Jul 24, 2026
bb295aa
feat: 네이밍, 타입 수정(#25)
kimyw1018 Jul 24, 2026
4530b88
feat: 네이밍수정(#25)
kimyw1018 Jul 24, 2026
d8a49eb
Merge: 최신 상태 반영 (#25)
kimyw1018 Jul 24, 2026
1ab1d2a
feat: 와일드카드, 위험성 제거 (#25)
kimyw1018 Jul 24, 2026
1b90a4d
feat: 주석 정리(#25)
kimyw1018 Jul 24, 2026
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
27 changes: 27 additions & 0 deletions src/main/java/com/mr/domain/auth/controller/AuthController.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,27 @@
package com.mr.domain.auth.controller;

import com.mr.domain.auth.dto.AuthRequestDTO;
import com.mr.domain.auth.dto.AuthResponseDTO;
import com.mr.domain.auth.entity.enums.SocialType;
import com.mr.domain.auth.service.AuthService;
import com.mr.global.apipayload.ApiResponse;
import jakarta.validation.Valid;
import lombok.RequiredArgsConstructor;
import org.springframework.web.bind.annotation.*;
Comment thread
kimyw1018 marked this conversation as resolved.
Resolved

@RestController
@RequiredArgsConstructor
@RequestMapping("/api/v1/auth")
public class AuthController {
Comment thread
kimyw1018 marked this conversation as resolved.
Resolved

private final AuthService authService;

@PostMapping("/login/{socialType}")
public ApiResponse<AuthResponseDTO.LoginResponse> socialLogin(
@PathVariable(name = "socialType") SocialType socialType,
Comment thread
kimyw1018 marked this conversation as resolved.
Resolved
@RequestBody @Valid AuthRequestDTO.SocialLoginRequest request
) {
AuthResponseDTO.LoginResponse response = authService.socialLogin(socialType, request.accessToken());
return ApiResponse.onSuccess(response);
}
Comment thread
kimyw1018 marked this conversation as resolved.
Resolved
}
16 changes: 16 additions & 0 deletions src/main/java/com/mr/domain/auth/dto/AuthRequestDTO.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,16 @@
package com.mr.domain.auth.dto;

import jakarta.validation.constraints.NotBlank;

public class AuthRequestDTO {

public record SocialLoginRequest(
@NotBlank(message = "소셜 액세스 토큰은 필수 입력값입니다.")
String accessToken
) {}

public record TokenRefreshRequest(
@NotBlank(message = "Refresh Token은 필수 입력값입니다.")
String refreshToken
) {}
}
22 changes: 22 additions & 0 deletions src/main/java/com/mr/domain/auth/dto/AuthResponseDTO.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,22 @@
package com.mr.domain.auth.dto;

import lombok.Builder;

public class AuthResponseDTO {

@Builder
public record TokenResponse(
String accessToken,
String refreshToken,
Long tokenExpirationTime
Comment thread
kimyw1018 marked this conversation as resolved.
Resolved
) {}

@Builder
public record LoginResponse(
Long userId,
String email,
String nickname,
Boolean isNewUser, // 최초 가입 여부
Comment thread
kimyw1018 marked this conversation as resolved.
Resolved
TokenResponse tokenInfo
) {}
}
7 changes: 3 additions & 4 deletions src/main/java/com/mr/domain/auth/entity/SocialAuth.java
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,7 @@

@Getter
@Entity
// TODO: 추후 User 도메인 완성 시 단방향/양방향 인덱스 추가
// TODO: 추후 User 도메인 완성 시 인덱스 추가
@Table(
name = "social_auth",
uniqueConstraints = {
Expand All @@ -29,7 +29,7 @@ public class SocialAuth extends BaseCreatedEntity {
@Column(name = "social_auth_id")
private Long id;

// TODO: User 엔티티 연관관계 연결 예정
// TODO: User연결 예정
@Column(name = "user_id", nullable = false)
private Long userId;

Expand All @@ -55,7 +55,7 @@ public class SocialAuth extends BaseCreatedEntity {
@Builder(access = AccessLevel.PRIVATE)
private SocialAuth(Long userId, SocialType socialType, String socialId, String refreshToken,
String refreshTokenHash, LocalDateTime expiredAt, String deviceInfo) {
// 컴파일 에러 수정: 실제 정의된 validateUserAccount 메서드로 매핑

validateUserAccount(userId);
validateUserAccount(socialType);
validateUserAccount(socialId);
Expand Down Expand Up @@ -116,7 +116,6 @@ public void updateRefreshToken(String encryptedToken, String tokenHash, LocalDat
this.deviceInfo = deviceInfo;
}

// 최신 토큰 만료 및 폐기 처리
public void expireToken() {
this.refreshToken = null;
this.refreshTokenHash = null;
Expand Down
48 changes: 48 additions & 0 deletions src/main/java/com/mr/domain/auth/service/AuthService.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,48 @@
package com.mr.domain.auth.service;

import com.mr.domain.auth.dto.AuthResponseDTO;
import com.mr.domain.auth.entity.enums.SocialType;
import com.mr.global.security.jwt.JwtTokenProvider;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

@Service
@RequiredArgsConstructor
@Transactional(readOnly = true)
public class AuthService {

private final JwtTokenProvider jwtTokenProvider;
// private final KakaoOAuthService kakaoOAuthService; (외부 API 파싱용 서비스)
// private final GoogleOAuthService googleOAuthService;

@Transactional
public AuthResponseDTO.LoginResponse socialLogin(SocialType socialType, String accessToken) {
// 1. 외부 소셜 API (카카오/구글) 통신하여 유저 프로필(email, socialId) 파싱
// SocialUserInfo userInfo = getSocialUserInfo(socialType, accessToken);

// 2. TODO: User 엔티티 연동 및 가입여부 검증 (Stub 구조)
// 만약 가입 안 되어있으면 DB User 생성 -> 저장
Long mockUserId = 1L;
String mockEmail = "user@example.com";
String mockNickname = "뮤즈유저";
boolean isNewUser = false;

String appAccessToken = jwtTokenProvider.createAccessToken(mockUserId);
String appRefreshToken = jwtTokenProvider.createRefreshToken(mockUserId);
Comment on lines +20 to +32

@coderabbitai coderabbitai Bot Jul 23, 2026 •

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

🔒 Security & Privacy | 🔴 Critical | ⚡ Quick win

🧩 Analysis chain

🏁 Script executed:

#!/bin/bash
set -euo pipefail

echo "== candidate files =="
git ls-files | rg 'AuthService\.java|CustomUserDetailsService\.java|User\.java|JwtTokenProvider\.java|UserRepository\.java|CustomUserCredentials\.java|spring-security|SecurityConfig\.java' || true

echo
echo "== AuthService excerpt =="
if [ -f src/main/java/com/mr/domain/auth/service/AuthService.java ]; then
  nl -ba src/main/java/com/mr/domain/auth/service/AuthService.java | sed -n '1,220p'
fi

echo
echo "== CustomUserDetailsService excerpt =="
if [ -f src/main/java/com/mr/global/security/principal/CustomUserDetailsService.java ]; then
  nl -ba src/main/java/com/mr/global/security/principal/CustomUserDetailsService.java | sed -n '1,140p'
fi

echo
echo "==Jwt token provider and user-related references =="
rg -n "createAccessToken|createRefreshToken|loadUserByUsername|findById|isActivate|ROLE|SocialType|socialId|accessToken|jwtTokenProvider" src/main/java -S || true

Repository: Musereview/BE

Length of output: 546


🏁 Script executed:

#!/bin/bash
set -euo pipefail

echo "== AuthService excerpt =="
sed -n '1,220p' src/main/java/com/mr/domain/auth/service/AuthService.java | cat -n

echo
echo "== CustomUserDetailsService excerpt =="
sed -n '1,140p' src/main/java/com/mr/global/security/principal/CustomUserDetailsService.java | cat -n

echo
echo "== JwtTokenProvider excerpt =="
sed -n '1,220p' src/main/java/com/mr/global/security/jwt/JwtTokenProvider.java | cat -n

echo
echo "== User entity excerpt =="
sed -n '1,220p' src/main/java/com/mr/domain/user/entity/User.java | cat -n

echo
echo "== Search for user/security/token usages =="
rg -n "createAccessToken|createRefreshToken|loadUserByUsername|findById|isActivate|ROLE|SocialType|socialId|accessToken|jwtTokenProvider|SecurityContextHolder|authentication" src/main/java -S || true

Repository: Musereview/BE

Length of output: 15775


소셜 토큰 검증과 실제 사용자 조회를 연결하세요.

socialLogin이 받은 accessToken을 검증하지 않고 userId=1L로 고정된 JWT를 발급하고, 이후 인증 주체도 실제 User/SocialAuth 조회 없이 고정된 이메일과 ROLE_USER 권한으로 반환됩니다. 이는 어떤 토큰이라도 같은 로그인 응답·권한을 얻을 수 있게 만듭니다.

  • CustomUserDetailsService.loadUserByUsername: userId -> UserRepository.findById와 존재하지 않을 때 예외 반환을 구현하세요. [Spring Security UserDetailsService 참고]
  • AuthService.socialLogin: 소셜 제공자 토큰 검증 → SocialAuth 조회/생성 성공 후에만 DTO의 사용자 속성과 jwtTokenProvider.createAccessToken/RefreshToken(...)을 호출하세요.
  • JWT 클레임도 실제 사용자 ID만 담도록 일관되게 유지하세요.
📍 Affects 2 files
  • src/main/java/com/mr/domain/auth/service/AuthService.java#L20-L32 (this comment)
  • src/main/java/com/mr/global/security/principal/CustomUserDetailsService.java#L12-L16
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@src/main/java/com/mr/domain/auth/service/AuthService.java` around lines 20 -
32, Update src/main/java/com/mr/domain/auth/service/AuthService.java:20-32 in
socialLogin to validate the provider accessToken, resolve or create the
corresponding SocialAuth/User, and only then populate the response and generate
JWTs using the real user ID and attributes; remove all mock identity values.
Update
src/main/java/com/mr/global/security/principal/CustomUserDetailsService.java:12-16
in loadUserByUsername to look up the user through UserRepository.findById and
throw the appropriate authentication exception when absent, preserving real
authorities and user identity throughout JWT authentication.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

다음 pr에서 구현 예정

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

@kimyw1018 알겠습니다. 현재 PR의 인프라 구축 범위와 분리하는 방향은 괜찮습니다. 다만 실제 소셜 토큰 검증·사용자 조회 전에는 임의 토큰으로 고정 사용자 JWT가 발급될 수 있으므로, 해당 엔드포인트는 운영 노출 전 반드시 후속 PR에서 완료해 주세요.

원하시면 후속 작업을 추적할 GitHub 이슈를 생성해 드릴까요? 🐰


AuthResponseDTO.TokenResponse tokenResponse = AuthResponseDTO.TokenResponse.builder()
.accessToken(appAccessToken)
.refreshToken(appRefreshToken)
.tokenExpirationTime(3600L)
.build();
Comment on lines +35 to +39

@coderabbitai coderabbitai Bot Jul 23, 2026 •

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

🗄️ Data Integrity & Integration | 🟡 Minor | ⚡ Quick win

토큰 만료 시간을 JWT 설정과 동일한 소스에서 계산하세요.

JwtTokenProvider는 설정된 accessTokenValidityInMilliseconds를 사용하지만 응답은 항상 3600L을 반환합니다. 설정값이 변경되면 클라이언트가 잘못된 만료 시간을 받아 너무 일찍 또는 늦게 갱신할 수 있습니다. provider에서 실제 TTL을 노출하거나 생성된 JWT의 exp를 기준으로 응답하고, 값의 단위도 명확히 정의하세요.

🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@src/main/java/com/mr/domain/auth/service/AuthService.java` around lines 34 -
38, Update the token response construction in AuthService to derive
tokenExpirationTime from the same configured access-token validity used by
JwtTokenProvider instead of the hardcoded 3600L. Expose or reuse the provider’s
actual TTL, ensure the response unit is explicitly consistent with the API
contract, and keep the returned expiration synchronized when JWT settings
change.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

다음 pr 에서 구현 예정

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

@kimyw1018 알겠습니다. 다음 PR에서 JwtTokenProvider의 실제 access-token TTL을 단일 기준으로 노출·재사용하고, 응답의 tokenExpirationTime 단위도 계약에 명시해 설정 변경 시 동기화되도록 처리하면 됩니다.

원하시면 이 작업을 추적할 GitHub 이슈를 만들어 드릴까요? 🐇


return AuthResponseDTO.LoginResponse.builder()
.userId(mockUserId)
.email(mockEmail)
.nickname(mockNickname)
.isNewUser(isNewUser)
.tokenInfo(tokenResponse)
.build();
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,9 @@ public enum CommonStatus implements BaseCode {
SUCCESS(HttpStatus.OK, "COMMON_200", "요청에 성공하였습니다."),
INVALID_INPUT_VALUE(HttpStatus.BAD_REQUEST, "COMMON_400_01", "입력값이 올바르지 않습니다."),
HTTP_MESSAGE_NOT_READABLE(HttpStatus.BAD_REQUEST, "COMMON_400_02", "요청 본문(JSON) 파싱에 실패했습니다."),
INTERNAL_SERVER_ERROR(HttpStatus.INTERNAL_SERVER_ERROR, "COMMON_500_01", "서버 에러가 발생했습니다.");
INTERNAL_SERVER_ERROR(HttpStatus.INTERNAL_SERVER_ERROR, "COMMON_500_01", "서버 에러가 발생했습니다."),
UNAUTHORIZED(HttpStatus.UNAUTHORIZED, "COMMON_401_01", "인증이 필요합니다."),
FORBIDDEN(HttpStatus.FORBIDDEN, "COMMON_403_01", "금지된 접근입니다.");

private final HttpStatus status;
private final String code;
Expand Down
30 changes: 0 additions & 30 deletions src/main/java/com/mr/global/config/SecurityConfig.java

This file was deleted.

4 changes: 4 additions & 0 deletions src/main/java/com/mr/global/config/SwaggerConfig.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,4 @@
package com.mr.global.config;

public class SwaggerConfig {
}
43 changes: 43 additions & 0 deletions src/main/java/com/mr/global/security/SecurityConfig.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,43 @@
package com.mr.global.security;

import com.mr.global.security.jwt.JwtAccessDeniedHandler;
import com.mr.global.security.jwt.JwtAuthenticationEntryPoint;
import com.mr.global.security.jwt.JwtAuthenticationFilter;
import com.mr.global.security.jwt.JwtTokenProvider;
import lombok.RequiredArgsConstructor;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
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.UsernamePasswordAuthenticationFilter;

@Configuration
@EnableWebSecurity
@RequiredArgsConstructor
public class SecurityConfig {

private final JwtTokenProvider jwtTokenProvider;
private final JwtAuthenticationEntryPoint jwtAuthenticationEntryPoint;
private final JwtAccessDeniedHandler jwtAccessDeniedHandler;

@Bean
Comment thread
kimyw1018 marked this conversation as resolved.
Resolved
public SecurityFilterChain securityFilterChain(HttpSecurity http) throws Exception {
http
.csrf(AbstractHttpConfigurer::disable)
.sessionManagement(session -> session.sessionCreationPolicy(SessionCreationPolicy.STATELESS))
.exceptionHandling(exception -> exception
.authenticationEntryPoint(jwtAuthenticationEntryPoint)
.accessDeniedHandler(jwtAccessDeniedHandler)
)
.authorizeHttpRequests(auth -> auth
.requestMatchers("/swagger-ui/**", "/v3/api-docs/**", "/api/v1/auth/**").permitAll()
Comment thread
kimyw1018 marked this conversation as resolved.
Resolved
.anyRequest().authenticated()
)
.addFilterBefore(new JwtAuthenticationFilter(jwtTokenProvider), UsernamePasswordAuthenticationFilter.class);

return http.build();
}
}
26 changes: 26 additions & 0 deletions src/main/java/com/mr/global/security/SecurityUtil.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,26 @@
package com.mr.global.security;

import com.mr.global.apipayload.code.CommonStatus;
import com.mr.global.apipayload.exception.GeneralException;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;

public class SecurityUtil {

private SecurityUtil() {
}

public static Long getCurrentUserId() {
final Authentication authentication = SecurityContextHolder.getContext().getAuthentication();

if (authentication == null || authentication.getName() == null || authentication.getName().equals("anonymousUser")) {
Comment thread
kimyw1018 marked this conversation as resolved.
Resolved
throw new GeneralException(CommonStatus.UNAUTHORIZED);

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

인증 정보가 없을 때 유입될 수 있는 anonymousUser 상황까지 놓치지 않고 꼼꼼하게 예외 처리해 주셨네요.

}

try {
return Long.parseLong(authentication.getName());
} catch (NumberFormatException e) {
throw new GeneralException(CommonStatus.UNAUTHORIZED);

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

SecurityUtil에서 던지는 GeneralException(CommonStatus.UNAUTHORIZED)은 Security Filter 단계가 아니라 컨트롤러 이후 단계에서 발생하므로 JwtAuthenticationEntryPoint가 처리하지 않을 것 같습니다! 공통 예외 처리기에서 이 예외의 HTTP 상태가 실제로 401로 내려가는지 테스트를 해보셨는지 궁금합니다!

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

말씀해주신 대로 SecurityUtil은 컨트롤러/서비스 레이어에서 실행돼서 시큐리티 필터의JwtAuthenticationEntryPoint가 아닌, 전역 예외처리에서 GeneralException을 가로채게 됩니다.

현재 GlobalExceptionHandler 에서 CommonStatus.UNAUTHORIZED 내부의 HttpStatus.UNAUTHORIZED, ApiResponse를 추출하여 HTTP Status 401로 반환하도록 구현되어 있습니다!

정상 반환되는지 재검증 완료했습니다

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

수고하셨습니당!!

}
}
}
Comment thread
kimyw1018 marked this conversation as resolved.
Resolved
Original file line number Diff line number Diff line change
@@ -0,0 +1,37 @@
package com.mr.global.security.jwt;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.mr.global.apipayload.ApiResponse;
import com.mr.global.apipayload.code.CommonStatus;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.http.MediaType;
import org.springframework.security.access.AccessDeniedException;
import org.springframework.security.web.access.AccessDeniedHandler;
import org.springframework.stereotype.Component;

import java.io.IOException;

@Component
public class JwtAccessDeniedHandler implements AccessDeniedHandler {

private final ObjectMapper objectMapper = new ObjectMapper();

@Override
public void handle(HttpServletRequest request, HttpServletResponse response,
AccessDeniedException accessDeniedException) throws IOException {

// 403 Forbidden 팀 공통 JSON 응답 반환
response.setContentType(MediaType.APPLICATION_JSON_VALUE);
response.setCharacterEncoding("UTF-8");
response.setStatus(HttpServletResponse.SC_FORBIDDEN);

ApiResponse<Object> apiResponse = ApiResponse.onFailure(
CommonStatus.FORBIDDEN.getCode(),
CommonStatus.FORBIDDEN.getMessage(),
null
);

response.getWriter().write(objectMapper.writeValueAsString(apiResponse));
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,37 @@
package com.mr.global.security.jwt;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.mr.global.apipayload.ApiResponse;
import com.mr.global.apipayload.code.CommonStatus;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.http.MediaType;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.web.AuthenticationEntryPoint;
import org.springframework.stereotype.Component;

import java.io.IOException;

@Component
public class JwtAuthenticationEntryPoint implements AuthenticationEntryPoint {

private final ObjectMapper objectMapper = new ObjectMapper();

@Override
public void commence(HttpServletRequest request, HttpServletResponse response,
AuthenticationException authException) throws IOException {

// 401 Unauthorized 팀 공통 JSON 응답 반환
response.setContentType(MediaType.APPLICATION_JSON_VALUE);
response.setCharacterEncoding("UTF-8");
response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);

ApiResponse<Object> apiResponse = ApiResponse.onFailure(
CommonStatus.UNAUTHORIZED.getCode(),
CommonStatus.UNAUTHORIZED.getMessage(),
null
);

response.getWriter().write(objectMapper.writeValueAsString(apiResponse));
}
}
Loading
Loading