使用 Spring Security 根据用户角色登录后重定向到不同的页面 [英] Redirect to different page after login based on user role with Spring Security

查看:37
本文介绍了使用 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>

</html>

在这里,我正在创建单独的链接以作为管理员/用户登录.如何根据输入的凭据添加一个重定向到下一页的登录页面,例如:如果 user1 是管理员,如果输入了他的凭据,他将被重定向到管理页面,反之亦然以供用户登录

这是我的 spring 安全配置代码:

here is my spring security config code :

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.

You can supply a custom AuthenticationSuccessHandler.
The AuthenticationSuccessHandler is what tells Spring Security what to do after a successful user authentication.
The default implementation typically uses a SimpleUrlAuthenticationSuccessHandler, which redirects users to the supplied URL once they successfully authenticate.

在您的自定义实现中,您可以根据用户的角色委托给不同的 SimpleUrlAuthenticationSuccessHandler.

In your custom implementation, you can delegate to a different SimpleUrlAuthenticationSuccessHandler based on the user's role.

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.

Then, supply the CustomAuthenticationSuccessHandler in the form login configuration.

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

这篇关于使用 Spring Security 根据用户角色登录后重定向到不同的页面的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆