SpringBoot+SpringSecurity实现权限控制

上一篇文章已经实现了SpringBoot+SpringSecurity查询数据库自定义登录,接下来要实现权限控制。继续修改config(HttpSecurity http)方法:

@Override
protected void configure(HttpSecurity http) throws Exception {
    http.formLogin()
            .loginPage("/toLogin")
            .loginProcessingUrl("/log")
            .defaultSuccessUrl("/main")
            .failureForwardUrl("/failed")
            .permitAll()
            .and()
            .authorizeRequests()
            .antMatchers("/", "/index", "/login", "/css/*", "/js/*", "/img/*")
            .permitAll()
            .antMatchers("/emps").hasAuthority("root")
            .anyRequest()
            .authenticated()
            .and().csrf().disable();
}

其中的antMatchers("/emp").hasAnyRole("root")表示/emps请求(包括/emps/*这种请求)必须要有root权限才能请求成功。与hasAuthority方法类似的还要hasAnyAuthority、hasRole、hasAnyRole。hasAnyAuthority方法的参数值中的字符串是多个权限,以逗号隔开,表示只要该用户有其中一个权限就可以请求。hasRole与hasAnyRole也是类似的,只不过SpringSecurity中做权限判断时会加上前缀:ROLE_。如果没有权限,会自动跳到SpringSecurity的默认403页面。

前端也可以通过themeleaf-springsecurity来实现权限控制,如果没有特定权限,不显示特定内容。首先引入相关依赖:



    org.thymeleaf.extras
    thymeleaf-extras-springsecurity5
    3.0.4.RELEASE

然后在html中引入命名空间:

如果想让root角色的用户看到相关内容,通过sec:authorize标签来实现:

这里的hasAnyRole与后端的hasAnyRole方法是一个意思。

为了自定义403页面,可以在config(HttpSecurity http)中加上语句:

http.exceptionHandling().accessDeniedPage("/nopermission");

其中的/nopermissio是一个请求名,再写个相应的controller就可以跳转到自定义的403页面。

你可能感兴趣的:(spring,boot,html,java,bootstrap)