基于SpringSecurity实现RBAC权限控制(待完善)

Spring Security是一个企业应用系统提供声明式的安全访问控制功能,减少为企业应用系统安全控制而编写的大量重复代码

认证:

spring security的原理就是使用很多的拦截器对URL进行拦截,以此来管理用户登录和授权,用户登录时,会被AuthenticationProcessingFilter拦截,通过ProviderManager来对用户信息进行验证,如果验证通过后会将用户的权限信息封装User放到SecurityContextHolder中,以备后面访问资源时使用。

我们要自定义用户的校验机制的话,只要实现AuthenticationProvider,将他注入到配置类中

授权:

基于RBAC的权限控制,RBAC一般都是由 3部分组成,用户,角色 ,资源(菜单,按钮),然后就是用户和角色的关联表,角色和资源的关联表核心就是判断当前用户所拥有的URL是否和当前访问的URL是否匹配

 

Spring Security配置

@Configuration
@EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter {

    @Autowired
    private AuthenticationProvider provider;

    @Autowired
    private AuthenticationSuccessHandler myAuthenticationSuccessHandler;
    
    @Autowired
    private AuthenticationFailureHandler myAuthenticationFailHander;
    
    //注入我们自己的AuthenticationProvider
    @Override
    protected void configure(HttpSecurity http) throws Exception {
           http 
           //表示表单登录的url是/login,表单提交的url是/login/form
           //myAuthenticationSuccessHandler   登录成功处理器
           //myAuthenticationFailHander   登录失败处理器
          .formLogin().loginPage("/login").loginProcessingUrl("/login/form")
          .successHandler(myAuthenticationSuccessHandler)
          .failureHandler(myAuthenticationFailHander)
          .permitAll() 
          //permitAll()表示允许访问/login,/login/form
          .and()
          //设置授权请求,任何请求都要经过下面的权限表达式处理
          .authorizeRequests()
          .anyRequest().access("@rbacService.hasPermission(request,authentication)") //权限表达式          
          .and()
          //在Security的默认拦截器里,默认会开启CSRF处理,判断请求是否携带了token,如果没有就拒绝访问,所以这里要关闭CSRF处理
          .csrf().disable();
    }

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

 

github下载地址:https://github.com/jake1263/SpringSecurity

posted @ 2019-07-16 18:28  踏月而来  阅读(1814)  评论(0编辑  收藏  举报