로그인 기능 구현 안됨 ㅜㅜ
1909
작성한 질문수 1
안녕하세요! 개인 프로젝트에 강의를 보면서 스프링 시큐리티를 입히고 있는 과정에서 문제가 있어서 문의드립니다!
저의 SecurityConfig 클래스는 이렇게 되어있는데 로그인 시 스프링 시큐리티가 호출되지 않습니다 ㅜㅜ
도대체 어디가 문제인 걸까요! 며칠째 삽질하다 문의 드립니다!
package com.zhfvkq.dyshop.security;
import com.zhfvkq.dyshop.member.service.CustomUserDetailsService;
import com.zhfvkq.dyshop.security.provider.CustomAuthenticationProvider;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.boot.autoconfigure.security.servlet.PathRequest;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.authentication.AuthenticationManager;
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.WebSecurityCustomizer;
import org.springframework.security.crypto.factory.PasswordEncoderFactories;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.security.web.SecurityFilterChain;
@Slf4j
@Configuration
@RequiredArgsConstructor
public class SecurityConfig {
private final AuthenticationSuccess authenticationSuccess;
private final AuthenticationFailure authenticationFailure;
private final LogoutExecute logoutExecute;
private final LogoutSuccess logoutSuccess;
private final CustomUserDetailsService customUserDetailsService;
private final AuthenticationEntryException authenticationEntryException;
private final AccessDeniedHandlerException accessDeniedHandlerException;
private String[] ignoredMatcherPattern = {"/", "/img/**", "/lib/**", "/member/**"};
@Bean
public static PasswordEncoder passwordEncoder() {
return PasswordEncoderFactories.createDelegatingPasswordEncoder();
}
@Bean
public CustomAuthenticationProvider customAuthenticationProvider() {
return new CustomAuthenticationProvider();
}
@Bean
public AuthenticationManager authenticationManager(AuthenticationConfiguration authConfiguration) throws Exception {
return authConfiguration.getAuthenticationManager();
}
@Bean
public SecurityFilterChain filterChain(HttpSecurity http) throws Exception {
http
.authorizeRequests()
.anyRequest().authenticated()
;
http.formLogin() // 로그인
.loginPage("/member/login")
.usernameParameter("userId")
.passwordParameter("password")
.loginProcessingUrl("/member/login")
.successHandler(authenticationSuccess)
.failureHandler(authenticationFailure)
.permitAll()
;
http.logout() // 로그아웃
.logoutUrl("/member/logout") // default post
.logoutSuccessUrl("/")
.invalidateHttpSession(true) // 세션 무효화
.deleteCookies("SESSION", "JSESSIONID", "remember-me")
.addLogoutHandler(logoutExecute)
.logoutSuccessHandler(logoutSuccess)
;
http.rememberMe() // 사용자 저장
.rememberMeParameter("idMaintain") // default 파라미터는 remember-me
.tokenValiditySeconds(604800) // 7일로 설정(default 14일)
.alwaysRemember(false)
.userDetailsService(customUserDetailsService)
;
http.sessionManagement()
.maximumSessions(1) // -1 무제한
.expiredUrl("/member/login") // 세션 만료
;
http.exceptionHandling() // Exception 처리
.authenticationEntryPoint(authenticationEntryException) // 인증 예외
.accessDeniedHandler(accessDeniedHandlerException) // 인가 예외
;
return http.build();
}
/**
* 정적 자원 및 루트 페이지 ignore
*/
@Bean
public WebSecurityCustomizer webSecurityCustomizer() {
return (web) -> web.ignoring()
.requestMatchers(PathRequest.toStaticResources().atCommonLocations())
.antMatchers(ignoredMatcherPattern);
}
}
제 깃허브도 같이 전달 드립니다!
https://github.com/zhfvkqHub dyshop프로젝트
답변 1
1
네
테스트 해 보니 여러군데서 에러가 발생하고 있습니다.
일단 시큐리티가 정상적으로 동작하기 위해서는 다음과 같이 수정이 되어야 합니다.
CustomAuthenticationProvider 클래스에서
@Override
public boolean supports(Class<?> authentication) {
return false;
} 저 부분이 true 가 되도록 변경이 되어야 합니다. 그래야 CustomAuthenticationProvider 의
Authentication authenticate(Authentication authentication) 메서드가 실행이 됩니다.
또한
if(passwordEncoder.matches(password, userDetails.getPassword())){
throw new BadCredentialsException("BadCredentialsException");
}위의 if 문이 false 가 될 때 예외가 발생하도록 해야 합니다.
또한
private UserDetailsService userDetailsService;
private PasswordEncoder passwordEncoder;위에서 private 뒤에 final 키워드가 빠져 있습니다.
그리고
@Bean
public WebSecurityCustomizer webSecurityCustomizer() {
return (web) -> web.ignoring()
.requestMatchers(PathRequest.toStaticResources().atCommonLocations())
.antMatchers(ignoredMatcherPattern)
;
}private String[] ignoredMatcherPattern = {"/", "/img/**", "/lib/**", "/member/**"};
위에서 ignoredMatcherPattern 부분이 필터에서 걸러내지 못하고 있습니다.
정확한 원인은 좀 더 봐야 되겠지만 일단 제가 다음과 같이 수정했습니다.
http
.authorizeRequests()
.antMatchers("/", "/img/**", "/lib/**", "/member/**", "/mail/**","/scss/**").permitAll()
.anyRequest().authenticated()
;
이렇게 하면 인증처리가 되긴 하는데 인증이 성공한 이후 thymeleaf 오류가 발생하고 있습니다.
일단 시큐리티가 작동하도록 수정하시고 이후 프로세스 오류를 점검하시기 바랍니다.
시큐리티 공부 버전 질문
0
190
1
[해결 방법] MethodSecurityConfig.customMethodSecurityMetadataSource() 호출하지 않는 이슈
0
197
1
AbstractSecurityInterceptor.class.beforeInvocation()를 2번 실행하는 경우
0
186
1
강의 코드가 왜이렇게 뒤죽박죽인가요...
0
271
1
메인 페이지로 접속해도 login url로 리다이렉트가 되지 않습니다..
0
248
1
파라미터값이 넘어가지 않습니다 ....
0
382
1
security filterChain 설정 질문이 있습니다.
0
337
1
소스 부분 질문 드립니다.
0
213
2
섹션4 7번 강의 문제가 있는거 같네요.
0
352
2
파일이 수시로 이름이 바껴있네요 ㄷㄷ
0
312
1
HttpSessionSecurityContextRepository를 사용안하는 문제
0
565
2
error , exception 이 잘 안됩니다.
0
289
2
thymeleaf tag 질문합니다.
0
201
2
버전업하면서 deprecated된 것들이 너무많아요
0
483
1
spring security 패치 관련
0
442
1
모바일을 사용할때 토큰말고 세션
0
869
2
DB 연동한 인가 부분에 대한 질문입니다!
0
269
1
Ajax방식도 똑같이 Session방식을 사용하는건가요?
0
313
1
Config 파일 생성 시 질문이 있습니다.
0
237
1
강사님 몇일동안 구글 검색만 100개 했는데도 이유를 모르겠습니다..
1
443
2
403 에러 뜹니다.
0
827
2
login_proc의 존재에 대한 간략한 설명입니다
0
283
1
top.html에 로그인 링크를 만들어서 로그인을 해봤습니다
0
295
2
안녕하세요. DB에 저장될 때 이해 안 가는 값이 있어서 질문드립니다!
0
196
1





