-
Notifications
You must be signed in to change notification settings - Fork 0
스프링 시큐리티 & 로그인 #23
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
seungheon123
wants to merge
14
commits into
develop
Choose a base branch
from
feat/12
base: develop
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
스프링 시큐리티 & 로그인 #23
Changes from all commits
Commits
Show all changes
14 commits
Select commit
Hold shift + click to select a range
c169228
:sparkles: JWT Util 클래스 구현
seungheon123 d246bb7
:sparkles: Spring Security 설정
seungheon123 ff0dc07
:sparkles: Password 길이 15 -> 100으로 변경
seungheon123 4601555
:sparkles: 로그인 구현
seungheon123 461364f
:sparkles: RestController의 예외를 처리할 수 있게 수정
seungheon123 4b6da74
:sparkles: 인증, 인가 예외 처리
seungheon123 22e48bf
:sparkles: JwtException handler
seungheon123 810b9a1
:sparkles: Jira 이슈 생성 주석 처리
seungheon123 c0621c5
:sparkles: 로그인 단위 테스트
seungheon123 cd7ace8
:sparkles: MemberRepository 생성
seungheon123 93bc125
:sparkles: 코드 정리
seungheon123 a05949f
:art: 시크릿키 환경변수로 등록
seungheon123 2c0f0ae
Feat: Merge Conflicts
sunwupark 1cb6de7
Feat: Merge Conflicts
sunwupark 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
Binary file not shown.
Binary file not shown.
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,72 @@ | ||
| package org.momo.security; | ||
|
|
||
| import jakarta.servlet.http.HttpServletRequest; | ||
| import lombok.RequiredArgsConstructor; | ||
| import org.momo.security.filter.JwtFilter; | ||
| import org.momo.security.handler.JwtAccessDeniedHandler; | ||
| import org.momo.security.handler.JwtAuthenticationEntryPoint; | ||
| import org.springframework.context.annotation.Bean; | ||
| import org.springframework.context.annotation.Configuration; | ||
| import org.springframework.security.authentication.AuthenticationManager; | ||
| import org.springframework.security.config.annotation.authentication.configuration.AuthenticationConfiguration; | ||
| 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.crypto.bcrypt.BCryptPasswordEncoder; | ||
| import org.springframework.security.web.SecurityFilterChain; | ||
| import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter; | ||
| import org.springframework.web.cors.CorsConfiguration; | ||
| import org.springframework.web.cors.CorsConfigurationSource; | ||
|
|
||
| import java.util.Collections; | ||
|
|
||
| @Configuration | ||
| @EnableWebSecurity //스프링 시큐리티 필터(Security Config)가 스프링 필터 체인에 등록이 된다. | ||
| @RequiredArgsConstructor | ||
| public class SecurityConfig { | ||
| private final JwtAuthenticationEntryPoint jwtAuthenticationEntryPoint; | ||
| private final JwtAccessDeniedHandler jwtAccessDeniedHandler; | ||
| @Bean | ||
| public BCryptPasswordEncoder bCryptPasswordEncoder(){ | ||
| return new BCryptPasswordEncoder(); | ||
| } | ||
|
|
||
| @Bean | ||
| public AuthenticationManager authenticationManager(AuthenticationConfiguration configuration) throws Exception{ | ||
| return configuration.getAuthenticationManager(); | ||
| } | ||
|
|
||
| @Bean | ||
| public SecurityFilterChain filterChain(HttpSecurity http) throws Exception{ | ||
| http | ||
| .cors(cors -> cors.configurationSource(new CorsConfigurationSource() { | ||
| @Override | ||
| public CorsConfiguration getCorsConfiguration(HttpServletRequest request) { | ||
| CorsConfiguration configuration = new CorsConfiguration(); | ||
| configuration.setAllowedOrigins(Collections.singletonList("*")); | ||
| configuration.setAllowedMethods(Collections.singletonList("*")); | ||
| configuration.setAllowCredentials(true); | ||
| configuration.setAllowedHeaders(Collections.singletonList("*")); | ||
| configuration.setMaxAge(3600L); | ||
| configuration.setExposedHeaders(Collections.singletonList("Authorization")); | ||
| return configuration; | ||
| } | ||
| })) | ||
| .csrf(AbstractHttpConfigurer::disable) | ||
| .formLogin(AbstractHttpConfigurer::disable) | ||
| .httpBasic(AbstractHttpConfigurer::disable) | ||
| .sessionManagement((session) -> session | ||
| .sessionCreationPolicy(SessionCreationPolicy.STATELESS)) | ||
|
|
||
| .exceptionHandling((exception) -> exception | ||
| .authenticationEntryPoint(jwtAuthenticationEntryPoint) | ||
| .accessDeniedHandler(jwtAccessDeniedHandler)) | ||
|
|
||
| .authorizeHttpRequests((request) -> request | ||
| .requestMatchers("/login").permitAll() | ||
| .anyRequest().authenticated()) | ||
| .addFilterBefore(new JwtFilter(), UsernamePasswordAuthenticationFilter.class); | ||
| return http.build(); | ||
| } | ||
| } |
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,67 @@ | ||
| package org.momo.security.filter; | ||
|
|
||
| import com.fasterxml.jackson.databind.ObjectMapper; | ||
| import jakarta.servlet.FilterChain; | ||
| import jakarta.servlet.ServletException; | ||
| import jakarta.servlet.http.HttpServletRequest; | ||
| import jakarta.servlet.http.HttpServletResponse; | ||
| import lombok.RequiredArgsConstructor; | ||
| import lombok.extern.slf4j.Slf4j; | ||
| import org.momo.Member.Entity.Member; | ||
| import org.momo.common.BaseResponseDto; | ||
| import org.momo.common.status.ErrorStatus; | ||
| import org.momo.exception.handler.JwtExpiredHandler; | ||
| import org.momo.exception.handler.JwtInvalidHandler; | ||
| import org.momo.security.principal.PrincipalDetails; | ||
| import org.momo.util.JwtUtil; | ||
| import org.springframework.security.authentication.UsernamePasswordAuthenticationToken; | ||
| import org.springframework.security.core.Authentication; | ||
| import org.springframework.security.core.context.SecurityContextHolder; | ||
| import org.springframework.web.filter.OncePerRequestFilter; | ||
|
|
||
| import java.io.IOException; | ||
| import java.io.PrintWriter; | ||
|
|
||
| @RequiredArgsConstructor | ||
| @Slf4j | ||
| public class JwtFilter extends OncePerRequestFilter { | ||
| @Override | ||
| protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws ServletException, IOException { | ||
| String accessToken = request.getHeader("Authorization"); | ||
| if (accessToken == null) { | ||
| filterChain.doFilter(request,response); | ||
| return; | ||
| } | ||
| try{ | ||
| JwtUtil.validateAccessToken(accessToken); | ||
| String email = JwtUtil.getEmail(accessToken); | ||
|
|
||
| Member member = Member.builder() | ||
| .email(email) | ||
| .build(); | ||
| PrincipalDetails principalDetails = PrincipalDetails.createPrincipalDetails(member); | ||
|
|
||
| Authentication authentication = new UsernamePasswordAuthenticationToken(principalDetails, null, principalDetails.getAuthorities()); | ||
| SecurityContextHolder.getContext().setAuthentication(authentication); | ||
| }catch (JwtExpiredHandler e){ | ||
| BaseResponseDto<Object> baseResponseDto = BaseResponseDto.onFailure( | ||
| ErrorStatus.JWT_ACCESS_TOKEN_EXPIRED.getCode(), | ||
| ErrorStatus.JWT_ACCESS_TOKEN_EXPIRED.getMessage(), | ||
| null | ||
| ); | ||
| ObjectMapper objectMapper = new ObjectMapper(); | ||
| objectMapper.writeValue(response.getOutputStream(),baseResponseDto); | ||
| return; | ||
| }catch (JwtInvalidHandler e){ | ||
| BaseResponseDto<Object> baseResponseDto = BaseResponseDto.onFailure( | ||
| ErrorStatus.JWT_TOKEN_INVALID.getCode(), | ||
| ErrorStatus.JWT_TOKEN_INVALID.getMessage(), | ||
| null | ||
| ); | ||
| ObjectMapper objectMapper = new ObjectMapper(); | ||
| objectMapper.writeValue(response.getOutputStream(),baseResponseDto); | ||
| return; | ||
| } | ||
| filterChain.doFilter(request,response); | ||
| } | ||
| } |
28 changes: 28 additions & 0 deletions
28
Api/src/main/java/org/momo/security/handler/JwtAccessDeniedHandler.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,28 @@ | ||
| package org.momo.security.handler; | ||
|
|
||
| import com.fasterxml.jackson.databind.ObjectMapper; | ||
| import jakarta.servlet.ServletException; | ||
| import jakarta.servlet.http.HttpServletRequest; | ||
| import jakarta.servlet.http.HttpServletResponse; | ||
| import lombok.extern.slf4j.Slf4j; | ||
| import org.momo.common.BaseResponseDto; | ||
| import org.springframework.security.access.AccessDeniedException; | ||
| import org.springframework.security.web.access.AccessDeniedHandler; | ||
| import org.springframework.stereotype.Component; | ||
|
|
||
| import java.io.IOException; | ||
|
|
||
| @Slf4j | ||
| @Component | ||
| public class JwtAccessDeniedHandler implements AccessDeniedHandler { | ||
|
|
||
| @Override | ||
| public void handle(HttpServletRequest request, HttpServletResponse response, AccessDeniedException accessDeniedException) throws IOException, ServletException { | ||
| log.error("JwtAccessDeniedHandler 실행"); | ||
| response.setContentType("application/json"); | ||
| response.setStatus(HttpServletResponse.SC_FORBIDDEN); | ||
| BaseResponseDto<Object> baseResponseDto = BaseResponseDto.onFailure(403, "권한이 없습니다.", null); | ||
| ObjectMapper objectMapper = new ObjectMapper(); | ||
| objectMapper.writeValue(response.getOutputStream(), baseResponseDto); | ||
| } | ||
| } |
31 changes: 31 additions & 0 deletions
31
Api/src/main/java/org/momo/security/handler/JwtAuthenticationEntryPoint.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,31 @@ | ||
| package org.momo.security.handler; | ||
|
|
||
| import com.fasterxml.jackson.databind.ObjectMapper; | ||
| import jakarta.servlet.ServletException; | ||
| import jakarta.servlet.http.HttpServletRequest; | ||
| import jakarta.servlet.http.HttpServletResponse; | ||
| import lombok.extern.slf4j.Slf4j; | ||
| import org.momo.common.BaseResponseDto; | ||
| import org.momo.common.status.ErrorStatus; | ||
| import org.springframework.security.core.AuthenticationException; | ||
| import org.springframework.security.web.AuthenticationEntryPoint; | ||
| import org.springframework.stereotype.Component; | ||
|
|
||
| import java.io.IOException; | ||
|
|
||
| @Slf4j | ||
| @Component | ||
| public class JwtAuthenticationEntryPoint implements AuthenticationEntryPoint { | ||
| @Override | ||
| public void commence(HttpServletRequest request, HttpServletResponse response, AuthenticationException authException) throws IOException, ServletException { | ||
| log.error("JwtAuthenticationEntryPoint 실행"); | ||
| response.setContentType("application/json"); | ||
| BaseResponseDto<Object> baseResponseDto = | ||
| BaseResponseDto.onFailure( | ||
| ErrorStatus.JWT_TOKEN_NOT_FOUND.getCode(), | ||
| ErrorStatus.JWT_TOKEN_NOT_FOUND.getMessage(), | ||
| null); | ||
| ObjectMapper objectMapper = new ObjectMapper(); | ||
| objectMapper.writeValue(response.getOutputStream(), baseResponseDto); | ||
| } | ||
| } |
59 changes: 59 additions & 0 deletions
59
Api/src/main/java/org/momo/security/principal/PrincipalDetails.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,59 @@ | ||
| package org.momo.security.principal; | ||
|
|
||
| import lombok.RequiredArgsConstructor; | ||
| import org.momo.Member.Entity.Member; | ||
| import org.springframework.security.core.GrantedAuthority; | ||
| import org.springframework.security.core.userdetails.UserDetails; | ||
|
|
||
| import java.util.ArrayList; | ||
| import java.util.Collection; | ||
| @RequiredArgsConstructor | ||
| public class PrincipalDetails implements UserDetails { | ||
|
|
||
| private final Member member; | ||
|
|
||
| public static PrincipalDetails createPrincipalDetails(Member member) { | ||
| return new PrincipalDetails(member); | ||
| } | ||
| @Override | ||
| public Collection<? extends GrantedAuthority> getAuthorities() { | ||
| Collection<GrantedAuthority> collect = new ArrayList<>(); | ||
| collect.add(new GrantedAuthority() { | ||
| @Override | ||
| public String getAuthority() { | ||
| return null; | ||
| } | ||
| }); | ||
| return collect; | ||
| } | ||
|
|
||
| @Override | ||
| public String getPassword() { | ||
| return member.getPassword(); | ||
| } | ||
|
|
||
| @Override | ||
| public String getUsername() { | ||
| return member.getName(); | ||
| } | ||
|
|
||
| @Override | ||
| public boolean isAccountNonExpired() { | ||
| return true; | ||
| } | ||
|
|
||
| @Override | ||
| public boolean isAccountNonLocked() { | ||
| return true; | ||
| } | ||
|
|
||
| @Override | ||
| public boolean isCredentialsNonExpired() { | ||
| return true; | ||
| } | ||
|
|
||
| @Override | ||
| public boolean isEnabled() { | ||
| return true; | ||
| } | ||
| } |
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 |
|---|---|---|
|
|
@@ -11,4 +11,4 @@ spring: | |
| hibernate: | ||
| format_sql: true | ||
| use_sql_comments: true | ||
| # show_sql: true | ||
| # show_sql: true | ||
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
Binary file not shown.
Binary file not shown.
22 changes: 22 additions & 0 deletions
22
Auth/src/main/java/org/momo/controller/AuthController.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,22 @@ | ||
| package org.momo.controller; | ||
|
|
||
| import lombok.RequiredArgsConstructor; | ||
| import org.momo.Base.Entity.Base; | ||
| import org.momo.common.BaseResponseDto; | ||
| import org.momo.common.status.SuccessStatus; | ||
| import org.momo.dto.AuthRequest; | ||
| import org.momo.dto.AuthResponse; | ||
| import org.momo.service.AuthService; | ||
| import org.springframework.web.bind.annotation.PostMapping; | ||
| import org.springframework.web.bind.annotation.RequestBody; | ||
| import org.springframework.web.bind.annotation.RestController; | ||
|
|
||
| @RestController | ||
| @RequiredArgsConstructor | ||
| public class AuthController { | ||
| private final AuthService authService; | ||
| @PostMapping("/login") | ||
| public BaseResponseDto<AuthResponse.LoginResponseDto> login(@RequestBody AuthRequest.LoginDto loginDto) { | ||
| return BaseResponseDto.of(SuccessStatus.LOGIN_SUCCESS.getCode(),SuccessStatus.LOGIN_SUCCESS.getMessage(), authService.login(loginDto)); | ||
| } | ||
| } |
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.
Uh oh!
There was an error while loading. Please reload this page.