Springboot +spring security,方法权限注解

一.简介

这篇文章来讲下Spring Security的方法权限注解。

二.注解介绍

  1. @PostAuthorize:在目标方法执行之后进行权限校验
  2. @PostFilter:在目标方法执行之后对方法的返回结果进行过滤
  3. @PreAuthorize:在目标方法执行之前进行权限校验。
  4. @PreFilter:在目标方法执行之前对方法参数进行过滤。
  5. @Secured:访问目标方法必须具备相应的角色
  6. @DenyAll:拒绝所有访问
  7. @PermitAll: 允许所有访问
  8. @RolesAlowed:访问目标方法必须具有的角色

三.权限表达式

  1. hasRole(role):当前用户是否具备指定角色
  2. hasAnyRole(role …):当前用户是否具备指定角色中的任意一个
  3. hasAuthority(authority):当前用户是否具备指定的权限
  4. hasAnyAuthority(authority …):当前用户是否具备指定的权限任意一个
  5. principal:当前登录主体
  6. authentication:context中authentication对象
  7. permitAll():允许所有请求
  8. denyAll():拒绝所有请求
  9. isAnonymous():当前用户是否是一个匿名用户

四.创建项目

如何创建一个SpringSecurity项目,前面文章已经有说明了,这里就不重复写了。

依赖:

org.springframework.security:spring-security-test

五.基本用法

5.1权限注解用法

UserService类,代码如下:

@Service
public class UserService {
    @PreAuthorize("hasRole('ADMIN')")
    public String hello() {
        return "hello";
    }
    @PreAuthorize("hasRole('ADMIN') and authentication.name=='lglbc'")
    public String hello2() {
        return "hello";
    }
    @PreAuthorize("hasRole('ADMIN') and authentication.name==#name")
    public String hello3(String name) {
        return "hello";
    }

    @PreFilter(value = "filterObject.id%2!=0",filterTarget = "users")
    public void addUsers(List<User> users, Integer other) {
        System.out.println("users = " + JSON.toJSONString(users));
    }
    @PostFilter("filterObject.id%2==0")
    public List<User> getAll() {
        List<User> users = new ArrayList<>();
        for (int i = 0; i < 10; i++) {
            users.add(new User(i, "lglbc_:" + i));
        }
        return users;
    }

    @Secured({"ROLE_ADMIN","ROLE_USER"})
    public User getUserByUsername(String username) {
        return new User(99, username);
    }

    @DenyAll
    public String denyAll() {
        return "DenyAll";
    }

    @PermitAll
    public String permitAll() {
        return "PermitAll";
    }
    @RolesAllowed({"ADMIN","USER"})
    public String rolesAllowed() {
        return "RolesAllowed";
    }
}

ApplicationTest类,代码如下:

@SpringBootTest
public class ApplicationTest {
    @Autowired
    private UserService userService;

    @Test
    @WithMockUser(roles = "ADMIN")
    void preauthorizeTest01() {
        String result = userService.hello();
        assertNotNull(result);
    }

    @Test
    @WithMockUser(roles = "ADMIN", username = "lglbc")
    void preauthorizeTest02() {
        String result = userService.hello2();
        assertNotNull(result);
    }

    @Test
    @WithMockUser(roles = "ADMIN", username = "lglbc")
    void preauthorizeTest03() {
        String result = userService.hello3("lglbc");
        assertNotNull(result);
    }

    @Test
    @WithMockUser(username = "lglbc")
    void preFilterTest01() {
        List<User> users = new ArrayList<>();
        for (int i = 0; i < 10; i++) {
            users.add(new User(i, "lglbc_:" + i));
        }
        userService.addUsers(users, 99);
    }

    @Test
    @WithMockUser(roles = "ADMIN")
    void postFilterTest01() {
        List<User> all = userService.getAll();
        assertNotNull(all);
        assertEquals(5, all.size());
        assertEquals(2, all.get(1).getId());
    }

    @Test
    @WithMockUser(roles = "ADMIN")
    void securedTest01() {
        User user = userService.getUserByUsername("lglbc");
        assertNotNull(user);
        assertEquals(99, user.getId());
        assertEquals("lglbc", user.getUserName());
    }

    @Test
    @WithMockUser(username = "lglbc")
    void denyAllTest01() {
//        userService.denyAll();
    }

    @Test
    @WithMockUser(username = "lglbc")
    void permitAllTest01() {
        String s = userService.permitAll();
        assertNotNull(s);
        assertEquals("PermitAll", s);
    }

    @Test
    @WithMockUser(roles = "ADMIN")
    void rolesAllowedTest01() {
        String s = userService.rolesAllowed();
        assertNotNull(s);
        assertEquals("RolesAllowed", s);
    }
}

3.2权限表达式用法

SecurityExpressService 类,代码如下:

import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.stereotype.Service;

@Service
public class SecurityExpressService {
    @PreAuthorize("@permission.check(#value)")
    public String customPermission(String value){
        return value;
    }
    @PreAuthorize("hasAuthority('ROLE_admin')")
    public String hasAuthority(String value){
        return value;
    }
    @PreAuthorize("hasAnyAuthority('ROLE_admin','ROLE_user')")
    public String hasAnyAuthority(String value){
        return value;
    }
    @PreAuthorize("hasRole('admin')")
    public String hasRole(String value){
        return value;
    }
    @PreAuthorize("hasAnyRole('admin','user')")
    public String hasAnyRole(String value){
        return value;
    }
    @PreAuthorize("principal.username=='lglbc'")
    public String principal(String value){
        return value;
    }
    @PreAuthorize("permitAll()")
    public String permitAll(String value){
        return value;
    }
    @PreAuthorize("denyAll()")
    public String denyAll(String value){
        return value;
    }
}

SecurityExpressTest 类,代码如下:

import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.security.test.context.support.WithMockUser;

@SpringBootTest
public class SecurityExpressTest {
    @Autowired
    private SecurityExpressService securityExpressService;
    @Test
    @WithMockUser(roles = "admin")
    public void hasAuthority(){
        securityExpressService.hasAuthority("hello");
    }
    @Test
    @WithMockUser(roles = "admin")
    public void hasAnyAuthority(){
        securityExpressService.hasAnyAuthority("hello");
    }
    @Test
    @WithMockUser(roles = "admin")
    public void hasRole(){
        securityExpressService.hasRole("hello");
    }
    @Test
    @WithMockUser(roles = "user")
    public void hasAnyRole(){
        securityExpressService.hasAnyRole("hello");
    }
    @Test
    @WithMockUser(roles = "admin",username = "lglbc")
    public void principal(){
        securityExpressService.principal("hello");
    }
    @Test
    @WithMockUser()
    public void permitAll(){
        securityExpressService.permitAll("hello");
    }
    @Test
    @WithMockUser(roles = "admin")
    public void denyAll(){
        securityExpressService.denyAll("hello");
    }
    @Test
    @WithMockUser(roles = "admin")
    public void customPermission(){
        securityExpressService.customPermission("lglbc");
    }
}
  • 0
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

刘德华一不小心就打代码

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值