-
Notifications
You must be signed in to change notification settings - Fork 0
Feater 1 #2
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
cloudwi
wants to merge
2
commits into
main
Choose a base branch
from
feater_1
base: 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
Feater 1 #2
Changes from all commits
Commits
Show all changes
2 commits
Select commit
Hold shift + click to select a range
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
78 changes: 78 additions & 0 deletions
78
...n/java/com/project/musinsastocknotificationbot/common/config/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,78 @@ | ||
| package com.project.musinsastocknotificationbot.common.config.security; | ||
|
|
||
| import com.project.musinsastocknotificationbot.common.config.security.oauth2.CustomOAuth2UserService; | ||
| import com.project.musinsastocknotificationbot.common.config.security.oauth2.OAuth2AuthenticationSuccessHandler; | ||
| import com.project.musinsastocknotificationbot.common.filter.JwtAuthenticationFilter; | ||
| import java.util.Arrays; | ||
| import java.util.List; | ||
| 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.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 org.springframework.web.cors.UrlBasedCorsConfigurationSource; | ||
|
|
||
| @Configuration | ||
| @EnableWebSecurity | ||
| public class SecurityConfig { | ||
|
|
||
| private final CustomOAuth2UserService customOAuth2UserService; | ||
| private final OAuth2AuthenticationSuccessHandler oAuth2AuthorizationSuccessHandler; | ||
| private final JwtAuthenticationFilter jwtAuthenticationFilter; | ||
|
|
||
| public SecurityConfig(CustomOAuth2UserService customOAuth2UserService, | ||
| OAuth2AuthenticationSuccessHandler oAuth2AuthorizationSuccessHandler, | ||
| JwtAuthenticationFilter jwtAuthenticationFilter) { | ||
| this.customOAuth2UserService = customOAuth2UserService; | ||
| this.oAuth2AuthorizationSuccessHandler = oAuth2AuthorizationSuccessHandler; | ||
| this.jwtAuthenticationFilter = jwtAuthenticationFilter; | ||
| } | ||
|
|
||
| @Bean | ||
| public BCryptPasswordEncoder bCryptPasswordEncoder() { | ||
| return new BCryptPasswordEncoder(); | ||
| } | ||
|
|
||
| @Bean | ||
| public SecurityFilterChain filterChain(HttpSecurity http) throws Exception { | ||
| http | ||
| .csrf().disable() | ||
| .sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS) | ||
| .and() | ||
| .formLogin().disable() | ||
| .httpBasic().disable() | ||
| .authorizeHttpRequests() | ||
| .requestMatchers(HttpMethod.OPTIONS).permitAll() | ||
| .requestMatchers("/h2-console/**", "favicon.ico").permitAll() | ||
| .anyRequest().permitAll() | ||
| .and() | ||
| .headers().frameOptions().sameOrigin() | ||
| .and() | ||
| .oauth2Login() | ||
| .userInfoEndpoint().userService(customOAuth2UserService) | ||
| .and() | ||
| .successHandler(oAuth2AuthorizationSuccessHandler); | ||
|
|
||
| http.addFilterBefore(jwtAuthenticationFilter, UsernamePasswordAuthenticationFilter.class); | ||
|
|
||
| return http.build(); | ||
| } | ||
|
|
||
| @Bean | ||
| CorsConfigurationSource corsConfigurationSource() { | ||
| CorsConfiguration configuration = new CorsConfiguration(); | ||
| configuration.setAllowedOrigins(Arrays.asList("http://localhost:3000")); | ||
| configuration.setAllowedMethods(Arrays.asList("*")); | ||
| configuration.setAllowedHeaders(List.of("*")); | ||
| configuration.setAllowCredentials(true); | ||
| UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource(); | ||
| source.registerCorsConfiguration("/**", configuration); | ||
| return source; | ||
| } | ||
| } |
23 changes: 23 additions & 0 deletions
23
...ject/musinsastocknotificationbot/common/config/security/jwt/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,23 @@ | ||
| package com.project.musinsastocknotificationbot.common.config.security.jwt; | ||
|
|
||
| import com.project.musinsastocknotificationbot.domain.member.service.MemberService; | ||
| 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; | ||
|
|
||
| @Service | ||
| public class CustomUserDetailsService implements UserDetailsService { | ||
|
|
||
| private final MemberService memberService; | ||
|
|
||
| public CustomUserDetailsService(MemberService memberService) { | ||
| this.memberService = memberService; | ||
| } | ||
|
|
||
| @Override | ||
| public UserDetails loadUserByUsername(String memberId) throws UsernameNotFoundException { | ||
| long id = Long.parseLong(memberId); | ||
| return memberService.findById(id); | ||
| } | ||
| } |
82 changes: 82 additions & 0 deletions
82
.../com/project/musinsastocknotificationbot/common/config/security/jwt/JwtTokenProvider.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,82 @@ | ||
| package com.project.musinsastocknotificationbot.common.config.security.jwt; | ||
|
|
||
| import io.jsonwebtoken.Claims; | ||
| import io.jsonwebtoken.Jwts; | ||
| import io.jsonwebtoken.SignatureAlgorithm; | ||
| import jakarta.servlet.http.HttpServletRequest; | ||
| import java.time.Duration; | ||
| import java.util.Date; | ||
| import org.springframework.beans.factory.annotation.Value; | ||
| import org.springframework.security.authentication.UsernamePasswordAuthenticationToken; | ||
| import org.springframework.security.core.Authentication; | ||
| import org.springframework.security.core.userdetails.UserDetails; | ||
| import org.springframework.stereotype.Component; | ||
|
|
||
| @Component | ||
| public class JwtTokenProvider { | ||
|
|
||
| private final CustomUserDetailsService customUserDetailsService; | ||
| private final String tokenSecretKey; | ||
| private final String jwtTokenHeaderName; | ||
| private static final long ACCESS_TOKEN_EXPIRED_TIME = Duration.ofMinutes(1).toMillis(); | ||
|
|
||
| public JwtTokenProvider(CustomUserDetailsService customUserDetailsService, @Value("${jwt.secret}") String tokenSecretKey, | ||
| @Value("${jwt.header}") String jwtTokenHeaderName) { | ||
| this.customUserDetailsService = customUserDetailsService; | ||
| this.tokenSecretKey = tokenSecretKey; | ||
| this.jwtTokenHeaderName = jwtTokenHeaderName; | ||
| } | ||
|
|
||
| public String createToken(long memberId) { | ||
| Claims claims = Jwts.claims().setSubject(String.valueOf(memberId)); | ||
|
|
||
| Date now = new Date(); | ||
| Date validity = new Date(now.getTime() + ACCESS_TOKEN_EXPIRED_TIME); | ||
|
|
||
| return Jwts.builder() | ||
| .setClaims(claims) | ||
| .setIssuedAt(now) | ||
| .setExpiration(validity) | ||
| .signWith(SignatureAlgorithm.HS256, tokenSecretKey) | ||
| .compact(); | ||
| } | ||
|
|
||
| public String removeBearer(String bearerToken) { | ||
| return bearerToken.substring("Bearer ".length()); | ||
| } | ||
|
|
||
| public boolean validateToken(String token) { | ||
| try { | ||
| Jwts.parser().setSigningKey(tokenSecretKey).parseClaimsJws(token); | ||
| return true; | ||
| } catch (Exception e) { | ||
| return false; | ||
| } | ||
| } | ||
|
|
||
| public String getMemberId(String token) { | ||
| return Jwts.parser() | ||
| .setSigningKey(tokenSecretKey) | ||
| .parseClaimsJws(token) | ||
| .getBody() | ||
| .getSubject(); | ||
| } | ||
|
|
||
| public Authentication getAuthentication(String token) { | ||
| String memberId = getMemberId(token); | ||
| UserDetails userDetails = customUserDetailsService.loadUserByUsername(memberId); | ||
| return new UsernamePasswordAuthenticationToken(userDetails, "", userDetails.getAuthorities()); | ||
| } | ||
|
|
||
|
|
||
|
|
||
| public String resolveToken(HttpServletRequest request) { | ||
| String token = request.getHeader(jwtTokenHeaderName); | ||
|
|
||
| if (token != null) { | ||
| return removeBearer(token); | ||
| } else { | ||
| return null; | ||
| } | ||
| } | ||
| } | ||
36 changes: 36 additions & 0 deletions
36
...ct/musinsastocknotificationbot/common/config/security/oauth2/CustomOAuth2UserService.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,36 @@ | ||
| package com.project.musinsastocknotificationbot.common.config.security.oauth2; | ||
|
|
||
| import com.project.musinsastocknotificationbot.domain.member.entity.vo.Role; | ||
| import java.util.Collections; | ||
| import org.springframework.security.core.authority.SimpleGrantedAuthority; | ||
| import org.springframework.security.oauth2.client.userinfo.DefaultOAuth2UserService; | ||
| import org.springframework.security.oauth2.client.userinfo.OAuth2UserRequest; | ||
| import org.springframework.security.oauth2.client.userinfo.OAuth2UserService; | ||
| import org.springframework.security.oauth2.core.OAuth2AuthenticationException; | ||
| import org.springframework.security.oauth2.core.user.DefaultOAuth2User; | ||
| import org.springframework.security.oauth2.core.user.OAuth2User; | ||
| import org.springframework.stereotype.Service; | ||
|
|
||
| @Service | ||
| public class CustomOAuth2UserService implements OAuth2UserService<OAuth2UserRequest, OAuth2User> { | ||
|
|
||
| @Override | ||
| public OAuth2User loadUser(OAuth2UserRequest userRequest) throws OAuth2AuthenticationException { | ||
| OAuth2UserService<OAuth2UserRequest, OAuth2User> oAuth2UserService = new DefaultOAuth2UserService(); | ||
| OAuth2User oAuth2User = oAuth2UserService.loadUser(userRequest); | ||
|
|
||
| String registrationId = userRequest.getClientRegistration() | ||
| .getRegistrationId(); | ||
|
|
||
| String userNameAttributeName = userRequest.getClientRegistration() | ||
cloudwi marked this conversation as resolved.
Show resolved
Hide resolved
|
||
| .getProviderDetails() | ||
| .getUserInfoEndpoint() | ||
| .getUserNameAttributeName(); | ||
|
|
||
| OAuth2Attribute oAuth2Attribute = OAuth2Attribute.of(Provider.of(registrationId), oAuth2User.getAttributes()); | ||
|
|
||
| return new DefaultOAuth2User( | ||
| Collections.singleton(new SimpleGrantedAuthority(Role.USER.getKey())), | ||
| oAuth2Attribute.convertToMap(), userNameAttributeName); | ||
| } | ||
| } | ||
48 changes: 48 additions & 0 deletions
48
...om/project/musinsastocknotificationbot/common/config/security/oauth2/OAuth2Attribute.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,48 @@ | ||
| package com.project.musinsastocknotificationbot.common.config.security.oauth2; | ||
|
|
||
| import java.util.HashMap; | ||
| import java.util.Map; | ||
|
|
||
| public record OAuth2Attribute( | ||
| Map<String, Object> attributes, | ||
| Provider provider, | ||
| String email | ||
| ) { | ||
|
|
||
| public static OAuth2Attribute of(Provider provider , | ||
| Map<String, Object> attributes) { | ||
| switch (provider) { | ||
| case NAVER -> { | ||
| return ofNaver(provider, attributes); | ||
| } | ||
| case KAKAO -> { | ||
| return ofKakao(provider, attributes); | ||
| } | ||
| default -> throw new RuntimeException("정상적인 url이 아닙니다."); | ||
|
|
||
| } | ||
| } | ||
|
|
||
| private static OAuth2Attribute ofNaver(Provider provider, | ||
| Map<String, Object> attributes) { | ||
| Map<String, Object> response = (Map<String, Object>) attributes.get("response"); | ||
|
|
||
| return new OAuth2Attribute(attributes, provider, (String) response.get("email")); | ||
| } | ||
|
|
||
| private static OAuth2Attribute ofKakao(Provider provider, | ||
| Map<String, Object> attributes) { | ||
| Map<String, Object> kakaoAccount = (Map<String, Object>) attributes.get("kakao_account"); | ||
|
|
||
| return new OAuth2Attribute(attributes, provider, (String) kakaoAccount.get("email")); | ||
| } | ||
|
|
||
| public Map<String, Object> convertToMap() { | ||
| Map<String, Object> map = new HashMap<>(); | ||
| map.put("response", this.attributes); | ||
| map.put("provider", this.provider); | ||
| map.put("email", this.email); | ||
|
|
||
| return map; | ||
| } | ||
| } |
70 changes: 70 additions & 0 deletions
70
...tocknotificationbot/common/config/security/oauth2/OAuth2AuthenticationSuccessHandler.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,70 @@ | ||
| package com.project.musinsastocknotificationbot.common.config.security.oauth2; | ||
|
|
||
| import com.project.musinsastocknotificationbot.common.config.security.jwt.JwtTokenProvider; | ||
| import com.project.musinsastocknotificationbot.domain.member.entity.Member; | ||
| import com.project.musinsastocknotificationbot.domain.member.entity.vo.Role; | ||
| import com.project.musinsastocknotificationbot.domain.member.repository.MemberRepository; | ||
| import jakarta.servlet.http.HttpServletRequest; | ||
| import jakarta.servlet.http.HttpServletResponse; | ||
| import java.io.IOException; | ||
| import java.util.Map; | ||
| import org.springframework.security.core.Authentication; | ||
| import org.springframework.security.oauth2.core.user.OAuth2User; | ||
| import org.springframework.security.web.authentication.SimpleUrlAuthenticationSuccessHandler; | ||
| import org.springframework.stereotype.Component; | ||
| import org.springframework.web.util.UriComponentsBuilder; | ||
|
|
||
| @Component | ||
| public class OAuth2AuthenticationSuccessHandler extends SimpleUrlAuthenticationSuccessHandler { | ||
|
|
||
| private final MemberRepository memberRepository; | ||
| private final JwtTokenProvider jwtTokenProvider; | ||
|
|
||
| public OAuth2AuthenticationSuccessHandler(MemberRepository memberRepository, | ||
| JwtTokenProvider jwtTokenProvider) { | ||
| this.memberRepository = memberRepository; | ||
| this.jwtTokenProvider = jwtTokenProvider; | ||
| } | ||
|
|
||
| @Override | ||
| public void onAuthenticationSuccess(HttpServletRequest request, HttpServletResponse response, | ||
| Authentication authentication) throws IOException { | ||
| var principal = authentication.getPrincipal(); | ||
|
|
||
| if (principal instanceof OAuth2User oauth2User) { | ||
|
|
||
| Member member = saveOrUpdate(oauth2User.getAttributes()); | ||
| String targetUrl = determineTargetUrl(member); | ||
| getRedirectStrategy().sendRedirect(request, response, targetUrl); | ||
| } | ||
| } | ||
|
|
||
| private Member saveOrUpdate(Map<String, Object> attributes) { | ||
| String email = (String) attributes.get("email"); | ||
| Provider provider = (Provider) attributes.get("provider"); | ||
|
|
||
| Member member = memberRepository.findByEmail(email) | ||
| .map(entity -> entity.update(provider)) | ||
| .orElse(toEntity(attributes)); | ||
|
|
||
| return memberRepository.save(member); | ||
| } | ||
|
|
||
| private Member toEntity(Map<String, Object> attributes) { | ||
| String email = (String) attributes.get("email"); | ||
| Provider provider = (Provider) attributes.get("provider"); | ||
| Role role = Role.USER; | ||
|
|
||
| return Member.from(email, provider, role); | ||
| } | ||
|
|
||
| protected String determineTargetUrl(Member member) { | ||
|
|
||
| String targetUrl = "http://localhost:3000/"; | ||
|
|
||
| return UriComponentsBuilder.fromOriginHeader(targetUrl) | ||
| .queryParam("Authorization", jwtTokenProvider.createToken(member.getId())) | ||
| .build() | ||
| .toUriString(); | ||
| } | ||
| } |
25 changes: 25 additions & 0 deletions
25
.../java/com/project/musinsastocknotificationbot/common/config/security/oauth2/Provider.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,25 @@ | ||
| package com.project.musinsastocknotificationbot.common.config.security.oauth2; | ||
|
|
||
| import java.util.Arrays; | ||
|
|
||
| public enum Provider { | ||
|
|
||
| NAVER("naver"), KAKAO("kakao"), DEFAULT("default"); | ||
|
|
||
| private final String key; | ||
|
|
||
| Provider(String key) { | ||
| this.key = key; | ||
| } | ||
|
|
||
| public String getKey() { | ||
| return this.key; | ||
| } | ||
|
|
||
| public static Provider of(String key) { | ||
| return Arrays.stream(Provider.values()) | ||
| .filter(provider -> provider.key.equals(key)) | ||
| .findFirst() | ||
| .orElse(Provider.DEFAULT); | ||
| } | ||
| } |
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
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.