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

<!-- 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页面。

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值