Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
10 changes: 10 additions & 0 deletions build.gradle
Original file line number Diff line number Diff line change
Expand Up @@ -28,6 +28,16 @@ dependencies {
implementation 'org.telegram:telegrambotsextensions:6.5.0'
//mail
implementation 'org.springframework.boot:spring-boot-starter-mail'
//security
implementation 'org.springframework.boot:spring-boot-starter-security'
testImplementation 'org.springframework.security:spring-security-test'
//oauth
implementation 'org.springframework.boot:spring-boot-starter-oauth2-client'
//jwt
// jwt
implementation 'io.jsonwebtoken:jjwt-api:0.11.5'
implementation 'io.jsonwebtoken:jjwt-impl:0.11.5'
implementation 'io.jsonwebtoken:jjwt-jackson:0.11.5'
}

tasks.named('test') {
Expand Down
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;
}
}
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);
}
}
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;
}
}
}
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()
.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);
}
}
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;
}
}
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();
}
}
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);
}
}
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
package com.project.musinsastocknotificationbot.common.config;
package com.project.musinsastocknotificationbot.common.filter;


import jakarta.servlet.*;
Expand Down Expand Up @@ -29,4 +29,6 @@ public void doFilter(ServletRequest req, ServletResponse res, FilterChain chain)
chain.doFilter(req, res);
}
}


}
Loading