programing

성공적인 로그인 후 Spring Security 이전 페이지로 리디렉션

linuxpc 2023. 8. 9. 20:33
반응형

성공적인 로그인 후 Spring Security 이전 페이지로 리디렉션

이 질문이 이전에 제기된 적이 있다는 것을 알고 있지만, 저는 여기서 특별한 문제에 직면해 있습니다.

스프링 보안 3.1.3을 사용합니다.

웹 응용 프로그램에 다음과 같은 세 가지 로그인 사례가 있습니다.

  1. 로그인 페이지를 통해 로그인합니다. 확인.
  2. 제한된 페이지를 통해 로그인: OK도 마찬가지입니다.
  3. 제한되지 않는 페이지를 통해 로그인: "제품" 페이지는 모든 사용자가 액세스할 수 있으며 사용자가 로그인한 경우 댓글을 게시할 수 있습니다.따라서 사용자가 연결할 수 있도록 로그인 양식이 동일한 페이지에 포함되어 있습니다.

사례 3)의 문제는 사용자를 "제품" 페이지로 리디렉션할 수 없다는 것입니다.로그인에 성공하면 어떤 일이 있어도 홈 페이지로 리디렉션됩니다.

사례 2)의 경우 성공적인 로그인 후 제한된 페이지로 리디렉션됩니다.

다음은 내 security.xml 파일의 관련 부분입니다.

<!-- Authentication policy for the restricted page  -->
<http use-expressions="true" auto-config="true" pattern="/restrictedPage/**">
    <form-login login-page="/login/restrictedLogin" authentication-failure-handler-ref="authenticationFailureHandler" />
    <intercept-url pattern="/**" access="isAuthenticated()" />
</http>

<!-- Authentication policy for every page -->
<http use-expressions="true" auto-config="true">
    <form-login login-page="/login" authentication-failure-handler-ref="authenticationFailureHandler" />
    <logout logout-url="/logout" logout-success-url="/" />
</http>

저는 "모든 페이지에 대한 인증 정책"이 그 문제에 책임이 있다고 생각합니다.하지만 제거하면 더 이상 로그인할 수 없습니다...j_spring_security_check에서 404 오류를 보냅니다.


편집:

랄프 덕분에 해결책을 찾을 수 있었습니다.그래서 중요한 것은 다음과 같습니다.나는 그 부동산을 사용했습니다.

<property name="useReferer" value="true"/>

랠프가 보여준 것.그 후 제 사례 1) : 로그인 페이지를 통해 로그인할 때 사용자가 동일한 페이지에 남아 있었습니다(예전처럼 홈 페이지로 리디렉션되지 않았습니다).이 단계까지의 코드는 다음과 같습니다.

<!-- Authentication policy for login page -->
<http use-expressions="true" auto-config="true" pattern="/login/**">
    <form-login login-page="/login" authentication-success-handler-ref="authenticationSuccessHandlerWithoutReferer" />
</http>

<!-- Authentication policy for every page -->
<http use-expressions="true" auto-config="true">
    <form-login login-page="/login" authentication-failure-handler-ref="authenticationFailureHandler" />
    <logout logout-url="/logout" logout-success-url="/" authentication-success-handler-ref="authenticationSuccessHandler"/>
</http>

<beans:bean id="authenticationSuccessHandler" class="org.springframework.security.web.authentication.SavedRequestAwareAuthenticationSuccessHandler">
    <!-- After login, return to the last visited page -->
    <beans:property name="useReferer" value="true" />
</beans:bean>

<beans:bean id="authenticationSuccessHandlerWithoutReferer" class="org.springframework.security.web.authentication.SavedRequestAwareAuthenticationSuccessHandler">
    <!-- After login, stay to the same page -->
    <beans:property name="useReferer" value="false" />
</beans:bean>

이것은 적어도 이론적으로는 효과가 있어야 하지만, 그렇지 않았습니다.저는 여전히 이유를 모르기 때문에 누군가가 이에 대한 답을 가지고 있다면 기꺼이 새로운 주제를 만들어 그가 해결책을 공유할 수 있도록 하겠습니다.

그 사이에, 저는 해결책을 찾았습니다.최선의 해결책은 아니지만, 제가 말했듯이, 누군가가 더 좋은 것을 보여준다면, 저는 귀를 기울입니다.다음은 로그인 페이지에 대한 새로운 인증 정책입니다.

<http use-expressions="true" auto-config="true" pattern="/login/**" >
    <intercept-url pattern="/**" access="isAnonymous()" />
    <access-denied-handler error-page="/"/>
</http>

여기서 해결책은 매우 분명합니다. 로그인 페이지는 익명 사용자에게만 허용됩니다.사용자가 연결되면 오류 처리기가 홈 페이지로 리디렉션합니다.

몇 가지 테스트를 해봤는데, 모든 것이 잘 작동하는 것 같습니다.

하는 작업()은 " " "에 의해 됩니다.AuthenticationSuccessHandler.

인터페이스를 )SavedRequestAwareAuthenticationSuccessHandler는 에 됩니다.AbstractAuthenticationProcessingFilter(또는다음같클중하래나스하위은과▁(하중또나▁oresclass▁like▁one)와 같은 하위 클래스 중 .UsernamePasswordAuthenticationFilter) 방에있어는 서successfulAuthentication.

인 3번의 리다이렉트를 해야 .SavedRequestAwareAuthenticationSuccessHandler당신이 원하는 것을 할 수 있게 해주세요.


때로는 (정확한 사용 사례에 따라) 다음과 같은 기능을 사용하기에 충분합니다.useRefererAbstractAuthenticationTargetUrlRequestHandler의 다니됩호에 의해 됩니다.SimpleUrlAuthenticationSuccessHandler의 슈퍼 )SavedRequestAwareAuthenticationSuccessHandler).

<bean id="authenticationFilter"
      class="org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter">
    <property name="filterProcessesUrl" value="/login/j_spring_security_check" />
    <property name="authenticationManager" ref="authenticationManager" />
    <property name="authenticationSuccessHandler">
        <bean class="org.springframework.security.web.authentication.SavedRequestAwareAuthenticationSuccessHandler">
            <property name="useReferer" value="true"/>
        </bean>
    </property>
    <property name="authenticationFailureHandler">
        <bean class="org.springframework.security.web.authentication.SimpleUrlAuthenticationFailureHandler">
            <property name="defaultFailureUrl" value="/login?login_error=t" />
        </bean>
    </property>
</bean>

Olcay의 좋은 답변을 연장하고 싶습니다.그의 접근 방식은 좋습니다. 레퍼러 URL을 세션에 넣으려면 로그인 페이지 컨트롤러가 다음과 같아야 합니다.

@RequestMapping(value = "/login", method = RequestMethod.GET)
public String loginPage(HttpServletRequest request, Model model) {
    String referrer = request.getHeader("Referer");
    request.getSession().setAttribute("url_prior_login", referrer);
    // some other stuff
    return "login";
}

그리고 당신은 연장해야 합니다.SavedRequestAwareAuthenticationSuccessHandler그리고 그것을 무시합니다.onAuthenticationSuccess(HttpServletRequest request, HttpServletResponse response, Authentication authentication)것들.이와 같은 것:

public class MyCustomLoginSuccessHandler extends SavedRequestAwareAuthenticationSuccessHandler {
    public MyCustomLoginSuccessHandler(String defaultTargetUrl) {
        setDefaultTargetUrl(defaultTargetUrl);
    }

    @Override
    public void onAuthenticationSuccess(HttpServletRequest request, HttpServletResponse response, Authentication authentication) throws ServletException, IOException {
        HttpSession session = request.getSession();
        if (session != null) {
            String redirectUrl = (String) session.getAttribute("url_prior_login");
            if (redirectUrl != null) {
                // we do not forget to clean this attribute from session
                session.removeAttribute("url_prior_login");
                // then we redirect
                getRedirectStrategy().sendRedirect(request, response, redirectUrl);
            } else {
                super.onAuthenticationSuccess(request, response, authentication);
            }
        } else {
            super.onAuthenticationSuccess(request, response, authentication);
        }
    }
}

그런 다음 스프링 구성에서 이 사용자 정의 클래스를 빈으로 정의하고 보안 구성에서 사용해야 합니다.주석 구성을 사용하는 경우 다음과 같이 보여야 합니다(확장할 클래스).WebSecurityConfigurerAdapter):

@Bean
public AuthenticationSuccessHandler successHandler() {
    return new MyCustomLoginSuccessHandler("/yourdefaultsuccessurl");
}

configure방법:

@Override
protected void configure(HttpSecurity http) throws Exception {
    http
            // bla bla
            .formLogin()
                .loginPage("/login")
                .usernameParameter("username")
                .passwordParameter("password")
                .successHandler(successHandler())
                .permitAll()
            // etc etc
    ;
}

저는 다음과 같은 해결책을 가지고 있고 그것은 저에게 효과가 있었습니다.

로그인 페이지가 요청될 때마다 참조자 값을 세션에 기록합니다.

@RequestMapping(value="/login", method = RequestMethod.GET)
public String login(ModelMap model,HttpServletRequest request) {

    String referrer = request.getHeader("Referer");
    if(referrer!=null){
        request.getSession().setAttribute("url_prior_login", referrer);
    }
    return "user/login";
}

성공적으로 로그인한 후의 사용자 정의 구현SavedRequestAwareAuthenticationSuccessHandler사용자를 이전 페이지로 리디렉션합니다.

HttpSession session = request.getSession(false);
if (session != null) {
    url = (String) request.getSession().getAttribute("url_prior_login");
}

사용자 리디렉션:

if (url != null) {
    response.sendRedirect(url);
}

지정 및 OAuth2 을 받았습니다.request.getHeader("Referer")결정 시점에서는 사용할 수 없습니다. 그나보안이미있저에 .ExceptionTranslationFilter.sendStartAuthentication:

protected void sendStartAuthentication(HttpServletRequest request,...
    ...
    requestCache.saveRequest(request, response);

그래서, 우리가 필요한 것은 공유하는 것입니다.requestCache봄콩:

@Bean
public RequestCache requestCache() {
   return new HttpSessionRequestCache();
}

@Override
protected void configure(HttpSecurity http) throws Exception {
   http.authorizeRequests()
   ... 
   .requestCache().requestCache(requestCache()).and()
   ...
}     

인증이 완료되면 다음과 같이 사용합니다.

@Autowired
private RequestCache requestCache;

public void authenticate(HttpServletRequest req, HttpServletResponse resp){
    ....
    SavedRequest savedRequest = requestCache.getRequest(req, resp);
    resp.sendRedirect(savedRequest != null && "GET".equals(savedRequest.getMethod()) ?  
    savedRequest.getRedirectUrl() : "defaultURL");
}

다음 일반 솔루션은 일반 로그인, Spring Social 로그인 또는 대부분의 다른 Spring Security 필터와 함께 사용할 수 있습니다.

Spring MVC 컨트롤러에서 제품 페이지를 로드할 때 사용자가 로그인하지 않은 경우 세션의 제품 페이지 경로를 저장합니다.XML 구성에서 기본 대상 URL을 설정합니다.예:

Spring MVC를 반환해야 .redirect:<my_saved_product_path>.

따라서 사용자가 로그인한 후 다음으로 전송됩니다./redirect페이지는 마지막으로 방문한 제품 페이지로 즉시 리디렉션됩니다.

전체 로그인 후 이전 페이지로 돌아가서 다음과 같이 사용자 지정 인증 관리자를 사용할 수 있습니다.

<!-- enable use-expressions -->
    <http auto-config="true" use-expressions="true">
        <!-- src** matches: src/bar.c src/baz.c src/test/bartest.c-->
        <intercept-url pattern="/problemSolution/home/**" access="hasRole('ROLE_ADMIN')"/>
        <intercept-url pattern="favicon.ico" access="permitAll"/>
        <form-login
                authentication-success-handler-ref="authenticationSuccessHandler"
                always-use-default-target="true"
                login-processing-url="/checkUser"
                login-page="/problemSolution/index"

                default-target-url="/problemSolution/home"
                authentication-failure-url="/problemSolution/index?error"
                username-parameter="username"
                password-parameter="password"/>
        <logout logout-url="/problemSolution/logout"
                logout-success-url="/problemSolution/index?logout"/>
        <!-- enable csrf protection -->
        <csrf/>
    </http>

    <beans:bean id="authenticationSuccessHandler"
            class="org.springframework.security.web.authentication.SavedRequestAwareAuthenticationSuccessHandler">
        <beans:property name="defaultTargetUrl" value="/problemSolution/home"/>
    </beans:bean>

    <!-- Select users and user_roles from database -->
    <authentication-manager>
        <authentication-provider user-service-ref="customUserDetailsService">
            <password-encoder hash="plaintext">
            </password-encoder>
        </authentication-provider>
    </authentication-manager>

사용자 지정 사용자 세부 정보 서비스 클래스

@Service
public class CustomUserDetailsService implements UserDetailsService {

        @Autowired
        private UserService userService;

        public UserDetails loadUserByUsername(String userName)
                        throws UsernameNotFoundException {
                com.codesenior.telif.local.model.User domainUser = userService.getUser(userName);

                boolean enabled = true;
                boolean accountNonExpired = true;
                boolean credentialsNonExpired = true;
                boolean accountNonLocked = true;

                return new User(
                                domainUser.getUsername(),
                                domainUser.getPassword(),
                                enabled,
                                accountNonExpired,
                                credentialsNonExpired,
                                accountNonLocked,
                                getAuthorities(domainUser.getUserRoleList())
                );
        }

        public Collection<? extends GrantedAuthority> getAuthorities(List<UserRole> userRoleList) {
                return getGrantedAuthorities(getRoles(userRoleList));
        }

        public List<String> getRoles(List<UserRole> userRoleList) {

                List<String> roles = new ArrayList<String>();

                for(UserRole userRole:userRoleList){
                        roles.add(userRole.getRole());
                }
                return roles;
        }

        public static List<GrantedAuthority> getGrantedAuthorities(List<String> roles) {
                List<GrantedAuthority> authorities = new ArrayList<GrantedAuthority>();

                for (String role : roles) {
                        authorities.add(new SimpleGrantedAuthority(role));
                }
                return authorities;
        }

}

사용자 클래스

import com.codesenior.telif.local.model.UserRole;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.Collection;
import java.util.List;


@Service
public class CustomUserDetailsService implements UserDetailsService {

        @Autowired
        private UserService userService;

        public UserDetails loadUserByUsername(String userName)
                        throws UsernameNotFoundException {
                com.codesenior.telif.local.model.User domainUser = userService.getUser(userName);

                boolean enabled = true;
                boolean accountNonExpired = true;
                boolean credentialsNonExpired = true;
                boolean accountNonLocked = true;

                return new User(
                                domainUser.getUsername(),
                                domainUser.getPassword(),
                                enabled,
                                accountNonExpired,
                                credentialsNonExpired,
                                accountNonLocked,
                                getAuthorities(domainUser.getUserRoleList())
                );
        }

        public Collection<? extends GrantedAuthority> getAuthorities(List<UserRole> userRoleList) {
                return getGrantedAuthorities(getRoles(userRoleList));
        }

        public List<String> getRoles(List<UserRole> userRoleList) {

                List<String> roles = new ArrayList<String>();

                for(UserRole userRole:userRoleList){
                        roles.add(userRole.getRole());
                }
                return roles;
        }

        public static List<GrantedAuthority> getGrantedAuthorities(List<String> roles) {
                List<GrantedAuthority> authorities = new ArrayList<GrantedAuthority>();

                for (String role : roles) {
                        authorities.add(new SimpleGrantedAuthority(role));
                }
                return authorities;
        }

}

사용자 역할 클래스

@Entity
public class UserRole {
        @Id
        @GeneratedValue
        private Integer userRoleId;

        private String role;

        @ManyToMany(fetch = FetchType.LAZY, mappedBy = "userRoleList")
        @JsonIgnore
        private List<User> userList;

        public Integer getUserRoleId() {
                return userRoleId;
        }

        public void setUserRoleId(Integer userRoleId) {
                this.userRoleId= userRoleId;
        }

        public String getRole() {
                return role;
        }

        public void setRole(String role) {
                this.role= role;
        }

        @Override
        public String toString() {
                return String.valueOf(userRoleId);
        }

        public List<User> getUserList() {
                return userList;
        }

        public void setUserList(List<User> userList) {
                this.userList= userList;
        }
}

SimpleUrlAuthentication을 확장하는 사용자 지정 SuccessHandler를 사용할 수 있습니다.할당된 역할에 따라 로그인할 때 사용자를 다른 URL로 리디렉션하는 SuccessHandler입니다.

CustomSuccessHandler 클래스는 다음과 같은 사용자 지정 리디렉션 기능을 제공합니다.

package com.mycompany.uomrmsweb.configuration;

import java.io.IOException;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.security.core.Authentication;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.web.DefaultRedirectStrategy;
import org.springframework.security.web.RedirectStrategy;
import org.springframework.security.web.authentication.SimpleUrlAuthenticationSuccessHandler;
import org.springframework.stereotype.Component;

@Component
public class CustomSuccessHandler extends SimpleUrlAuthenticationSuccessHandler{

    private RedirectStrategy redirectStrategy = new DefaultRedirectStrategy();

    @Override
    protected void handle(HttpServletRequest request, HttpServletResponse response, Authentication authentication) throws IOException {
        String targetUrl = determineTargetUrl(authentication);

        if (response.isCommitted()) {
            System.out.println("Can't redirect");
            return;
        }

        redirectStrategy.sendRedirect(request, response, targetUrl);
    }

    protected String determineTargetUrl(Authentication authentication) {
        String url="";

        Collection<? extends GrantedAuthority> authorities =  authentication.getAuthorities();

        List<String> roles = new ArrayList<String>();

        for (GrantedAuthority a : authorities) {
            roles.add(a.getAuthority());
        }

        if (isStaff(roles)) {
            url = "/staff";
        } else if (isAdmin(roles)) {
            url = "/admin";
        } else if (isStudent(roles)) {
            url = "/student";
        }else if (isUser(roles)) {
            url = "/home";
        } else {
            url="/Access_Denied";
        }

        return url;
    }

    public void setRedirectStrategy(RedirectStrategy redirectStrategy) {
        this.redirectStrategy = redirectStrategy;
    }
    protected RedirectStrategy getRedirectStrategy() {
        return redirectStrategy;
    }

    private boolean isUser(List<String> roles) {
        if (roles.contains("ROLE_USER")) {
            return true;
        }
        return false;
    }

    private boolean isStudent(List<String> roles) {
        if (roles.contains("ROLE_Student")) {
            return true;
        }
        return false;
    }

    private boolean isAdmin(List<String> roles) {
        if (roles.contains("ROLE_SystemAdmin") || roles.contains("ROLE_ExaminationsStaff")) {
            return true;
        }
        return false;
    }

    private boolean isStaff(List<String> roles) {
        if (roles.contains("ROLE_AcademicStaff") || roles.contains("ROLE_UniversityAdmin")) {
            return true;
        }
        return false;
    }
}

Spring SimpleUrl 인증 확장SuccessHandler 클래스 및 재정의 핸들() 메서드는 사용자가 정의한 determinateTargetUrl() 메서드에서 반환한 URL을 사용하여 구성된 RedirectStrategy [이 경우 기본값]을 사용하여 리디렉션을 호출합니다.이 메서드는 Authentication 개체에서 현재 로그인한 사용자의 역할을 추출한 다음 해당 역할을 기반으로 적절한 URL을 구성합니다.마지막으로 스프링 보안 프레임워크 내의 모든 리디렉션을 담당하는 리디렉션 전략은 요청을 지정된 URL로 리디렉션합니다.

SecurityConfiguration 클래스를 사용하여 CustomSuccessHandler를 등록하는 중:

package com.mycompany.uomrmsweb.configuration;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.context.annotation.Configuration;
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.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.core.userdetails.UserDetailsService;

@Configuration
@EnableWebSecurity
public class SecurityConfiguration extends WebSecurityConfigurerAdapter {

    @Autowired
    @Qualifier("customUserDetailsService")
    UserDetailsService userDetailsService;

    @Autowired
    CustomSuccessHandler customSuccessHandler;

    @Autowired
    public void configureGlobalSecurity(AuthenticationManagerBuilder auth) throws Exception {
            auth.userDetailsService(userDetailsService);
    }

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http.authorizeRequests()
        .antMatchers("/", "/home").access("hasRole('USER')")
        .antMatchers("/admin/**").access("hasRole('SystemAdmin') or hasRole('ExaminationsStaff')")
        .antMatchers("/staff/**").access("hasRole('AcademicStaff') or hasRole('UniversityAdmin')")
        .antMatchers("/student/**").access("hasRole('Student')")  
                    .and().formLogin().loginPage("/login").successHandler(customSuccessHandler)
        .usernameParameter("username").passwordParameter("password")
        .and().csrf()
        .and().exceptionHandling().accessDeniedPage("/Access_Denied");
    }
}

successHandler는 사용자 지정 로직을 기반으로 궁극적인 리디렉션을 담당하는 클래스입니다. 이 경우에는 [USER/Student/SystemAdmin/UniversityAdmin/ExaminationsStaff/AcademicStaff] 역할에 따라 사용자를 [학생/관리자/직원]으로 리디렉션합니다.

Utku Ozdemir의 솔루션은 어느 정도 작동하지만 세션 속성이 요청보다 우선하기 때문에 저장된 요청의 목적을 무시하는 것 같습니다.이것은 보안 페이지로 리디렉션이 의도한 대로 작동하지 않음을 의미합니다. 로그인 후 리디렉션 대상 대신 이전에 있던 페이지로 전송됩니다.따라서 다른 방법으로 SavedRequestAware의 수정된 버전을 사용할 수 있습니다.인증SuccessHandler를 확장하는 대신 사용합니다.이렇게 하면 세션 속성을 사용할 시기를 보다 효과적으로 제어할 수 있습니다.

다음은 예입니다.

private static class MyCustomLoginSuccessHandler extends SimpleUrlAuthenticationSuccessHandler {

    private RequestCache requestCache = new HttpSessionRequestCache();

    @Override
    public void onAuthenticationSuccess(HttpServletRequest request, HttpServletResponse response,
            Authentication authentication) throws ServletException, IOException {
        SavedRequest savedRequest = requestCache.getRequest(request, response);

        if (savedRequest == null) {
            HttpSession session = request.getSession();
            if (session != null) {
                String redirectUrl = (String) session.getAttribute("url_prior_login");
                if (redirectUrl != null) {
                    session.removeAttribute("url_prior_login");
                    getRedirectStrategy().sendRedirect(request, response, redirectUrl);
                } else {
                    super.onAuthenticationSuccess(request, response, authentication);
                }
            } else {
                super.onAuthenticationSuccess(request, response, authentication);
            }

            return;
        }

        String targetUrlParameter = getTargetUrlParameter();
        if (isAlwaysUseDefaultTargetUrl()
                || (targetUrlParameter != null && StringUtils.hasText(request.getParameter(targetUrlParameter)))) {
            requestCache.removeRequest(request, response);
            super.onAuthenticationSuccess(request, response, authentication);

            return;
        }

        clearAuthenticationAttributes(request);

        // Use the DefaultSavedRequest URL
        String targetUrl = savedRequest.getRedirectUrl();
        logger.debug("Redirecting to DefaultSavedRequest Url: " + targetUrl);
        getRedirectStrategy().sendRedirect(request, response, targetUrl);
    }
}

또한 인증에 실패하면 레퍼러가 로그인 페이지 자체가 되기 때문에 레퍼러를 저장하지 않습니다.따라서 오류 매개 변수를 수동으로 확인하거나 아래와 같이 별도의 RequestMapping을 제공하십시오.

@RequestMapping(value = "/login", params = "error")
public String loginError() {
    // Don't save referrer here!
}

사용자 역할에 관계없이 특정 페이지로 리디렉션하려면 Spring의 구성 파일에서 defaultSuccessUrl을 사용하면 됩니다.

@Override
protected void configure(HttpSecurity http) throws Exception {
    
    
      http.authorizeRequests() 
      .antMatchers("/admin").hasRole("ADMIN") 
      .and()
      .formLogin() .loginPage("/login") 
                    .defaultSuccessUrl("/admin",true)
      .loginProcessingUrl("/authenticateTheUser")
      .permitAll();
     
    

가장 간단한 해결책은 확장된 성공 핸들러를 추가하는 것입니다.SimpleUrlAuthenticationSuccessHandler익명의 학급으로서.setUseReferer(true)초기화 블록에 있습니다.

    @Bean
    public SecurityFilterChain securityFilterChain(HttpSecurity http) throws Exception {
        return http
                //...
                .formLogin(
                        cfg -> cfg
                                .loginPage("/login")
                                .successHandler(new SimpleUrlAuthenticationSuccessHandler() {{
                                    setUseReferer(true);
                                }})
                )

                .logout(cfg -> cfg.logoutSuccessHandler((request, response, authentication) ->
                        response.sendRedirect(request.getHeader("Referer")))
                )
                //...

                .build();
    }

언급URL : https://stackoverflow.com/questions/14573654/spring-security-redirect-to-previous-page-after-successful-login

반응형