1 通过在方法上加注解实现方法的安全
2 方法安全默认是不开启的
3 Spring Security配置类上加注解@EnableGlobalMethodSecurity
4 提示信息如下
@EnableGlobalMethodSecurity(prePostEnabled=true)
使用表达式时间方法级别的安全性 4个注解可用
@PreAuthorize 在方法调用之前,基于表达式的计算结果来限制对方法的访问
@PostAuthorize 允许方法调用,但是如果表达式计算结果为false,将抛出一个安全性异常
@PostFilter 允许方法调用,但必须按照表达式来过滤方法的结果
@PreFilter 允许方法调用,但必须在进入方法之前过滤输入值
@EnableGlobalMethodSecurity(securedEnabled=true)
开启@Secured 注解过滤权限
@EnableGlobalMethodSecurity(jsr250Enabled=true)
开启@RolesAllowed 注解过滤权限
1 在配置类上启动方法安全保护,启用prePostEnabled 和 securedEnabled
@EnableGlobalMethodSecurity(prePostEnabled = true,securedEnabled = true)
2 创建service类,设置对应的访问权限
package org.akk.security.service;
import org.springframework.security.access.annotation.Secured;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.stereotype.Service;
@Service
public class MethodService {
@PreAuthorize("hasRole('admin')")
public String admin(){
return "hello admin";
}
// 需要注意的是@Secured("ROLE_user") 必须又ROLE_作为前缀,不能会权限失效 谁也进不去
@Secured("ROLE_user")
public String user(){
return "hello user";
}
@PreAuthorize("hasAnyRole('admin','user')")
public String hello() {
return "hello function";
}
}
3 在Controller类添加对应RestApi
@GetMapping("/methodAdmin")
public String methodAdmin(){
return methodService.admin();
}
@GetMapping("/methodUser")
public String methodUser(){
return methodService.user();
}
@GetMapping("/methodAdminAndUser")
public String methodAdminAndUser(){
return methodService.hello();
}
4使用不同权限来测试
首先使用user权限的akk
下图post登录成功
调用methodAdminAndUser User和Admin都可以访问的Api
下图成功调用
调用methodUser User访问的Api 成功访问
调用methodAdmin User访问的Api 访问失败
Forbidden没有权限
{
"timestamp": "2020-04-12T09:04:38.413+0000",
"status": 403,
"error": "Forbidden",
"message": "Forbidden",
"path": "/methodAdmin"
}