Skip to content

Commit

Permalink
SCRUM-66 fix: 시큐리티 에러 수정
Browse files Browse the repository at this point in the history
  • Loading branch information
yeopyeop-82 committed Aug 19, 2024
1 parent dad5443 commit 9b2c422
Show file tree
Hide file tree
Showing 17 changed files with 90 additions and 186 deletions.
12 changes: 6 additions & 6 deletions build.gradle
Original file line number Diff line number Diff line change
Expand Up @@ -57,12 +57,12 @@ dependencies {
// Mysql
runtimeOnly('com.mysql:mysql-connector-j')

// 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'
implementation 'commons-codec:commons-codec:1.13'
implementation 'com.auth0:java-jwt:3.13.0'
// // 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'
// implementation 'commons-codec:commons-codec:1.13'
// implementation 'com.auth0:java-jwt:3.13.0'

// Redis
implementation 'org.springframework.boot:spring-boot-starter-data-redis'
Expand Down
114 changes: 33 additions & 81 deletions src/main/java/com/kakaoteck/golagola/config/SecurityConfig.java
Original file line number Diff line number Diff line change
@@ -1,37 +1,29 @@
package com.kakaoteck.golagola.config;


import com.kakaoteck.golagola.jwt.JWTFilter;
import com.kakaoteck.golagola.jwt.JWTUtil;
import com.kakaoteck.golagola.oauth2.CustomSuccessHandler;
import com.kakaoteck.golagola.security.filter.JwtAuthenticationFilter;
import com.kakaoteck.golagola.security.jwt.JWTFilter;
import com.kakaoteck.golagola.security.jwt.JWTUtil;
import com.kakaoteck.golagola.security.oauth2.CustomSuccessHandler;
import com.kakaoteck.golagola.service.CustomOAuth2UserService;
import jakarta.servlet.http.HttpServletRequest;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.Customizer;
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.oauth2.client.web.OAuth2LoginAuthenticationFilter;
import org.springframework.security.web.SecurityFilterChain;
import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter;
import org.springframework.security.web.authentication.logout.LogoutHandler;
import org.springframework.web.cors.CorsConfiguration;
import org.springframework.web.cors.CorsConfigurationSource;

import java.util.Collections;

import com.kakaoteck.golagola.security.filter.JwtAuthenticationFilter;
import lombok.RequiredArgsConstructor;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.authentication.AuthenticationProvider;
import org.springframework.security.config.annotation.method.configuration.EnableMethodSecurity;
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.web.SecurityFilterChain;
import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter;
import org.springframework.security.web.authentication.logout.LogoutHandler;

import static org.springframework.security.config.http.SessionCreationPolicy.STATELESS;

Expand All @@ -40,79 +32,61 @@
@Configuration
@EnableWebSecurity
public class SecurityConfig {

private final CustomOAuth2UserService customOAuth2UserService;
private final CustomSuccessHandler customSuccessHandler;
private final JWTUtil jwtUtil;
private final JwtAuthenticationFilter jwtAuthFilter;
private final AuthenticationProvider authenticationProvider;
private final LogoutHandler logoutHandler;

public SecurityConfig(CustomOAuth2UserService customOAuth2UserService, CustomSuccessHandler customSuccessHandler, JWTUtil jwtUtil) {

this.customOAuth2UserService = customOAuth2UserService;
this.customSuccessHandler = customSuccessHandler;
this.jwtUtil = jwtUtil;
}

@Bean
public SecurityFilterChain filterChain(HttpSecurity http) throws Exception{
public SecurityFilterChain securityFilterChain(HttpSecurity http) throws Exception {

http.cors(corsCustomizer -> corsCustomizer.configurationSource(new CorsConfigurationSource() {

@Override
public CorsConfiguration getCorsConfiguration(HttpServletRequest request) {

CorsConfiguration configuration = new CorsConfiguration();

configuration.setAllowedOrigins(Collections.singletonList("http://localhost:3000"));
configuration.setAllowedMethods(Collections.singletonList("*"));
configuration.setAllowCredentials(true);
configuration.setAllowedHeaders(Collections.singletonList("*"));
configuration.setMaxAge(3600L);

configuration.setExposedHeaders(Collections.singletonList("Set-Cookie"));
configuration.setExposedHeaders(Collections.singletonList("Authorization"));

return configuration;
@Override
public CorsConfiguration getCorsConfiguration(HttpServletRequest request) {
CorsConfiguration configuration = new CorsConfiguration();
configuration.setAllowedOrigins(Collections.singletonList("http://localhost:3000"));
configuration.setAllowedMethods(Collections.singletonList("*"));
configuration.setAllowCredentials(true);
configuration.setAllowedHeaders(Collections.singletonList("*"));
configuration.setMaxAge(3600L);
configuration.setExposedHeaders(Collections.singletonList("Authorization"));
return configuration;
}
}));

// CSRF 보호 비활성화
http.csrf(csrf -> csrf.disable());
http.csrf(AbstractHttpConfigurer::disable);

// 폼 로그인 비활성화
http.formLogin(login -> login.disable());
http.formLogin(AbstractHttpConfigurer::disable);

// HTTP Basic 인증 비활성화
http.httpBasic(basic -> basic.disable());
http.httpBasic(AbstractHttpConfigurer::disable);

//JWTFilter 추가
// http.addFilterBefore(new JWTFilter(jwtUtil), UsernamePasswordAuthenticationFilter.class);
// OAuth2 로그인 설정
http.oauth2Login(oauth2 -> oauth2.userInfoEndpoint(userInfo -> userInfo.userService(customOAuth2UserService))
.successHandler(customSuccessHandler));

// 재로그인 방지를 위한 JWTFilter 선행해서 실행
// JWT 필터 설정
// http.addFilterBefore(jwtAuthFilter, UsernamePasswordAuthenticationFilter.class);
http.addFilterAfter(new JWTFilter(jwtUtil), OAuth2LoginAuthenticationFilter.class);

// 경로별 인가 작업
http.authorizeHttpRequests(auth -> auth
.requestMatchers(WHITE_LIST_URL).permitAll()
.anyRequest().authenticated());

//oauth2
http.oauth2Login(oauth2 -> oauth2.userInfoEndpoint((userInfoEndpointConfig) -> userInfoEndpointConfig
.userService(customOAuth2UserService))
.successHandler(customSuccessHandler)
);
// 세션 설정: STATELESS
http.sessionManagement(session -> session.sessionCreationPolicy(STATELESS));

//경로별 인가 작업
http.authorizeHttpRequests((auth) -> auth
.requestMatchers("/").permitAll()
.anyRequest().authenticated()); // 나머지 주소는 인증

//세션 설정 : STATELESS
http.sessionManagement((session) -> session
.sessionCreationPolicy(SessionCreationPolicy.STATELESS));
// 로그아웃 설정
http.logout(logout -> logout.logoutUrl("/api/v1/auth/logout").addLogoutHandler(logoutHandler));

return http.build();
}



private static final String[] WHITE_LIST_URL = {
"/api/v1/auth/**",
Expand All @@ -127,26 +101,4 @@ public CorsConfiguration getCorsConfiguration(HttpServletRequest request) {
"/webjars/**",
"/swagger-ui.html"
};

@Bean
public SecurityFilterChain securityFilterChain(HttpSecurity http) throws Exception {
http
.csrf(AbstractHttpConfigurer::disable)
.authorizeHttpRequests(req ->
req.requestMatchers(WHITE_LIST_URL)
.permitAll()
.anyRequest()
.authenticated()
)
.sessionManagement(session -> session.sessionCreationPolicy(STATELESS))
.authenticationProvider(authenticationProvider)
.addFilterBefore(jwtAuthFilter, UsernamePasswordAuthenticationFilter.class)
.logout(logout ->
logout.logoutUrl("/api/v1/auth/logout")
.addLogoutHandler(logoutHandler)
)
;

return http.build();
}
}

This file was deleted.

16 changes: 0 additions & 16 deletions src/main/java/com/kakaoteck/golagola/controller/MyController.java

This file was deleted.

Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
package com.kakaoteck.golagola.Repository;
package com.kakaoteck.golagola.domain.auth.Repository;

import com.kakaoteck.golagola.entity.UserEntity;
import com.kakaoteck.golagola.domain.auth.entity.UserEntity;
import org.springframework.data.jpa.repository.JpaRepository;

public interface UserRepository extends JpaRepository<UserEntity, Long> {
Expand Down
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
package com.kakaoteck.golagola.dto;
package com.kakaoteck.golagola.domain.auth.dto;

import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.oauth2.core.user.OAuth2User;
Expand Down
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
package com.kakaoteck.golagola.dto;
package com.kakaoteck.golagola.domain.auth.dto;

import java.util.Map;

Expand Down
Original file line number Diff line number Diff line change
@@ -1,6 +1,5 @@
package com.kakaoteck.golagola.dto;
package com.kakaoteck.golagola.domain.auth.dto;

import java.io.Serializable;
import java.util.Map;

public class NaverResponse implements OAuth2Response{
Expand Down
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
package com.kakaoteck.golagola.dto;
package com.kakaoteck.golagola.domain.auth.dto;

public interface OAuth2Response {

Expand Down
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
package com.kakaoteck.golagola.dto;
package com.kakaoteck.golagola.domain.auth.dto;

import lombok.Getter;
import lombok.Setter;
Expand Down
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
package com.kakaoteck.golagola.entity;
package com.kakaoteck.golagola.domain.auth.entity;

import jakarta.persistence.Entity;
import jakarta.persistence.GeneratedValue;
Expand Down
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
package com.kakaoteck.golagola.jwt;
package com.kakaoteck.golagola.security.jwt;

import com.kakaoteck.golagola.dto.CustomOAuth2User;
import com.kakaoteck.golagola.dto.UserDTO;
import com.kakaoteck.golagola.domain.auth.dto.CustomOAuth2User;
import com.kakaoteck.golagola.domain.auth.dto.UserDTO;
import jakarta.servlet.FilterChain;
import jakarta.servlet.ServletException;
import jakarta.servlet.http.Cookie;
Expand All @@ -25,60 +25,55 @@ public JWTFilter(JWTUtil jwtUtil) {
@Override
protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws ServletException, IOException {

//cookie들을 불러온 뒤 Authorization Key에 담긴 쿠키를 찾음
// cookie들을 불러온 뒤 Authorization Key에 담긴 쿠키를 찾음
String authorization = null;
Cookie[] cookies = request.getCookies();
for (Cookie cookie : cookies) {

System.out.println(cookie.getName());
if (cookie.getName().equals("Authorization")) {

authorization = cookie.getValue();
// 쿠키가 null인지 확인
if (cookies != null) {
for (Cookie cookie : cookies) {
System.out.println(cookie.getName());
if (cookie.getName().equals("Authorization")) {
authorization = cookie.getValue();
}
}
}

//Authorization 헤더 검증
// Authorization 헤더 검증
if (authorization == null) {

System.out.println("token null");
filterChain.doFilter(request, response);

//조건이 해당되면 메소드 종료 (필수)
return;
return; // 조건이 해당되면 메소드 종료 (필수)
}

//토큰
// 토큰
String token = authorization;

//토큰 소멸 시간 검증
// 토큰 소멸 시간 검증
if (jwtUtil.isExpired(token)) {

System.out.println("token expired");
filterChain.doFilter(request, response);

//조건이 해당되면 메소드 종료 (필수)
return;
return; // 조건이 해당되면 메소드 종료 (필수)
}

//토큰에서 username과 role 획득
// 토큰에서 username과 role 획득
String username = jwtUtil.getUsername(token);
String role = jwtUtil.getRole(token);

//userDTO를 생성하여 값 set
// userDTO를 생성하여 값 set
UserDTO userDTO = new UserDTO();
userDTO.setUsername(username);
userDTO.setRole(role);

//UserDetails에 회원 정보 객체 담기
// UserDetails에 회원 정보 객체 담기
CustomOAuth2User customOAuth2User = new CustomOAuth2User(userDTO);

//스프링 시큐리티 인증 토큰 생성
// 스프링 시큐리티 인증 토큰 생성
Authentication authToken = new UsernamePasswordAuthenticationToken(customOAuth2User, null, customOAuth2User.getAuthorities());
//세션에 사용자 등록
// 세션에 사용자 등록
SecurityContextHolder.getContext().setAuthentication(authToken);

filterChain.doFilter(request, response);

}

}
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
package com.kakaoteck.golagola.jwt;
package com.kakaoteck.golagola.security.jwt;

import io.jsonwebtoken.Jwts;
import org.springframework.beans.factory.annotation.Value;
Expand Down Expand Up @@ -44,4 +44,4 @@ public String createJwt(String username, String role, Long expiredMs) {
.compact();
}

}
}
Loading

0 comments on commit 9b2c422

Please sign in to comment.