• 카테고리

    질문 & 답변
  • 세부 분야

    백엔드

  • 해결 여부

    미해결

로그인 기능 구현 안됨 ㅜㅜ

22.11.06 22:43 작성 조회수 1.45k

0

안녕하세요! 개인 프로젝트에 강의를 보면서 스프링 시큐리티를 입히고 있는 과정에서 문제가 있어서 문의드립니다!

저의 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 오류가 발생하고 있습니다.

image

일단 시큐리티가 작동하도록 수정하시고 이후 프로세스 오류를 점검하시기 바랍니다.

hamoey님의 프로필

hamoey

질문자

2022.11.07

감사합니다!! 덕분에 해결했습니다!!!