-
Notifications
You must be signed in to change notification settings - Fork 3
Feature/sec #31
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
Merged
Merged
Feature/sec #31
Changes from all commits
Commits
Show all changes
14 commits
Select commit
Hold shift + click to select a range
b766cd1
feat: Spring Security JWT 인증 필터 및 Security 설정 추가
sat7312 ec64910
refactor: TradeController userId를 @AuthenticationPrincipal로 교체
sat7312 30e248e
로그인 입력값 검증 추가
sat7312 b47e404
fix: BaseInitData 초기 데이터 비밀번호 BCrypt 적용 및 유효성 조건
sat7312 414fe51
fix: Users 엔터티 password 컬럼 길이 255로 확장
sat7312 683f37d
Merge remote-tracking branch 'origin/dev' into feature/sec
sat7312 5d228c5
feat: Swagger JWT Bearer 인증 스키마 추가
sat7312 bc9cff4
feat: 회원가입 시 예수금 5천만원 계좌 자동 생성
sat7312 986ae42
chore: origin/dev 병합 및 SpringDoc 충돌 해결
sat7312 591a687
refactor: AssetController userId를 @AuthenticationPrincipal로 교체 및 Stoc…
sat7312 2f6ac1d
refactor: UserRes에서 refreshToken 필드 제거 (HttpOnly 쿠키 방식으로 전환 시작)
sat7312 678c00f
refactor: TokenReq 삭제 (refreshToken을 바디 대신 쿠키로 수신)
sat7312 bfe1c5b
refactor: UsersService logout/reissueToken 파라미터를 String refreshToken으…
sat7312 ca0606d
feat: refreshToken을 HttpOnly 쿠키 방식으로 전환
sat7312 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
18 changes: 0 additions & 18 deletions
18
src/main/java/com/back/together02be/global/config/CorsConfig.java
This file was deleted.
Oops, something went wrong.
37 changes: 0 additions & 37 deletions
37
src/main/java/com/back/together02be/global/config/SecurityConfig.java
This file was deleted.
Oops, something went wrong.
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/back/together02be/global/security/CustomAuthenticationFilter.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.back.together02be.global.security; | ||
|
|
||
| import com.back.together02be.global.util.JwtUtil; | ||
| import jakarta.servlet.FilterChain; | ||
| import jakarta.servlet.ServletException; | ||
| import jakarta.servlet.http.HttpServletRequest; | ||
| import jakarta.servlet.http.HttpServletResponse; | ||
| import lombok.RequiredArgsConstructor; | ||
| import org.springframework.beans.factory.annotation.Value; | ||
| import org.springframework.security.authentication.UsernamePasswordAuthenticationToken; | ||
| import org.springframework.security.core.Authentication; | ||
| import org.springframework.security.core.context.SecurityContextHolder; | ||
| import org.springframework.security.core.userdetails.UserDetails; | ||
| import org.springframework.stereotype.Component; | ||
| import org.springframework.web.filter.OncePerRequestFilter; | ||
|
|
||
| import java.io.IOException; | ||
| import java.util.Map; | ||
|
|
||
| @Component | ||
| @RequiredArgsConstructor | ||
| public class CustomAuthenticationFilter extends OncePerRequestFilter { | ||
|
|
||
| private final CustomUserDetailsService userDetailsService; | ||
|
|
||
| @Value("${jwt.secret}") | ||
| private String jwtSecret; | ||
|
|
||
| @Override | ||
| protected void doFilterInternal( | ||
| HttpServletRequest request, | ||
| HttpServletResponse response, | ||
| FilterChain filterChain | ||
| ) throws ServletException, IOException { | ||
|
|
||
| // 헤더에서 토큰 꺼냄 | ||
| String authHeader = request.getHeader("Authorization"); | ||
|
|
||
| // 토큰 없으면 그냥 통과 | ||
| if (authHeader == null || !authHeader.startsWith("Bearer ")) { | ||
| filterChain.doFilter(request, response); | ||
| return; | ||
| } | ||
|
|
||
| // "Bearer eyJhbGciOiJIUzI1NiJ9..." -> 7부터 토큰 | ||
| String token = authHeader.substring(7); | ||
|
|
||
| Map<String, Object> payload = JwtUtil.payloadOrNull(token, jwtSecret); | ||
|
|
||
| // JWT 검증 후 유효하면 Security Context에 저장 | ||
| if (payload != null) { | ||
| String username = (String) payload.get("username"); | ||
| UserDetails userDetails = userDetailsService.loadUserByUsername(username); | ||
|
|
||
| Authentication authentication = new UsernamePasswordAuthenticationToken( | ||
| userDetails, | ||
| null, | ||
| userDetails.getAuthorities() | ||
| ); | ||
|
|
||
| SecurityContextHolder.getContext().setAuthentication(authentication); | ||
| } | ||
|
|
||
| filterChain.doFilter(request, response); | ||
| } | ||
| } |
32 changes: 32 additions & 0 deletions
32
src/main/java/com/back/together02be/global/security/CustomUserDetailsService.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,32 @@ | ||
| package com.back.together02be.global.security; | ||
|
|
||
| import com.back.together02be.users.entity.Users; | ||
| import com.back.together02be.users.repository.UsersRepository; | ||
| import lombok.RequiredArgsConstructor; | ||
| import org.springframework.security.core.userdetails.UserDetails; | ||
| import org.springframework.security.core.userdetails.UserDetailsService; | ||
| import org.springframework.security.core.userdetails.UsernameNotFoundException; | ||
| import org.springframework.stereotype.Service; | ||
|
|
||
| import java.util.List; | ||
|
|
||
| @Service | ||
| @RequiredArgsConstructor | ||
| public class CustomUserDetailsService implements UserDetailsService { | ||
|
|
||
| private final UsersRepository usersRepository; | ||
|
|
||
| @Override | ||
| public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException { | ||
| Users user = usersRepository.findByUsername(username) | ||
| .orElseThrow(() -> new UsernameNotFoundException("존재하지 않는 아이디입니다: " + username)); | ||
|
|
||
| return new SecurityUser( | ||
| user.getId(), | ||
| user.getUsername(), | ||
| user.getPassword(), | ||
| user.getNickname(), | ||
| List.of() | ||
| ); | ||
| } | ||
| } |
96 changes: 96 additions & 0 deletions
96
src/main/java/com/back/together02be/global/security/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,96 @@ | ||
| package com.back.together02be.global.security; | ||
|
|
||
| import lombok.RequiredArgsConstructor; | ||
| import org.springframework.context.annotation.Bean; | ||
| import org.springframework.context.annotation.Configuration; | ||
| import org.springframework.http.HttpMethod; | ||
| 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.crypto.password.PasswordEncoder; | ||
| import org.springframework.security.web.SecurityFilterChain; | ||
| import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter; | ||
| import org.springframework.security.web.header.writers.frameoptions.XFrameOptionsHeaderWriter; | ||
| import org.springframework.web.cors.CorsConfiguration; | ||
| import org.springframework.web.cors.UrlBasedCorsConfigurationSource; | ||
|
|
||
| import java.util.List; | ||
|
|
||
| @Configuration | ||
| @EnableWebSecurity | ||
| @RequiredArgsConstructor | ||
| public class SecurityConfig { | ||
|
|
||
| private final CustomAuthenticationFilter jwtAuthFilter; | ||
|
|
||
| @Bean | ||
| public PasswordEncoder passwordEncoder() { | ||
| return new BCryptPasswordEncoder(); | ||
| } | ||
|
|
||
| @Bean | ||
| public SecurityFilterChain filterChain(HttpSecurity http) throws Exception { | ||
| http | ||
| .csrf(AbstractHttpConfigurer::disable) | ||
| .sessionManagement(session -> | ||
| session.sessionCreationPolicy(SessionCreationPolicy.STATELESS) | ||
| ) | ||
| .authorizeHttpRequests(authorizeHttpRequests -> authorizeHttpRequests | ||
| .requestMatchers("/favicon.ico").permitAll() | ||
| .requestMatchers("/h2-console/**").permitAll() | ||
| .requestMatchers("/swagger-ui/**", "/v3/api-docs/**").permitAll() | ||
| .requestMatchers(HttpMethod.POST, | ||
| "/api/users/signup", | ||
| "/api/users/login", | ||
| "/api/users/token" | ||
| ) | ||
| .permitAll() | ||
| .requestMatchers(HttpMethod.POST, "/api/users/logout").authenticated() | ||
| .anyRequest().authenticated() | ||
| ) | ||
|
|
||
| .headers(headers -> headers | ||
| .addHeaderWriter(new XFrameOptionsHeaderWriter( | ||
| XFrameOptionsHeaderWriter.XFrameOptionsMode.SAMEORIGIN) | ||
| ) | ||
| ) | ||
| .addFilterBefore(jwtAuthFilter, UsernamePasswordAuthenticationFilter.class) | ||
| .exceptionHandling(exceptionHandling -> exceptionHandling | ||
| .authenticationEntryPoint((request, response, authenticationException) -> { | ||
| response.setContentType("application/json; charset=UTF-8"); | ||
| response.setStatus(401); | ||
| response.getWriter().write( | ||
| """ | ||
| {"message": "로그인 후 이용해주세요.", "data": null} | ||
| """ | ||
| ); | ||
| }) | ||
| .accessDeniedHandler((request, response, authenticationException) -> { | ||
| response.setContentType("application/json; charset=UTF-8"); | ||
| response.setStatus(403); | ||
| response.getWriter().write( | ||
| """ | ||
| {"message": "권한이 없습니다.", "data": null} | ||
| """ | ||
| ); | ||
| }) | ||
| ); | ||
| return http.build(); | ||
| } | ||
|
|
||
| // 기존의 CORS 설정을 옮김 | ||
| @Bean | ||
| public UrlBasedCorsConfigurationSource corsConfigurationSource() { | ||
| CorsConfiguration configuration = new CorsConfiguration(); | ||
| configuration.setAllowedOriginPatterns(List.of("*")); | ||
| configuration.setAllowedMethods(List.of("GET", "POST", "PUT", "PATCH", "DELETE", "OPTIONS")); | ||
| configuration.setAllowedHeaders(List.of("*")); | ||
| configuration.setAllowCredentials(true); | ||
|
|
||
| UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource(); | ||
| source.registerCorsConfiguration("/**", configuration); | ||
| return source; | ||
| } | ||
| } |
26 changes: 26 additions & 0 deletions
26
src/main/java/com/back/together02be/global/security/SecurityUser.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,26 @@ | ||
| package com.back.together02be.global.security; | ||
|
|
||
| import lombok.Getter; | ||
| import org.springframework.security.core.GrantedAuthority; | ||
| import org.springframework.security.core.userdetails.User; | ||
|
|
||
| import java.util.Collection; | ||
|
|
||
| @Getter | ||
| public class SecurityUser extends User { | ||
|
|
||
| private final Long id; | ||
| private final String nickname; | ||
|
|
||
| public SecurityUser( | ||
| Long id, | ||
| String username, | ||
| String password, | ||
| String nickname, | ||
| Collection<? extends GrantedAuthority> authorities | ||
| ) { | ||
| super(username, password, authorities); | ||
| this.id = id; | ||
| this.nickname = nickname; | ||
| } | ||
| } | ||
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.