• 카테고리

    질문 & 답변
  • 세부 분야

    백엔드

  • 해결 여부

    미해결

다중 로그인시 로그인 인증이 되지 않습니다.ㅠ 조언 부탁드립니다.

23.05.26 11:43 작성 23.05.26 11:56 수정 조회수 560

0

안녕하세요. 강사님!시큐리티 강의 잘 보고 있습니다. 강의를 보면서 프로젝트를 진행하고 있는데 국문 -> 국문 LOGIN 화면영문 -> 영문 LOGIN 화면으로 이동하게 하려고 하려고 WebSecurityConfigurerAdapter를 상속받은 class를 2개 만들어 Order(0) , Order(1)로 진행했는데
해당 login 페이지에서 아이디/비번을 입력하면 인증이 되지 않고 .loginProcessingUrl("/login-ko") 해당 페이지로 넘어갑니다.

왜 단일로 할때는 문제 없었는데 다중으로 했을 때 왜 이런 문제가 발생했을까요?ㅠㅠ조언 부탁드립니다.package com.posco.hyrex.infra.config;

import com.posco.hyrex.modules.front.account.provider.AccountAuthenticationProvider;
import javassist.tools.web.Webserver;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.security.servlet.PathRequest;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.annotation.Order;
import org.springframework.security.authentication.AuthenticationProvider;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.builders.WebSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfiguration;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.crypto.factory.PasswordEncoderFactories;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.security.web.authentication.AuthenticationFailureHandler;
import org.springframework.security.web.authentication.AuthenticationSuccessHandler;
import org.springframework.security.web.authentication.logout.SecurityContextLogoutHandler;

import javax.servlet.http.HttpServletResponse;

@Slf4j
@Configuration
@EnableWebSecurity
@RequiredArgsConstructor
@Order(0)
public class SecurityConfig extends WebSecurityConfigurerAdapter {

    @Autowired
    private AuthenticationSuccessHandler authenticationSuccessHandler;

    @Autowired
    private AuthenticationFailureHandler authenticationFailureHandler;

    @Override
    protected void configure(AuthenticationManagerBuilder auth) throws Exception {
        auth.authenticationProvider(accountAuthenticationProvider());
    }

    @Bean
    public AuthenticationProvider accountAuthenticationProvider() {
        return new AccountAuthenticationProvider();
    }


    @Bean
    public PasswordEncoder passwordEncoder() {
        return PasswordEncoderFactories.createDelegatingPasswordEncoder();
    }

    @Bean
    public SecurityContextLogoutHandler securityContextLogoutHandler() {
        return new SecurityContextLogoutHandler();
    }

    @Override
    protected void configure(final HttpSecurity http) throws Exception {

        http.csrf().disable();
        http.cors().disable();

        http
                .antMatcher("/ko/partner/**")
                .authorizeRequests()
                .mvcMatchers("/ko/partner/summary**","/ko/login**").permitAll()
                .anyRequest().authenticated()
        .and()
                .formLogin()
                .loginPage("/ko/login")
                .loginProcessingUrl("/login-ko")
                .defaultSuccessUrl("/ko/partner/summary")
                .successHandler(authenticationSuccessHandler)
                .failureHandler(authenticationFailureHandler)
                .permitAll()
        ;
    }


    @Override
    public void configure(WebSecurity web) throws Exception {
        web.ignoring()
                .mvcMatchers("/error/**","/assets/**")
                .requestMatchers(PathRequest.toStaticResources().atCommonLocations());
    }

}

@Configuration
@Order(1)
class SecurityConfig2 extends WebSecurityConfigurerAdapter{


    @Autowired
    private AuthenticationSuccessHandler authenticationSuccessHandler;

    @Autowired
    private AuthenticationFailureHandler authenticationFailureHandler;

    @Override
    public void configure(HttpSecurity http) throws Exception {

        http
                .antMatcher("/en/partner/**")
                .authorizeRequests()
                .mvcMatchers("/en/partner/summary**","/en/login**").permitAll()
                .anyRequest().authenticated()
            .and()
                .formLogin()
                .loginPage("/en/login")
                .loginProcessingUrl("/login-en")
                .defaultSuccessUrl("/en/partner/summary")
                .successHandler(authenticationSuccessHandler)
                .failureHandler(authenticationFailureHandler)
                .permitAll();


    }

}
 <!-- 본문 시작 -->
        <main class="main main-sub-top">
            <section class="login-section">
                <div class="column">
                    <div class="background"></div>
                </div>
                <div class="column">
                    <form th:action="@{/login-ko}" method="post">
                        <div class="login-form">
                            <div class="row">
                                <div class="col">
                                    <div class="logo">
                                        <img src="/assets/images/logo-dark.svg" alt="">
                                    </div>
                                    <p class="text">서비스를 이용하기 위해 로그인 해주세요.</p>
                                </div>
                            </div>
                            <div class="row">
                                <div class="col">
                                    <div class="form-floating-icon">
                                        <i class="icon icon-login"></i>
                                        <input type="text" id="floatingInput" name="username" class="form-control" th:classappend="${error == 'true'}? is-invalid" placeholder="아이디">
                                        <label for="floatingInput">아이디</label>
                                        <!-- 유효성 체크 -->
<!--                                        <div class="invalid-feedback">아이디가 일치하지 않습니다.</div>-->
                                    </div>
                                </div>
                            </div>
                            <div class="row">
                                <div class="col">
                                    <div class="form-floating-icon">
                                        <i class="icon icon-password"></i>
                                        <input type="password" id="floatingInput2" name="password" class="form-control" th:classappend="${error == 'true'}? is-invalid" placeholder="비밀번호">
                                        <label for="floatingInput2">비밀번호</label>
                                        <!-- 유효성 체크 -->
                                        <div th:if="${param.error}" class="invalid-feedback" th:text="${exception}">패스워드가 일치하지 않습니다.</div>
                                    </div>
                                </div>
                            </div>
                            <div class="row">
                                <div class="col">
                                    <button class="button button-primary" type="submit">로그인</button>
                                </div>
                            </div>
                            <div class="row">
                                <div class="col">
                                    <div class="info">
                                        <p><span class="color-primary">*</span> 아이디/비밀번호를 잊어버리신 경우 아래의 연락처로 문의해 주세요.</p>
                                        <ul>
                                            <li>E-MAIL : hyrex@posco.com</li>
                                            <li>TEL : 02-1234-1234</li>
                                        </ul>
                                    </div>
                                </div>
                            </div>
                        </div>
                    </form>
                </div>
            </section>
        </main>

 -----------------------------------------------------------

    @Override
    protected void configure(final HttpSecurity http) throws Exception {

        http.csrf().disable();
        http.cors().disable();

        http
                .antMatcher("/ko/partner/**")
                .authorizeRequests()
                .mvcMatchers("/ko/partner/summary**","/ko/login**").permitAll()
                .anyRequest().authenticated()
        .and()
                .formLogin()
//                .loginPage("/ko/login")
//                .defaultSuccessUrl("/ko/partner/summary")
//                .successHandler(authenticationSuccessHandler)
//                .failureHandler(authenticationFailureHandler)
//                .permitAll()
        ;
    }

위와 같이 loginPage 경로에 주석을 걸고
/ko/partner/test 경로로 접속했을때
기본 /login 페이지로 가는 부분에서도 에러가 발생합니다.ㅠ
먼가 설정을 잘못한 부분이 있을까요?

답변 2

·

답변을 작성해보세요.

0

정확한 테스트를 위해 소스 공유 가능할까요?

0

인프런 AI 인턴님의 프로필

인프런 AI 인턴

2023.05.28

안녕하세요, 인프런 AI 인턴이에요.

다중 로그인시 로그인 인증이 되지 않는 문제로 보이는데요. login-processing-url 값을 “login-ko”로 설정하고 있기 때문에 다중 로그인시 해당 값이 중복되어 발생하는 문제일 수 있습니다. 이 경우에는 login-processing-url 값을 고유한 값으로 변경해주시면 될 것 같습니다.

또한, SecurityConfig2 클래스에서도 AuthenticationSuccessHandler와 AuthenticationFailureHandler를 설정하고 있지만, 이전에 SecurityConfig 클래스에서 빈으로 등록되어 있는 것으로 보입니다. 따라서 해당 빈을 공유하도록 설정하거나 SecurityConfig2 클래스에서 새로운 빈을 등록해주시면 될 것 같습니다.

아래는 예시 코드입니다.

@Configuration
@Order(1)
class SecurityConfig2 extends WebSecurityConfigurerAdapter{

    @Autowired
    private AuthenticationSuccessHandler authenticationSuccessHandler;

    @Autowired
    private AuthenticationFailureHandler authenticationFailureHandler;

    @Override
    public void configure(HttpSecurity http) throws Exception {

        http
                .antMatcher("/en/partner/**")
                .authorizeRequests()
                .mvcMatchers("/en/partner/summary**","/en/login**").permitAll()
                .anyRequest().authenticated()
            .and()
                .formLogin()
                .loginPage("/en/login")
                .loginProcessingUrl("/login-en")
                .defaultSuccessUrl("/en/partner/summary")
                .successHandler(authenticationSuccessHandler)
                .failureHandler(authenticationFailureHandler)
                .permitAll();


    }

    @Bean
    public AuthenticationSuccessHandler authenticationSuccessHandler() {
        return new DefaultAuthenticationSuccessHandler();
    }

    @Bean
    public AuthenticationFailureHandler authenticationFailureHandler() {
        return new DefaultAuthenticationFailureHandler();
    }

}

위와 같이 authenticationSuccessHandler와 authenticationFailureHandler를 새로운 빈으로 등록해주시면 됩니다.

또한, SecurityConfig 클래스에서 주석처리되어 있는 부분이 있습니다. 해당 설정이 필요하지 않으시다면 주석처리를 유지해주세요.