Springboot +spring security,方法权限注解

阿里云国内75折 回扣 微信号:monov8
阿里云国际,腾讯云国际,低至75折。AWS 93折 免费开户实名账号 代冲值 优惠多多 微信号:monov8 飞机:@monov6

一.简介

这篇文章来讲下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");
    }
}
阿里云国内75折 回扣 微信号:monov8
阿里云国际,腾讯云国际,低至75折。AWS 93折 免费开户实名账号 代冲值 优惠多多 微信号:monov8 飞机:@monov6
标签: Spring