SpringBoot+SpringSecurity实现权限控制

2022-08-13 09:47:55

上一篇文章已经实现了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来实现权限控制,如果没有特定权限,不显示特定内容。首先引入相关依赖:

<!-- https://mvnrepository.com/artifact/org.thymeleaf.extras/thymeleaf-extras-springsecurity5 -->
<dependency>
    <groupId>org.thymeleaf.extras</groupId>
    <artifactId>thymeleaf-extras-springsecurity5</artifactId>
    <version>3.0.4.RELEASE</version>
</dependency>

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

<html lang="en" xmlns:th="http://www.thymeleaf.org"
  xmlns:sec="http://www.thymeleaf.org/thymeleaf-extras-springsecurity4">

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

<div sec:authorize="hasAnyRole('root')">
  <a class="btn btn-sm btn-primary" th:href="@{'/emps/toUpdate/' + ${emp.getId()}}">编辑</a>
  <a class="btn btn-sm btn-danger" th:href="@{'/emps/delete/' + ${emp.getId()}}">删除</a>
</div>

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

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

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

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

  • 作者:weixin_46628668
  • 原文链接:https://blog.csdn.net/weixin_46628668/article/details/123939507
    更新时间:2022-08-13 09:47:55