Security配置不同的角色登陆到不同页面/路径

网上很多教程对不同路径或页面登录讲解模糊,只给思路未贴代码。博主做项目时踩坑,记录配置Security及创建LoginSuccessHandle实现接口,通过在response.sendRedirect中写不同角色登录路径来完成配置。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

在网上看到很多教程,登陆到不同的路径或页面,讲的都很模糊。或者说没有贴代码,只给了部分思路。在做项目的时候踩了不少坑,在此记录一下。

配置Security


@EnableWebSecurity
@EnableGlobalMethodSecurity(prePostEnabled = true) // 启用方法安全设置
public class SecurityConfig extends WebSecurityConfigurerAdapter {//首先是继承WebSecurityConfigurerAdapter 

    private  static  final String KEY="wxj1994";

    @Autowired
    private UserDetailsService userDetailsService;

    @Autowired
    private PasswordEncoder passwordEncoder;

    @Bean
    public PasswordEncoder passwordEncoder() {
        return new BCryptPasswordEncoder();   // 使用 BCrypt 加密
    }

    @Bean
    public AuthenticationProvider authenticationProvider() {
        DaoAuthenticationProvider authenticationProvider = new DaoAuthenticationProvider();
        authenticationProvider.setUserDetailsService(userDetailsService);
        authenticationProvider.setPasswordEncoder(passwordEncoder); // 设置密码加密方式
        return authenticationProvider;
    }


@Override
protected void configure(HttpSecurity http) throws Exception {
    http.authorizeRequests().antMatchers("/css/**", "/js/**", "/fonts/**","/Playerss","manage/**").permitAll() // 都可以访问
            .antMatchers("/h2-console/**").permitAll() // 都可以访问
            .antMatchers("/admins/**").hasRole("ADMIN") // 需要相应的角色才能访问
            .and()
            .formLogin()   //基于 Form 表单登录验证
            .loginPage("/login").failureUrl("/login-error").defaultSuccessUrl("/admin/adminindex").successHandler(new LoginSuccessHandle()) // 自定义登录界面

            .and().rememberMe().key(KEY) // 启用 remember me
            .and().exceptionHandling().accessDeniedPage("/403");  // 处理异常,拒绝访问就重定向到 403 页面




    http.csrf().ignoringAntMatchers("/h2-console/**"); // 禁用 H2 控制台的 CSRF 防护
    http.headers().frameOptions().sameOrigin(); // 允许来自同一来源的H2 控制台的请求
}





    @Override
    public void configure(WebSecurity web) throws Exception {
        //解决静态资源被拦截的问题
        web.ignoring().antMatchers("/manage/**","/css/**","/js/**");
    }


/***
 * 认证信息管理
 * **/
    @Autowired
    public void configureGlobal(AuthenticationManagerBuilder auth) throws Exception {
        auth.userDetailsService(userDetailsService);
        auth.authenticationProvider(authenticationProvider());
    }

}
***这一段主要是配置不同的角色登陆不同的路径或者页面***
  • 这一段主要是配置不同的角色登陆不同的路径或者页面
    接下来创建一个LoginSuccessHandle 实现AuthenticationSuccessHandler接口
public class LoginSuccessHandle implements AuthenticationSuccessHandler {

    @Override
    public void onAuthenticationSuccess(HttpServletRequest request, HttpServletResponse response, Authentication authentication)throws IOException {

        Set<String> roles = AuthorityUtils.authorityListToSet(authentication.getAuthorities());
        //获取到登陆者的权限,然后做跳转
        if (roles.contains("ROLE_ADMIN")){ 
            response.sendRedirect("/****");

            return;
        }else if (roles.contains("ROLE_USER")){
            response.sendRedirect("/*****");
            System.out.println();
            return;
        }else {
            response.sendRedirect("/403");
        }

    }
}

在 response.sendRedirect(“/**“);里面写上你不同角色登陆的不同路径
OK 大功告成!

评论 4
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值