-
Notifications
You must be signed in to change notification settings - Fork 8
[센] Chapter 8. Spring Security - Security 구조, 폼 로그인 #117
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Open
sekong11
wants to merge
1
commit into
sen/main
Choose a base branch
from
sen/#111
base: sen/main
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
Open
Changes from all commits
Commits
File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
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
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
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
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
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
9 changes: 6 additions & 3 deletions
9
src/main/java/com/example/umc10th/domain/member/exception/MemberException.java
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
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -1,7 +1,10 @@ | ||
| package com.example.umc10th.domain.member.exception; | ||
|
|
||
| public class MemberException extends RuntimeException { | ||
| public MemberException(String message) { | ||
| super(message); | ||
| import com.example.umc10th.global.apiPayload.code.BaseErrorCode; | ||
| import com.example.umc10th.global.apiPayload.exception.ProjectException; | ||
|
|
||
| public class MemberException extends ProjectException { | ||
| public MemberException(BaseErrorCode code) { | ||
| super(code); | ||
| } | ||
| } |
18 changes: 17 additions & 1 deletion
18
src/main/java/com/example/umc10th/domain/member/exception/code/MemberErrorCode.java
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
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -1,4 +1,20 @@ | ||
| package com.example.umc10th.domain.member.exception.code; | ||
|
|
||
| public enum MemberErrorCode { | ||
| import com.example.umc10th.global.apiPayload.code.BaseErrorCode; | ||
| import lombok.Getter; | ||
| import lombok.RequiredArgsConstructor; | ||
| import org.springframework.http.HttpStatus; | ||
|
|
||
| @RequiredArgsConstructor | ||
| @Getter | ||
| public enum MemberErrorCode implements BaseErrorCode { | ||
|
|
||
| MEMBER_NOT_FOUND(HttpStatus.BAD_REQUEST, | ||
| "MEMBER404_1", | ||
| "사용자가 존재하지 않습니다."), | ||
| ; | ||
|
|
||
| private final HttpStatus status; | ||
| private final String code; | ||
| private final String message; | ||
| } |
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
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
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
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
66 changes: 66 additions & 0 deletions
66
src/main/java/com/example/umc10th/global/config/SecurityConfig.java
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
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,66 @@ | ||
| package com.example.umc10th.global.config; | ||
|
|
||
| import com.example.umc10th.global.security.exception.CustomAccessDenied; | ||
| import com.example.umc10th.global.security.exception.CustomEntryPoint; | ||
| 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.crypto.bcrypt.BCryptPasswordEncoder; | ||
| import org.springframework.security.crypto.password.PasswordEncoder; | ||
| import org.springframework.security.web.SecurityFilterChain; | ||
|
|
||
| @EnableWebSecurity | ||
| @Configuration | ||
| public class SecurityConfig { | ||
|
|
||
| private final String[] allowUris = { | ||
| // Swagger 허용 | ||
| "/swagger-ui/**", | ||
| "/swagger-resources/**", | ||
| "/v3/api-docs/**", | ||
| "/api/v1/auth/signup" | ||
| }; | ||
|
|
||
| @Bean | ||
| public SecurityFilterChain securityFilterChain(HttpSecurity http) throws Exception { | ||
| http | ||
| .csrf(AbstractHttpConfigurer::disable) | ||
| .authorizeHttpRequests(requests -> requests | ||
| .requestMatchers(allowUris).permitAll() | ||
| .anyRequest().authenticated() | ||
| ) | ||
| .formLogin(form -> form | ||
| .defaultSuccessUrl("/swagger-ui/index.html", true) | ||
| .permitAll() | ||
| ) | ||
| .logout(logout -> logout | ||
| .logoutUrl("/logout") | ||
| .logoutSuccessUrl("/login?logout") | ||
| .permitAll() | ||
| ) | ||
| .exceptionHandling(exception->exception | ||
| .accessDeniedHandler(customAccessDenied()) | ||
| .authenticationEntryPoint(customEntryPoint()) | ||
| ) | ||
| ; | ||
|
|
||
| return http.build(); | ||
| } | ||
|
|
||
| @Bean | ||
| public PasswordEncoder passwordEncoder() { | ||
| return new BCryptPasswordEncoder(); | ||
| } | ||
|
|
||
| @Bean | ||
| public CustomAccessDenied customAccessDenied() { | ||
| return new CustomAccessDenied(); | ||
| } | ||
|
|
||
| @Bean | ||
| public CustomEntryPoint customEntryPoint() { | ||
| return new CustomEntryPoint(); | ||
| } | ||
| } |
34 changes: 34 additions & 0 deletions
34
src/main/java/com/example/umc10th/global/security/entity/AuthMember.java
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
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,34 @@ | ||
| package com.example.umc10th.global.security.entity; | ||
|
|
||
| import com.example.umc10th.domain.member.entity.Member; | ||
| import lombok.Getter; | ||
| import lombok.RequiredArgsConstructor; | ||
| import org.jspecify.annotations.Nullable; | ||
| import org.springframework.security.core.GrantedAuthority; | ||
| import org.springframework.security.core.userdetails.UserDetails; | ||
|
|
||
| import java.util.Collection; | ||
| import java.util.List; | ||
|
|
||
| @Getter | ||
| @RequiredArgsConstructor | ||
| public class AuthMember implements UserDetails { | ||
|
|
||
| private final Member member; | ||
|
|
||
|
|
||
| @Override | ||
| public Collection<? extends GrantedAuthority> getAuthorities() { | ||
| return List.of(); | ||
| } | ||
|
|
||
| @Override | ||
| public @Nullable String getPassword() { | ||
| return member.getPassword(); | ||
| } | ||
|
|
||
| @Override | ||
| public String getUsername() { | ||
| return member.getEmail(); | ||
| } | ||
| } |
35 changes: 35 additions & 0 deletions
35
src/main/java/com/example/umc10th/global/security/exception/CustomAccessDenied.java
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
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,35 @@ | ||
| package com.example.umc10th.global.security.exception; | ||
|
|
||
| import com.example.umc10th.global.apiPayload.ApiResponse; | ||
| import com.example.umc10th.global.apiPayload.code.BaseErrorCode; | ||
| import com.example.umc10th.global.apiPayload.code.GeneralErrorCode; | ||
| import com.fasterxml.jackson.databind.ObjectMapper; | ||
| import jakarta.servlet.http.HttpServletRequest; | ||
| import jakarta.servlet.http.HttpServletResponse; | ||
| import org.springframework.security.access.AccessDeniedException; | ||
| import org.springframework.security.web.access.AccessDeniedHandler; | ||
|
|
||
| import java.io.IOException; | ||
|
|
||
| public class CustomAccessDenied implements AccessDeniedHandler { | ||
|
|
||
| @Override | ||
| public void handle( | ||
| HttpServletRequest request, | ||
| HttpServletResponse response, | ||
| AccessDeniedException accessDeniedException | ||
| ) throws IOException { | ||
| ObjectMapper objectMapper = new ObjectMapper(); | ||
| BaseErrorCode code = GeneralErrorCode.FORBIDDEN; | ||
|
|
||
| // 응답 Content-Type, HTTP 상태코드 정의 | ||
| response.setContentType("application/json;charset=UTF-8"); | ||
| response.setStatus(code.getStatus().value()); | ||
|
|
||
| // Response Body에 응답통일한 객체를 넣기 | ||
| ApiResponse<Void> errorResponse = ApiResponse.<Void>onFailureEntity(code, null).getBody(); | ||
|
|
||
| // 실제 Response로 덮어쓰기 | ||
| objectMapper.writeValue(response.getOutputStream(), errorResponse); | ||
| } | ||
| } |
35 changes: 35 additions & 0 deletions
35
src/main/java/com/example/umc10th/global/security/exception/CustomEntryPoint.java
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
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,35 @@ | ||
| package com.example.umc10th.global.security.exception; | ||
|
|
||
| import com.example.umc10th.global.apiPayload.ApiResponse; | ||
| import com.example.umc10th.global.apiPayload.code.BaseErrorCode; | ||
| import com.example.umc10th.global.apiPayload.code.GeneralErrorCode; | ||
| import com.fasterxml.jackson.databind.ObjectMapper; | ||
| import jakarta.servlet.http.HttpServletRequest; | ||
| import jakarta.servlet.http.HttpServletResponse; | ||
| import org.springframework.security.core.AuthenticationException; | ||
| import org.springframework.security.web.AuthenticationEntryPoint; | ||
|
|
||
| import java.io.IOException; | ||
|
|
||
| public class CustomEntryPoint implements AuthenticationEntryPoint { | ||
|
|
||
| @Override | ||
| public void commence( | ||
| HttpServletRequest request, | ||
| HttpServletResponse response, | ||
| AuthenticationException authException | ||
| ) throws IOException { | ||
| ObjectMapper objectMapper = new ObjectMapper(); | ||
| BaseErrorCode code = GeneralErrorCode.UNAUTHORIZED; | ||
|
|
||
| // 응답 Content-Type, HTTP 상태코드 정의 | ||
| response.setContentType("application/json;charset=UTF-8"); | ||
| response.setStatus(code.getStatus().value()); | ||
|
|
||
| // Response Body에 응답통일한 객체를 넣기 | ||
| ApiResponse<Void> errorResponse = ApiResponse.<Void>onFailureEntity(code, null).getBody(); | ||
|
|
||
| // 실제 Response로 덮어쓰기 | ||
| objectMapper.writeValue(response.getOutputStream(), errorResponse); | ||
| } | ||
| } | ||
Oops, something went wrong.
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.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
지금 저희가 CustomEntryPoint를 만든 이유부터 생각해 보면 좋을 것 같습니다.
만약 컨트롤러나 서비스에서 예외가 발생했다면 @RestControllerAdvice를 활용해서 만들어두신 GeneralExceptionAdvice가 바로 잡아 냈을 것입니다. 그러나 시큐리티 필터에서 에러가 났다면 RestControllerAdvice가 잡아낼 수 없기 때문에 CustomEntryPoint를 만들고 ObjectMapper로 JSON을 만들어 클라이언트에게 반환하게 해두신 거죠.
그런데 여기서 한 가지 아쉬운 점이 있습니다. CustomEntryPoint에서 ObjectMapper로 직접 JSON 응답을 만들고 있잖아요? 이러면 에러 응답 포맷을 바꿀 때 GeneralExceptionAdvice랑 CustomEntryPoint 두 군데를 다 수정해야 합니다.
이걸 해결하는 방법으로 HandlerExceptionResolver를 CustomEntryPoint에 주입하는 방식이 있습니다. 필터에서 터진 예외를 resolver.resolveException()으로 MVC 쪽에 토스해버리면, 우리가 이미 만들어둔 @RestControllerAdvice가 그 예외를 잡아서 처리해주니까 에러 응답 로직이 한 곳으로 모이게 됩니다.
구현은 GeneralExceptionAdvice에 AuthenticationException과 AccessDeniedException 전용 핸들러를 추가하는 방식으로 하면 될 것 같습니다! 참고로 CustomAccessDenied도 같은 구조라서, 리팩토링할 때 같이 적용하면 될 것 같습니다~