Skip to content

Commit

Permalink
Merge pull request #60 from kakao-tech-campus-2nd-step3/week6
Browse files Browse the repository at this point in the history
[Develop] 6주차 최종 코드 PR
  • Loading branch information
amm0124 authored Oct 11, 2024
2 parents 14637ed + 29a27bc commit c02e931
Show file tree
Hide file tree
Showing 113 changed files with 2,568 additions and 612 deletions.
1 change: 0 additions & 1 deletion build.gradle
Original file line number Diff line number Diff line change
Expand Up @@ -33,7 +33,6 @@ dependencies {
implementation 'org.springframework.boot:spring-boot-starter-oauth2-client'
implementation 'org.springframework.boot:spring-boot-starter-security'
implementation 'org.springframework.boot:spring-boot-starter-actuator'
implementation 'org.springframework.boot:spring-boot-starter-oauth2-client'


// H2 Database
Expand Down
Original file line number Diff line number Diff line change
@@ -1,21 +1,29 @@
package poomasi.domain.auth.config;

import jdk.jfr.Description;
import lombok.RequiredArgsConstructor;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.connection.RedisConnectionFactory;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.security.web.servlet.util.matcher.MvcRequestMatcher;
import org.springframework.web.servlet.handler.HandlerMappingIntrospector;
import poomasi.global.redis.service.RedisService;
import poomasi.global.util.JwtUtil;
import poomasi.domain.auth.token.blacklist.service.TokenBlacklistService;
import poomasi.domain.auth.token.refreshtoken.service.TokenStorageService;
import poomasi.domain.auth.token.util.JwtUtil;
import poomasi.domain.auth.token.refreshtoken.service.TokenRedisService;
import poomasi.domain.member.service.MemberService;

@RequiredArgsConstructor
@Configuration
public class SecurityBeanGenerator {

@Autowired
private RedisService redisService;
private final TokenStorageService tokenStorageService;
private final MemberService memberService;
private final TokenBlacklistService tokenBlacklistService;

@Bean
@Description("AuthenticationProvider를 위한 Spring bean")
Expand All @@ -30,9 +38,10 @@ MvcRequestMatcher.Builder mvc(HandlerMappingIntrospector introspector) {
}

@Bean
@Description("jwt 토큰 발급을 위한 spring bean")
JwtUtil jwtProvider() {
return new JwtUtil(redisService);
JwtUtil jwtUtil(){
return new JwtUtil(tokenBlacklistService,
tokenStorageService,
memberService);
}
}

}
111 changes: 82 additions & 29 deletions src/main/java/poomasi/domain/auth/config/SecurityConfig.java
Original file line number Diff line number Diff line change
@@ -1,8 +1,10 @@
package poomasi.domain.auth.config;

import lombok.AllArgsConstructor;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Description;
import org.springframework.http.HttpMethod;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.config.annotation.authentication.configuration.AuthenticationConfiguration;
Expand All @@ -13,72 +15,123 @@
import org.springframework.security.config.http.SessionCreationPolicy;
import org.springframework.security.web.SecurityFilterChain;
import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter;
import org.springframework.security.web.authentication.logout.LogoutFilter;
import org.springframework.security.web.authentication.logout.LogoutHandler;
import org.springframework.security.web.servlet.util.matcher.MvcRequestMatcher;
import poomasi.domain.auth.security.filter.CustomLogoutFilter;
import poomasi.domain.auth.security.filter.CustomUsernamePasswordAuthenticationFilter;
import poomasi.domain.auth.security.filter.JwtAuthenticationFilter;
import poomasi.global.util.JwtUtil;
import poomasi.domain.auth.security.handler.CustomSuccessHandler;
import poomasi.domain.auth.security.userdetail.OAuth2UserDetailServiceImpl;
import poomasi.domain.auth.security.handler.*;
import poomasi.domain.auth.token.util.JwtUtil;


@AllArgsConstructor
@Configuration
@EnableWebSecurity
@EnableMethodSecurity(securedEnabled = false, prePostEnabled = false) // 인가 처리에 대한 annotation
@EnableMethodSecurity(securedEnabled = true , prePostEnabled = false) // 인가 처리에 대한 annotation
public class SecurityConfig {

private final AuthenticationConfiguration authenticationConfiguration;
private final JwtUtil jwtUtil;
private final MvcRequestMatcher.Builder mvc;
private final CustomSuccessHandler customSuccessHandler;

@Autowired
private OAuth2UserDetailServiceImpl oAuth2UserDetailServiceImpl;

@Bean
public AuthenticationManager authenticationManager(AuthenticationConfiguration configuration) throws Exception {
return configuration.getAuthenticationManager();
}

@Description("순서 : Oauth2 -> jwt -> login -> logout")
@Bean
public SecurityFilterChain securityFilterChain(HttpSecurity http) throws Exception {

// TODO : 나중에 허용될 endpoint가 많아지면 whiteList로 관리 예정
// 임시로 GET : [api/farms, api/products, api/login, api/signup, /]은 열어둠
http.authorizeHttpRequests((authorize) -> authorize
.requestMatchers(HttpMethod.GET, "/api/farm/**").permitAll()
.requestMatchers(HttpMethod.GET, "/api/product/**").permitAll()
.requestMatchers("/api/login", "/", "/api/signup").permitAll()
.anyRequest().
authenticated()
);
//form login disable
http.formLogin(AbstractHttpConfigurer::disable);

//basic login disable
http.httpBasic(AbstractHttpConfigurer::disable);

//csrf 해제
http.csrf(AbstractHttpConfigurer::disable);

//cors 해제
http.cors(AbstractHttpConfigurer::disable);

//session 해제 -> jwt token 로그인
http.sessionManagement(session -> session
.sessionCreationPolicy(SessionCreationPolicy.STATELESS)
);

//Oauth2.0 소셜 로그인 필터 구현
//세션 해제
http.sessionManagement((session) -> session
.sessionCreationPolicy(SessionCreationPolicy.STATELESS));

//기본 로그아웃 해제
http.logout(AbstractHttpConfigurer::disable);

//jwt 인증 필터 구현
http.addFilterBefore(new JwtAuthenticationFilter(jwtUtil), CustomUsernamePasswordAuthenticationFilter.class);
/*
// 기본 경로 및 테스트 경로
http.authorizeHttpRequests((authorize) -> authorize
.requestMatchers(HttpMethod.GET, "/api/farm/**").permitAll()
.requestMatchers(HttpMethod.GET, "/api/product/**").permitAll()
.requestMatchers(HttpMethod.GET, "/api/review/**").permitAll()
.requestMatchers("/api/sign-up", "/api/login", "api/reissue").permitAll()
.requestMatchers("/api/need-auth/**").authenticated()
.anyRequest().
authenticated()
);*/

//로그인 filter 구현
http.addFilterAt(new CustomUsernamePasswordAuthenticationFilter(authenticationManager(authenticationConfiguration), jwtUtil), UsernamePasswordAuthenticationFilter.class);

//form login disable
http.formLogin(AbstractHttpConfigurer::disable);
http.authorizeHttpRequests((authorize) -> authorize
.requestMatchers("/**").permitAll()
.requestMatchers("/api/need-auth/**").authenticated()
.anyRequest()
.authenticated()
);

//basic login disable
http.httpBasic(AbstractHttpConfigurer::disable);
/*
로그아웃 필터 등록하기
LogoutHandler[] handlers = {
new CookieClearingLogoutHandler(),
new ClearAuthenticationHandler()
};
CustomLogoutFilter customLogoutFilter = new CustomLogoutFilter(jwtUtil, new CustomLogoutSuccessHandler(), handlers);
customLogoutFilter.setFilterProcessesUrl("/api/logout");
customLogoutFilter.
http.addFilterAt(customLogoutFilter, LogoutFilter.class);
http.logout( (logout) ->
logout.
logoutSuccessHandler(new CustomLogoutSuccessHandler())
.addLogoutHandler(new CookieClearingLogoutHandler())
.addLogoutHandler(new ClearAuthenticationHandler())
);
*/

/*
oauth2 인증은 현재 해제해놨습니다 -> 차후 code를 front에서 어떤 경로로 받을 것인지
아니면 kakao에서 바로 redirect를 백엔드로 할 지 정해지면
processing url 작성하겠습니다
http
.oauth2Login((oauth2) -> oauth2
.userInfoEndpoint((userInfoEndpointConfig) -> userInfoEndpointConfig
.userService(oAuth2UserDetailServiceImpl))
.successHandler(customSuccessHandler)
);
*/
http.oauth2Login(AbstractHttpConfigurer::disable);

CustomUsernamePasswordAuthenticationFilter customUsernameFilter =
new CustomUsernamePasswordAuthenticationFilter(authenticationManager(authenticationConfiguration), jwtUtil);
customUsernameFilter.setFilterProcessesUrl("/api/login");

http.addFilterAt(customUsernameFilter, UsernamePasswordAuthenticationFilter.class);
http.addFilterBefore(new JwtAuthenticationFilter(jwtUtil), UsernamePasswordAuthenticationFilter.class);
//http.addFilterAfter(customLogoutFilter, JwtAuthenticationFilter.class);

//log out filter 추가
//http.addFilterBefore(new CustomLogoutFilter(), CustomLogoutFilter.class);
return http.build();

}

}


Expand Down
36 changes: 0 additions & 36 deletions src/main/java/poomasi/domain/auth/controller/AuthController.java

This file was deleted.

This file was deleted.

This file was deleted.

This file was deleted.

46 changes: 0 additions & 46 deletions src/main/java/poomasi/domain/auth/entity/RefreshToken.java

This file was deleted.

42 changes: 42 additions & 0 deletions src/main/java/poomasi/domain/auth/security/AuthTestController.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,42 @@
package poomasi.domain.auth.security;


import jdk.jfr.Description;
import lombok.extern.slf4j.Slf4j;
import org.springframework.security.access.annotation.Secured;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
import poomasi.domain.auth.security.userdetail.UserDetailsImpl;
import poomasi.domain.member.entity.Member;

@Slf4j
@Description("접근 제어 확인 controller")
@RestController
public class AuthTestController {

@Secured("ROLE_CUSTOMER")
@GetMapping("/api/auth-test/customer")
public String customer() {
Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
Object impl = authentication.getPrincipal();
Member member = ((UserDetailsImpl) impl).getMember();

log.info("email : " + member.getEmail());

return "hi. customer";
}

@Secured("ROLE_FARMER")
@GetMapping("/api/need-auth/farmer")
public String farmer() {
return "hi. farmer";
}

@GetMapping("/api/need-auth")
public String needAuth() {
return "auth";
}

}
Loading

0 comments on commit c02e931

Please sign in to comment.