From 17e80640c0cdb2794c4150fd880be05b3a038d11 Mon Sep 17 00:00:00 2001 From: JooHyunLee Date: Tue, 23 Apr 2024 18:07:26 +0900 Subject: [PATCH 1/2] =?UTF-8?q?fix:#25=20AuthenticationProvider=20?= =?UTF-8?q?=EA=B5=AC=ED=98=84=ED=95=B4=EC=84=9C=20=EB=A1=9C=EA=B7=B8?= =?UTF-8?q?=EC=9D=B8=20=EC=B2=98=EB=A6=AC?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../CustomAuthenticationProvider.java | 50 +++++++++++++++++++ 1 file changed, 50 insertions(+) create mode 100644 src/main/java/com/t3t/authenticationapi/account/component/CustomAuthenticationProvider.java diff --git a/src/main/java/com/t3t/authenticationapi/account/component/CustomAuthenticationProvider.java b/src/main/java/com/t3t/authenticationapi/account/component/CustomAuthenticationProvider.java new file mode 100644 index 0000000..6266050 --- /dev/null +++ b/src/main/java/com/t3t/authenticationapi/account/component/CustomAuthenticationProvider.java @@ -0,0 +1,50 @@ +package com.t3t.authenticationapi.account.component; + +import com.t3t.authenticationapi.account.auth.CustomUserDetails; +import com.t3t.authenticationapi.account.dto.UserEntity; +import com.t3t.authenticationapi.account.service.DefaultUserDetailsService; +import lombok.RequiredArgsConstructor; +import org.springframework.context.annotation.Bean; +import org.springframework.context.annotation.Configuration; +import org.springframework.context.annotation.Lazy; +import org.springframework.security.authentication.AuthenticationProvider; +import org.springframework.security.authentication.BadCredentialsException; +import org.springframework.security.authentication.UsernamePasswordAuthenticationToken; +import org.springframework.security.core.Authentication; +import org.springframework.security.core.AuthenticationException; +import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder; +import org.springframework.stereotype.Component; +import org.springframework.stereotype.Controller; + + +@Configuration +@RequiredArgsConstructor +public class CustomAuthenticationProvider implements AuthenticationProvider { + private final DefaultUserDetailsService userDetailsService; + + @Bean + public BCryptPasswordEncoder bCryptPasswordEncoder(){ + return new BCryptPasswordEncoder(); + } + + @Override + public Authentication authenticate(Authentication authentication) throws AuthenticationException { + String username = authentication.getName(); + String password = authentication.getCredentials().toString(); + + CustomUserDetails userDetails = (CustomUserDetails) userDetailsService.loadUserByUsername(username); + + String dbPassword = userDetails.getPassword(); + if(!bCryptPasswordEncoder().matches(password,dbPassword)){ + throw new BadCredentialsException("id, pw not match"); + } + + return new UsernamePasswordAuthenticationToken(userDetails, null, userDetails.getAuthorities()); + } + + @Override + public boolean supports(Class authentication) { + return authentication.equals(UsernamePasswordAuthenticationToken.class); + } + +} From daaadb1984d5fd7d6fa085655d91939fb96f1ac9 Mon Sep 17 00:00:00 2001 From: JooHyunLee Date: Tue, 23 Apr 2024 18:14:36 +0900 Subject: [PATCH 2/2] =?UTF-8?q?fix:#25=20Authentication=20Provider=20?= =?UTF-8?q?=EB=93=B1=EB=A1=9D?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../AuthenticationApiApplication.java | 2 -- .../account/auth/CustomUserDetails.java | 3 +++ .../common/GlobalExceptionHandler.java | 10 ++++++--- .../CustomAuthenticationProvider.java | 2 -- .../account/controller/LoginController.java | 5 ----- .../account/filter/LoginFilter.java | 2 ++ .../service/DefaultUserDetailsService.java | 2 -- .../config/SecurityConfig.java | 22 +++++++++++++------ src/main/resources/application.yml | 11 ++++++++++ src/main/resources/application_prod.yml | 4 +++- 10 files changed, 41 insertions(+), 22 deletions(-) diff --git a/src/main/java/com/t3t/authenticationapi/AuthenticationApiApplication.java b/src/main/java/com/t3t/authenticationapi/AuthenticationApiApplication.java index 118386f..972efc3 100644 --- a/src/main/java/com/t3t/authenticationapi/AuthenticationApiApplication.java +++ b/src/main/java/com/t3t/authenticationapi/AuthenticationApiApplication.java @@ -9,9 +9,7 @@ @SpringBootApplication @EnableDiscoveryClient public class AuthenticationApiApplication { - public static void main(String[] args) { SpringApplication.run(AuthenticationApiApplication.class, args); } - } diff --git a/src/main/java/com/t3t/authenticationapi/account/auth/CustomUserDetails.java b/src/main/java/com/t3t/authenticationapi/account/auth/CustomUserDetails.java index 7fd0da3..f5678aa 100644 --- a/src/main/java/com/t3t/authenticationapi/account/auth/CustomUserDetails.java +++ b/src/main/java/com/t3t/authenticationapi/account/auth/CustomUserDetails.java @@ -46,6 +46,9 @@ public String getUsername() { public String getUserId(){ return userEntity.getUserId(); } + public String getRole(){ + return userEntity.getRole(); + } @Override public boolean isAccountNonExpired() { diff --git a/src/main/java/com/t3t/authenticationapi/account/common/GlobalExceptionHandler.java b/src/main/java/com/t3t/authenticationapi/account/common/GlobalExceptionHandler.java index a876d98..cf1f5b4 100644 --- a/src/main/java/com/t3t/authenticationapi/account/common/GlobalExceptionHandler.java +++ b/src/main/java/com/t3t/authenticationapi/account/common/GlobalExceptionHandler.java @@ -17,25 +17,29 @@ public class GlobalExceptionHandler { * @author joohyun1996 (이주현) */ @ExceptionHandler(TokenNotExistsException.class) - public ResponseEntity> handleTokenNotExistsException(TokenNotExistsException tokenNotExistsException){ + public ResponseEntity> handleTokenNotExistsException(TokenNotExistsException tokenNotExistsException) { return ResponseEntity.status(HttpStatus.FORBIDDEN).body(new BaseResponse().message(tokenNotExistsException.getMessage())); } + /** * access 토큰이 만료된 경우에 대한 예외 처리 핸들러 + * * @return 403 Forbidden - 예외 메시지 반한 * @author joohyun1996 (이주현) */ @ExceptionHandler(TokenHasExpiredException.class) - public ResponseEntity> handleTokenHasExpiredException(TokenHasExpiredException tokenHasExpiredException){ + public ResponseEntity> handleTokenHasExpiredException(TokenHasExpiredException tokenHasExpiredException) { return ResponseEntity.status(HttpStatus.FORBIDDEN).body(new BaseResponse().message(tokenHasExpiredException.getMessage())); } + /** * refresh, blacklist 토큰이 이미 Redis에 저장되어 있을 경우에 대한 예외 처리 핸들러 + * * @return 400 Forbidden - 예외 메시지 반한 * @author joohyun1996 (이주현) */ @ExceptionHandler(TokenAlreadyExistsException.class) - public ResponseEntity> handleTokenAlreadyExistsException(TokenAlreadyExistsException tokenAlreadyExistsException){ + public ResponseEntity> handleTokenAlreadyExistsException(TokenAlreadyExistsException tokenAlreadyExistsException) { return ResponseEntity.status(HttpStatus.BAD_REQUEST).body(new BaseResponse().message(tokenAlreadyExistsException.getMessage())); } } diff --git a/src/main/java/com/t3t/authenticationapi/account/component/CustomAuthenticationProvider.java b/src/main/java/com/t3t/authenticationapi/account/component/CustomAuthenticationProvider.java index 6266050..ecfb855 100644 --- a/src/main/java/com/t3t/authenticationapi/account/component/CustomAuthenticationProvider.java +++ b/src/main/java/com/t3t/authenticationapi/account/component/CustomAuthenticationProvider.java @@ -13,8 +13,6 @@ import org.springframework.security.core.Authentication; import org.springframework.security.core.AuthenticationException; import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder; -import org.springframework.stereotype.Component; -import org.springframework.stereotype.Controller; @Configuration diff --git a/src/main/java/com/t3t/authenticationapi/account/controller/LoginController.java b/src/main/java/com/t3t/authenticationapi/account/controller/LoginController.java index 2044470..eb34b4a 100644 --- a/src/main/java/com/t3t/authenticationapi/account/controller/LoginController.java +++ b/src/main/java/com/t3t/authenticationapi/account/controller/LoginController.java @@ -13,11 +13,6 @@ */ @RestController public class LoginController { - private final DefaultUserDetailsService service; - - public LoginController(DefaultUserDetailsService service) { - this.service = service; - } /** * LoginFilter 수행시 successfulAuthentication 메소드가 수행되고 해당 메소드에서 응답이 커밋됨 * @author joohyun1996(이주현) diff --git a/src/main/java/com/t3t/authenticationapi/account/filter/LoginFilter.java b/src/main/java/com/t3t/authenticationapi/account/filter/LoginFilter.java index cf26d1c..9a74351 100644 --- a/src/main/java/com/t3t/authenticationapi/account/filter/LoginFilter.java +++ b/src/main/java/com/t3t/authenticationapi/account/filter/LoginFilter.java @@ -16,6 +16,7 @@ import org.springframework.security.core.Authentication; import org.springframework.security.core.AuthenticationException; import org.springframework.security.core.GrantedAuthority; +import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder; import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter; import org.springframework.util.StreamUtils; @@ -58,6 +59,7 @@ public Authentication attemptAuthentication(HttpServletRequest request, HttpServ } String username = loginDto.getUsername(); + // 암호화된 정보로 확인 String password = loginDto.getPassword(); UsernamePasswordAuthenticationToken authToken = new UsernamePasswordAuthenticationToken(username, password, null); diff --git a/src/main/java/com/t3t/authenticationapi/account/service/DefaultUserDetailsService.java b/src/main/java/com/t3t/authenticationapi/account/service/DefaultUserDetailsService.java index 5d268c2..8018b19 100644 --- a/src/main/java/com/t3t/authenticationapi/account/service/DefaultUserDetailsService.java +++ b/src/main/java/com/t3t/authenticationapi/account/service/DefaultUserDetailsService.java @@ -21,7 +21,6 @@ public class DefaultUserDetailsService implements UserDetailsService { private final AccountRepository accountRepository; - private final BCryptPasswordEncoder bCryptPasswordEncoder; /** * 회원이 입력한 UserName, Password가 Database에 있는지 검증하는 메소드 * @param username @@ -40,7 +39,6 @@ public UserDetails loadUserByUsername(String username) throws UsernameNotFoundEx userEntity.setUsername(userEntityDto.getUsername()); userEntity.setUserId(userEntityDto.getUserId()); userEntity.setPassword(userEntityDto.getPassword()); -// userEntity.setPassword(bCryptPasswordEncoder.encode(userEntityDto.getPassword())); userEntity.setRole(userEntityDto.getRole()); return new CustomUserDetails(userEntity); diff --git a/src/main/java/com/t3t/authenticationapi/config/SecurityConfig.java b/src/main/java/com/t3t/authenticationapi/config/SecurityConfig.java index 44bcfd4..ff574f9 100644 --- a/src/main/java/com/t3t/authenticationapi/config/SecurityConfig.java +++ b/src/main/java/com/t3t/authenticationapi/config/SecurityConfig.java @@ -1,18 +1,26 @@ package com.t3t.authenticationapi.config; +import com.t3t.authenticationapi.account.auth.CustomUserDetails; +import com.t3t.authenticationapi.account.component.CustomAuthenticationProvider; import com.t3t.authenticationapi.account.component.JWTUtils; import com.t3t.authenticationapi.account.filter.CommonExceptionFilter; import com.t3t.authenticationapi.account.filter.CustomLogoutFilter; import com.t3t.authenticationapi.account.filter.LoginFilter; +import com.t3t.authenticationapi.account.service.DefaultUserDetailsService; import com.t3t.authenticationapi.account.service.TokenService; 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.security.authentication.AuthenticationManager; +import org.springframework.security.authentication.AuthenticationProvider; +import org.springframework.security.authentication.dao.DaoAuthenticationProvider; +import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder; import org.springframework.security.config.annotation.authentication.configuration.AuthenticationConfiguration; 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.core.userdetails.UserDetailsService; import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder; import org.springframework.security.web.SecurityFilterChain; import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter; @@ -28,16 +36,19 @@ public class SecurityConfig { private final AuthenticationConfiguration authenticationConfiguration; private final JWTUtils jwtUtils; private final TokenService tokenService; + private final CustomAuthenticationProvider provider; + + @Autowired + public void globalConfigure(AuthenticationManagerBuilder auth) throws Exception{ + auth.authenticationProvider(provider); + } @Bean public AuthenticationManager authenticationManager(AuthenticationConfiguration authenticationConfiguration) throws Exception { return authenticationConfiguration.getAuthenticationManager(); } - @Bean - public BCryptPasswordEncoder bCryptPasswordEncoder(){ - return new BCryptPasswordEncoder(); - } + /** * Security Filter Chain 설정. * Auth-Server에서는 인증만 담당하기 때문에 다른 URL에 대해서는 설정 X @@ -55,9 +66,6 @@ public SecurityFilterChain filterChain(HttpSecurity http) throws Exception { .antMatchers("/refresh").permitAll() .antMatchers("/logout").authenticated() .anyRequest().authenticated()) - .logout(logout -> logout - .logoutUrl("/logout") // logout 담당 url - .logoutSuccessUrl("/index")) // logout 성공시 redirect 할 url .addFilterBefore(new CommonExceptionFilter(), LoginFilter.class) .addFilterAt(new LoginFilter(authenticationManager(authenticationConfiguration), jwtUtils, tokenService), UsernamePasswordAuthenticationFilter.class) .addFilterBefore(new CustomLogoutFilter(jwtUtils, tokenService), LogoutFilter.class) diff --git a/src/main/resources/application.yml b/src/main/resources/application.yml index dfdfa3b..5e2fdf2 100644 --- a/src/main/resources/application.yml +++ b/src/main/resources/application.yml @@ -1,4 +1,6 @@ spring: + application: + name: AUTH-SERVICE jpa: open-in-view: true hibernate: @@ -41,3 +43,12 @@ t3t: keyId: "0582f8b117604b7d86e9f3ff26931cde" redisServerPassword: keyId: "ec1eb8e0706e402cbec8487cbcb86564" +server: + port: 8084 + +eureka: + client: + register-with-eureka: true + fetch-registry: true + service-url: + defaultZone: http://localhost:8761/eureka \ No newline at end of file diff --git a/src/main/resources/application_prod.yml b/src/main/resources/application_prod.yml index 887fa0b..78855b1 100644 --- a/src/main/resources/application_prod.yml +++ b/src/main/resources/application_prod.yml @@ -1,4 +1,6 @@ -eureka: + eureka: client: + register-with-eureka: true + fetch-registry: true service-url: defaultZone: ${eurekaServiceUrlDefaultZone} \ No newline at end of file