簡體   English   中英

使用 Spring 安全性根據用戶角色登錄后重定向到不同的頁面

[英]Redirect to different page after login based on user role with Spring Security

 <.DOCTYPE html> <html> <head> <meta charset="ISO-8859-1"> <title>Welcome to Akash Home</title> <link rel="stylesheet" type="text/css" href="/webjars/bootstrap/css/bootstrap.min.css" /> <script type="text/javascript" src="/webjars/jquery/jquery.min.js"></script> <script type="text/javascript" src="/webjars/bootstrap/js/bootstrap.min.js"></script> </head> <body> <div class="container text-center"> <h1>Welcome to the portal</h1> <h3> <a href="/register">Register</a> </h3> <h3> <a href="show-menu-list-admin">Login as a admin</a><br> <a href="show-menu-list-customer">Login as a user</a><br> <!-- <a href="login">login</a> --> <a href="logout">logout</a> </h3> </div> </body> </html>

在這里,我正在創建單獨的鏈接以作為管理員/用戶登錄。 如何根據輸入的憑據添加單個登錄頁面重定向到下一頁:如果 user1 是管理員,如果輸入了他的憑據,他將被重定向到管理頁面,反之亦然以進行用戶登錄

這是我的 spring 安全配置代碼:

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.authentication.dao.DaoAuthenticationProvider;
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;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;

@Configuration
@EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter {

    @Bean
    public UserDetailsService getUserDetailService() {
        return new UserDetailsServiceImpl();
    }

    @Bean
    public BCryptPasswordEncoder passwordEncoder() {
        return new BCryptPasswordEncoder();
    }

    @Bean
    public DaoAuthenticationProvider authenticationProvider() {
        DaoAuthenticationProvider daoAuthenticationProvider = new DaoAuthenticationProvider();
        daoAuthenticationProvider.setUserDetailsService(this.getUserDetailService());
        daoAuthenticationProvider.setPasswordEncoder(passwordEncoder());

        return daoAuthenticationProvider;
    }

//  authentication - configure method

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

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http.authorizeRequests().antMatchers("/show-menu-list-admin").hasRole("ADMIN")
                .antMatchers("/show-menu-list-customer").hasRole("USER").and().formLogin().and().csrf().disable();
    }

}

您可以提供自定義AuthenticationSuccessHandler
AuthenticationSuccessHandler告訴 Spring Security 在成功的用戶身份驗證后做什么。
默認實現通常使用SimpleUrlAuthenticationSuccessHandler ,一旦用戶成功通過身份驗證,它將重定向到提供的 URL。

在您的自定義實現中,您可以根據用戶的角色委托給不同的SimpleUrlAuthenticationSuccessHandler

public class CustomAuthenticationSuccessHandler implements AuthenticationSuccessHandler {
    SimpleUrlAuthenticationSuccessHandler userSuccessHandler =
            new SimpleUrlAuthenticationSuccessHandler("/user-page");
    SimpleUrlAuthenticationSuccessHandler adminSuccessHandler =
            new SimpleUrlAuthenticationSuccessHandler("/admin-page");

    @Override
    public void onAuthenticationSuccess(HttpServletRequest request, HttpServletResponse response,
            Authentication authentication) throws IOException, ServletException {
        Collection<? extends GrantedAuthority> authorities = authentication.getAuthorities();
        for (final GrantedAuthority grantedAuthority : authorities) {
            String authorityName = grantedAuthority.getAuthority();
            if (authorityName.equals("ROLE_ADMIN")) {
                // if the user is an ADMIN delegate to the adminSuccessHandler
                this.adminSuccessHandler.onAuthenticationSuccess(request, response, authentication);
                return;
            }
        }
        // if the user is not an admin delegate to the userSuccessHandler
        this.userSuccessHandler.onAuthenticationSuccess(request, response, authentication);
    }
}

然后,在表單登錄配置中提供CustomAuthenticationSuccessHandler

http
    .formLogin(formLogin -> formLogin
        .successHandler(new CustomAuthenticationSuccessHandler())
    );

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM