Skip to content

Conversation

@Kim-TaeUk
Copy link
Member

@Kim-TaeUk Kim-TaeUk commented Mar 16, 2025

Related Issue

Key Changes

  1. 인증 사용자 조회 및 검증
    AS-IS)
    Controller 단에서 Principal.getName()을 통해 userId 문자열을 얻고 Long 타입으로 캐스팅,
    추출한 userId로 userService.getUserOrException 호출하는 로직이 Controller에서 중복 발생
    TO-BE)
    Spring Security에서 제공하는 @AuthenticationPrincipal 사용,
    CustomArgumentResolver를 통해 인증 사용자 정보 주입,
    Resolver에서 사용자 검증이라는 관심사를 전담 및 일관된 처리

  2. 리소스 존재 여부 검증 및 리소스 접근 제어
    AS-IS)
    요청에 해당하는 리소스 존재 여부 검증을 위해 findById().orElseThrow()를 Service 단에서 반복 호출,
    숨김 혹은 차단 리소스 접근 가능 여부 검증을 위해 반복되는 로직 발생
    TO-BE)
    AuthorizationValidator나 AccessValidator에서 수행하여 관심사 분리,
    Validator.canAcces로 일관된 처리

  3. 리소스 조작 가능 여부 검증
    AS-IS)
    Service 단에서 리소스 조작 가능 여부를 직접 확인
    TO-BE)
    @PreAuthorize + AuthorizationService.validate로 위임
    AuthorizationService.validate -> ResourceAuthorizationHandler -> XXXAuthorizationValidator

전체 인증 인가 플로우

  1. Client -> Server: 요청 전송
  2. Server.Servlet Container 요청 수신
  3. JwtAuthenticationFilter
    • JWT 유효성 검증
    • 유효한 경우 userId를 담은 CustomAuthenticationToken 생성 후, SecurityContextHolder에 저장
  4. DispatcherServlet -> Controller 전달
  5. CustomArgumentResolver
    • SecurityContext의 인증 객체에서 userId 추출
    • UserService.getUserOrException을 통해 유저 존재 여부 확인
      • 존재O: @AuthenticationPrincipal User에 바인딩
      • 존재X: 404 에러 응답
  6. @PreAuthorize
    • isAuthenticated(): 인증된 사용자만 접근 허용
    • AuthorizationService.validate: 리소스 존재 여부&조작 가능 여부 확인
    • AccessValidator.canAccess: 리소스 존재 여부&접근 가능 여부 확인
  7. 검증 모두 통과 시, Controller -> Service 호출: 비즈니스 로직만 수행
    • JWT 유효성 검증
    • User 존재 여부 검증
    • 리소스 존재 여부 검증
    • 리소스 접근 가능 여부 검증
    • 리소스 조작 가능 여부 검증

To Reviewers

볼륨이 좀 크네요..! 죄송합니다 ㅎㅎ,,

References

Kim-TaeUk added 30 commits March 3, 2025 16:34
userId를 Long -> String으로 casting하여 타입이 일관적이지 않았음
from UserAuthentication
to CustomAuthenticationToken
HashMap인 validatorMap을 통해 ResourceAuthorizationValidator의 구현체를 저장하고 사용
…자동 매핑 기능 추가

@Autowired를 통해 List<ResourceAuthorizationValidator>를 주입, for loop를 통해 validatorMap에 validator의 resourceType을 key로 저장
- 존재하지 않는 resourceType인 경우 null에 대해 exception throw
- Validator에서 permission 체크하도록
Optional과 orElseThrow를 통해 null 처리 간결하게 변경
권한 X = 본인의 리소스가 아닌 경우
from hasPermission
to authorizeResourceAccess
@Kim-TaeUk Kim-TaeUk marked this pull request as ready for review April 8, 2025 14:59
@github-actions github-actions bot requested review from ChaeAg and rinarina0429 April 8, 2025 15:00
Copy link
Member

@sansan20535 sansan20535 left a comment

Choose a reason for hiding this comment

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

리뷰 남기면서 많이 배웠습니다! 감사합니다 : )

Copy link
Member

@rinarina0429 rinarina0429 left a comment

Choose a reason for hiding this comment

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

우기온앤온 이렇게나 큰 pr을 . . .
수고하셨습니다 이전 Controller보다 훨씬 깔끔하네요! 더 나은 방식이 있을지는 같이 더 찾아봐요 ~
커멘트 한번씩만 확인 부탁드립니다아

Copy link
Contributor

@GiJungPark GiJungPark left a comment

Choose a reason for hiding this comment

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

빠른 피드백 반영 확인했습니다. :)

@rinarina0429 rinarina0429 self-requested a review April 16, 2025 00:43
@Kim-TaeUk Kim-TaeUk merged commit a9cca0a into dev Apr 18, 2025
1 check passed
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

[FIX] 인증/인가 개선 및 리팩토링

6 participants