[김유민] sprint9#312
Open
kimyumin03 wants to merge 18 commits intocodeit-bootcamp-spring:김유민from
Hidden character warning
The head ref may contain hidden characters: "\uae40\uc720\ubbfc-sprint9"
Open
Conversation
This file contains hidden or 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
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
요구사항
기본
Spring Security 환경설정
having filters [DisableEncodeUrl, WebAsyncManagerIntegration, SecurityContextHolder, HeaderWriter,
Csrf, Logout, UsernamePasswordAuthentication, DefaultResources, DefaultLoginPageGenerating,
DefaultLogoutPageGenerating, BasicAuthentication, RequestCacheAware,
SecurityContextHolderAwareRequest, AnonymousAuthentication, ExceptionTranslation, Authorization]
CSRF 보호 설정하기
회원가입
엔드포인트: POST /api/users
요청: Body UserCreateRequest, MultipartFile
응답: 200 UserDto
인증 - 로그인
인증 - 세션을 활용한 현재 사용자 정보 조회
- 엔드포인트: GET /api/auth/me
- 요청: Header(자동 포함) Cookie: JSESSIONID=…
- 응답: 200 UserDto
- @AuthenticationPrincipal 활용
인증 - 로그아웃
Spring Security의 logout 흐름은 그대로 유지하면서 필요한 부분만 대체
로그아웃을 처리할 url을 /api/auth/logout로 설정
http
.logout(logout -> logout
.logoutUrl(...)
)
LogoutSuccessHandler 컴포넌트를 대체
http
.logout(logout -> logout
...
.logoutSuccessHandler(...)
)
인가 - 권한 정의
CREATE TABLE users
(
...
role varchar(20) NOT NULL
);
ALTER TABLE users
ADD role varchar(20) NOT NULL;
회원가입 시 기본 권한: USER
사용자 권한을 수정하는 API를 구현
API 스펙
- 엔드포인트: PUT /api/auth/role
- 요청: Body UserRoleUpdateRequest
- 응답: 200 UserDto
애플리케이션 실행 시 ADMIN 권한을 가진 어드민 계정이 초기화되도록 구현하세요.
어드민 계정이 없는 경우에만 초기화
DiscodeitUserDetails.getAuthorities 수정
인가 - 권한 적용
authorizeHttpRequests를 활성화하고, 모든 요청을 인증하도록 설정
http
.authorizeHttpRequests(auth -> auth
.anyRequest().authenticated()
)
다음의 요청은 인증하지 않도록 설정
http
.authorizeHttpRequests(auth -> auth
...
.requestMatchers(...).permitAll()
)
Method Security를 활성화
...
@EnableMethodSecurity
public class SecurityConfig {...}
Service의 메소드 별로 아래의 조건에 맞게 권한을 수정
구현 위치 요약
Spring Security 기본 설정
SecurityConfigSecurityFilterChainBean 등록csrf+CookieCsrfTokenRepository.withHttpOnlyFalse()설정SpaCsrfTokenRequestHandler적용formLogin().loginProcessingUrl("/api/auth/login")logout().logoutUrl("/api/auth/logout")authorizeHttpRequests+permitAll대상 설정@EnableMethodSecurityPasswordEncoder(BCrypt) Bean 등록RoleHierarchy및MethodSecurityExpressionHandlerBean 등록CSRF 토큰 발급 / 세션 기반 사용자 조회 / 권한 변경 API
AuthApi,AuthControllerGET /api/auth/csrf-token(203, CSRF 토큰 발급)GET /api/auth/me(세션 기반 현재 사용자 조회,@AuthenticationPrincipal)PUT /api/auth/role(사용자 권한 수정)인증 관련 컴포넌트
DiscodeitUserDetailsService(UserDetailsService구현)DiscodeitUserDetails(UserDto+ 비밀번호 보관,getAuthorities에서ROLE_...반환)LoginSuccessHandler(로그인 성공 시UserDto응답)LoginFailureHandler(로그인 실패 시 에러 응답)HttpStatusReturningLogoutSuccessHandler(로그아웃 시 204 응답)회원가입 / 비밀번호 해시 / 권한 기본값
User엔티티role필드 추가 (Roleenum:ADMIN,CHANNEL_MANAGER,USER)Role.USER설정UserDto,UserMapper(역할 포함 매핑)BasicUserService#create(회원가입 시PasswordEncoder로 비밀번호 해시)BasicUserService#update(비밀번호 변경 시 재해시)BasicUserService#updateRole(권한 변경,@PreAuthorize("hasRole('ADMIN')"))채널 인가 적용
BasicChannelServicecreate/update/delete에@PreAuthorize("hasRole('CHANNEL_MANAGER')")적용DB 스키마 변경
schema.sqlusers테이블에role varchar(20) NOT NULL컬럼 추가멘토에게