Skip to content

Feature/jwt practice #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
wants to merge 13 commits into
base: main
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from 1 commit
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
Next Next commit
feature,refactor - JWT를 이용한 인증처리 practice
* DTO 생성
* Entity 구조 변경
* Exception 핸들러 및 설정파일 변경
* 메모리DB H2 Console 이용
  • Loading branch information
chs1234 committed Aug 20, 2023
commit 931e9f0c6a43b848057409a9d3fff4988c44ff11
2 changes: 1 addition & 1 deletion .idea/compiler.xml

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

4 changes: 2 additions & 2 deletions .idea/dataSources.xml

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

15 changes: 10 additions & 5 deletions build.gradle
Original file line number Diff line number Diff line change
Expand Up @@ -24,15 +24,20 @@ repositories {
dependencies {
implementation 'org.springframework.boot:spring-boot-starter-data-jpa'
implementation 'org.springframework.boot:spring-boot-starter-security'
implementation 'org.springframework.boot:spring-boot-starter-oauth2-client'
implementation 'org.springframework.boot:spring-boot-starter-validation'
implementation 'org.springframework.boot:spring-boot-starter-web'
implementation 'org.springframework.boot:spring-boot-starter-mustache'
testImplementation 'org.springframework.boot:spring-boot-starter-test'
testImplementation 'org.springframework.security:spring-security-test'

compileOnly 'org.projectlombok:lombok'
annotationProcessor 'org.projectlombok:lombok'
testImplementation 'org.springframework.boot:spring-boot-starter-test'
testImplementation 'org.springframework.security:spring-security-test'
runtimeOnly 'com.mysql:mysql-connector-j:8.0.33'

runtimeOnly 'com.h2database:h2'
// runtimeOnly 'com.mysql:mysql-connector-j:8.0.33'

implementation 'io.jsonwebtoken:jjwt-api:0.11.5'
runtimeOnly 'io.jsonwebtoken:jjwt-impl:0.11.5'
runtimeOnly 'io.jsonwebtoken:jjwt-jackson:0.11.5'
}

tasks.named('test') {
Expand Down
24 changes: 24 additions & 0 deletions docker-compose.yml
Original file line number Diff line number Diff line change
@@ -0,0 +1,24 @@
## compose 파일 버전
#version: '3'
#services:
# # 서비스 명
# db:
# # 사용할 이미지
# image: mysql
# # 컨테이너 실행 시 재시작
# restart: always
# # 컨테이너명 설정
# container_name: mysql-container-by-compose
# # 접근 포트 설정(컨테이너 외부:컨테이너 내부)
# ports:
#
# - 3307:3306
# # 환경 변수 설정
# environment:
# MYSQL_ROOT_PASSWORD: root
# # 명령어 설정
# command:
# - --character-set-server=utf8mb4
# - --collation-server=utf8mb4_unicode_ci
## volumes:
## -
98 changes: 0 additions & 98 deletions src/main/java/com/example/security2/auth/PrincipalDetails.java

This file was deleted.

This file was deleted.

25 changes: 25 additions & 0 deletions src/main/java/com/example/security2/config/CorsConfig.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,25 @@
package com.example.security2.config;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.cors.CorsConfiguration;
import org.springframework.web.cors.UrlBasedCorsConfigurationSource;
import org.springframework.web.filter.CorsFilter;

@Configuration
public class CorsConfig {

@Bean
public CorsFilter corsFilter() {
UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();

CorsConfiguration config = new CorsConfiguration();
config.setAllowCredentials(true);
config.addAllowedOriginPattern("*");
config.addAllowedHeader("*");
config.addAllowedMethod("*");

source.registerCorsConfiguration("/rest/api/**", config);
return new CorsFilter(source);
}
}
25 changes: 25 additions & 0 deletions src/main/java/com/example/security2/config/JwtSecurityConfig.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,25 @@
package com.example.security2.config;

import com.example.security2.jwt.JwtFilter;
import com.example.security2.jwt.TokenProvider;
import org.springframework.security.config.annotation.SecurityConfigurerAdapter;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.web.DefaultSecurityFilterChain;
import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter;

public class JwtSecurityConfig extends SecurityConfigurerAdapter<DefaultSecurityFilterChain, HttpSecurity> {

private final TokenProvider tokenProvider;

public JwtSecurityConfig(TokenProvider tokenProvider) {
this.tokenProvider = tokenProvider;
}

@Override
public void configure(HttpSecurity http) throws Exception {
// security 로직에 JwtFilter 등록
http.addFilterBefore(
new JwtFilter(tokenProvider),
UsernamePasswordAuthenticationFilter.class);
}
}
89 changes: 56 additions & 33 deletions src/main/java/com/example/security2/config/SecurityConfig.java
Original file line number Diff line number Diff line change
@@ -1,59 +1,82 @@
package com.example.security2.config;

import com.example.security2.oauth.PrincipalOauth2UserService;
import com.example.security2.jwt.JwtAccessDeniedHandler;
import com.example.security2.jwt.JwtAuthenticationEntryPoint;
import com.example.security2.jwt.TokenProvider;
import org.springframework.boot.autoconfigure.security.servlet.PathRequest;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
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.config.annotation.web.configurers.HeadersConfigurer;
import org.springframework.security.config.http.SessionCreationPolicy;
import org.springframework.security.web.SecurityFilterChain;
import org.springframework.security.web.access.expression.WebExpressionAuthorizationManager;
import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter;
import org.springframework.security.web.util.matcher.AntPathRequestMatcher;
import org.springframework.web.filter.CorsFilter;

@Configuration
@EnableWebSecurity // 스프링 필터체인에 등록
@EnableMethodSecurity(securedEnabled = true, prePostEnabled = true) // 권한 처리, Secured 어노테이션 활성화. preAuthorize, postAuthorize 어노테이션 활성화
@EnableWebSecurity
@EnableMethodSecurity
public class SecurityConfig {

private final PrincipalOauth2UserService principalOauth2UserService;
private final CorsFilter corsFilter;
private final TokenProvider tokenProvider;
private final JwtAuthenticationEntryPoint jwtAuthenticationEntryPoint;
private final JwtAccessDeniedHandler jwtAccessDeniedHandler;

public SecurityConfig(PrincipalOauth2UserService principalOauth2UserService) {
this.principalOauth2UserService = principalOauth2UserService;
}
/*private static final String[] WHITE_LIST = {
"/rest/api/v1/auth",
"/rest/api/v1/user/hello",
"/rest/api/v1/user/signup"
};*/

// SecurityConfig <-> PrincipalOauth2UserService 순환참조로 인해 분리(PasswordConfig)
/*@Bean
public PasswordEncoder passwordEncoder() {
return new BCryptPasswordEncoder();
}*/
public SecurityConfig(CorsFilter corsFilter, TokenProvider tokenProvider, JwtAuthenticationEntryPoint jwtAuthenticationEntryPoint, JwtAccessDeniedHandler jwtAccessDeniedHandler) {
this.corsFilter = corsFilter;
this.tokenProvider = tokenProvider;
this.jwtAuthenticationEntryPoint = jwtAuthenticationEntryPoint;
this.jwtAccessDeniedHandler = jwtAccessDeniedHandler;
}

@Bean
public SecurityFilterChain securityFilterChain(HttpSecurity http) throws Exception {
// csrf, cors 일단 비활성화
http.csrf(AbstractHttpConfigurer::disable);
http.cors(AbstractHttpConfigurer::disable);
http
.csrf(AbstractHttpConfigurer::disable)
// .cors(AbstractHttpConfigurer::disable)

.addFilterBefore(corsFilter, UsernamePasswordAuthenticationFilter.class)
// jwt 예외핸들러 등록
.exceptionHandling(httpSecurityExceptionHandlingConfigurer ->
httpSecurityExceptionHandlingConfigurer
.authenticationEntryPoint(jwtAuthenticationEntryPoint)
.accessDeniedHandler(jwtAccessDeniedHandler)
)

http.authorizeHttpRequests((requests) -> requests
.requestMatchers("/user/**").authenticated()
.requestMatchers("/manager/**").access(
new WebExpressionAuthorizationManager("hasRole('ROLE_ADMIN') or hasRole('ROLE_MANAGER')")
// 세션을 사용하지 않기 때문에 "STATELESS"로 설정
.sessionManagement(sessionManagementConfigurer ->
sessionManagementConfigurer.sessionCreationPolicy(SessionCreationPolicy.STATELESS)
)
.requestMatchers("/admin/**").access(
new WebExpressionAuthorizationManager("hasRole('ROLE_ADMIN')")

.authorizeHttpRequests((requests) -> requests
.requestMatchers(PathRequest.toH2Console()).permitAll()
.requestMatchers(
new AntPathRequestMatcher("/rest/api/v1/auth"),
Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

보통 rest는 붙이지 않고 api/v1이렇게만 합니당

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

수정해서 올리겠습니다~!

new AntPathRequestMatcher("/rest/api/v1/user/hello"),
new AntPathRequestMatcher("/rest/api/v1/user/signup")
).permitAll()
// .requestMatchers("/rest/api/v1/auth", "/rest/api/v1/user/hello", "/rest/api/v1/user/signup").permitAll()
.anyRequest().authenticated()
)
.anyRequest().permitAll())
.formLogin(form -> form
.loginPage("/loginForm")
.usernameParameter("email")
.loginProcessingUrl("/login")
.defaultSuccessUrl("/")
// enable h2 console
.headers(header -> header
.frameOptions(HeadersConfigurer.FrameOptionsConfig::sameOrigin)
)
.oauth2Login(oauth2 -> oauth2
.loginPage("/loginForm")
.userInfoEndpoint(userInfoEndpointConfig -> userInfoEndpointConfig
.userService(principalOauth2UserService)
)
);

// JwtFilter 적용
.apply(new JwtSecurityConfig(tokenProvider));

return http.build();
}
Expand Down
22 changes: 0 additions & 22 deletions src/main/java/com/example/security2/config/WebMvcConfig.java

This file was deleted.

Loading