Spring Security redirect to previous page after successful login

前端 未结 9 1191
孤独总比滥情好
孤独总比滥情好 2020-11-27 10:09

I know this question has been asked before, however I\'m facing a particular issue here.

I use spring security 3.1.3.

I have 3 possible login cases in my web

9条回答
  •  不知归路
    2020-11-27 10:38

    You can use a Custom SuccessHandler extending SimpleUrlAuthenticationSuccessHandler for redirecting users to different URLs when login according to their assigned roles.

    CustomSuccessHandler class provides custom redirect functionality:

    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 authorities =  authentication.getAuthorities();
    
            List roles = new ArrayList();
    
            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 roles) {
            if (roles.contains("ROLE_USER")) {
                return true;
            }
            return false;
        }
    
        private boolean isStudent(List roles) {
            if (roles.contains("ROLE_Student")) {
                return true;
            }
            return false;
        }
    
        private boolean isAdmin(List roles) {
            if (roles.contains("ROLE_SystemAdmin") || roles.contains("ROLE_ExaminationsStaff")) {
                return true;
            }
            return false;
        }
    
        private boolean isStaff(List roles) {
            if (roles.contains("ROLE_AcademicStaff") || roles.contains("ROLE_UniversityAdmin")) {
                return true;
            }
            return false;
        }
    }
    

    Extending Spring SimpleUrlAuthenticationSuccessHandler class and overriding handle() method which simply invokes a redirect using configured RedirectStrategy [default in this case] with the URL returned by the user defined determineTargetUrl() method. This method extracts the Roles of currently logged in user from Authentication object and then construct appropriate URL based on there roles. Finally RedirectStrategy , which is responsible for all redirections within Spring Security framework , redirects the request to specified URL.

    Registering CustomSuccessHandler using SecurityConfiguration class:

    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 is the class responsible for eventual redirection based on any custom logic, which in this case will be to redirect the user [to student/admin/staff ] based on his role [USER/Student/SystemAdmin/UniversityAdmin/ExaminationsStaff/AcademicStaff].

提交回复
热议问题