spring security 基于方法的鉴权
依赖
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-security</artifactId>
</dependency>
配置
@Configuration
@EnableWebSecurity
@EnableMethodSecurity // 启用基于方法鉴权 否则@PreAuthorize注解不好用
public class SecurityConfig {
// 由于不做认证,所以什么也没写
}
controller
import com.mydemo.permissiontest.service.PermissionTestSerivce;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
@RestController
@RequestMapping("/test")
public class UseJarController {
@Autowired
PermissionTestSerivce permissionTestSerivce;
@PreAuthorize("@sst.printTest()")
@GetMapping("/print")
public void testSST(){
System.out.println("SST 执行了");
}
@GetMapping("/testPer")
public void testPer(){
permissionTestSerivce.printTest();
}
}
权限鉴定方法
@Service("sst")
public class PermissionTestSerivce {
public boolean printTest() {
System.out.println("......打印测试.......");
return true; // true有权限 false 无权限 这里只是测试执行了没有
}
}
SpringSecurity基于方法的权限控制与@PreAuthorize应用示例
本文介绍了如何在SpringSecurity中启用基于方法的鉴权,使用@PreAuthorize注解进行权限控制,并通过例子展示了在@RestController和@Service中的应用。
4485





