最近项目需要做“接口权限”控制,但不需要做RBAC (Role Based Access Control)这种大的业务。于是有下面的方案。
一、项目pom文件
<parent><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-parent</artifactId><version>3.1.2</version><relativePath/> <!-- lookup parent from repository --></parent><dependencies><dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-security</artifactId></dependency><dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-web</artifactId></dependency><dependency><groupId>org.projectlombok</groupId><artifactId>lombok</artifactId><optional>true</optional></dependency></dependencies>
二、过滤器及配置
1、过滤器功能:从请求头获取 “auth”的值,等于“1”,则放行。
2、安全配置使用默认配置
3、@EnableMethodSecurity 则是告诉spring容器,@PreAuthorize注解可生效
@Configuration
@EnableMethodSecurity
public class AuthFilter extends OncePerRequestFilter {@Beanpublic SecurityFilterChain securityFilterChain(HttpSecurity http) throws Exception {return http.build();}@Overrideprotected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws ServletException, IOException {String token = request.getHeader("auth");CustAuComp.flag = token.equals("1");filterChain.doFilter(request, response);}}
三、自定义授权对象
“custAu”组件名,与后面controller授权注解“@PreAuthorize”对应
/*** 自定义授权对象*/
@Component("custAu")
public class CustAuComp {/*** 简单的放行开关*/public static boolean flag = false;/*** 自定义的方法* @param elVal el表达式* @return true 放行*/public boolean hasPermission(String elVal) {System.out.println("hasPermission "+elVal);return flag;}}
四、Controller
@PreAuthorize(“@custAu.hasPermission(‘role1’)”)
custAu 与第三的组件名对应,hasPermission与其内的方法对应,role1是EL表达式
@RestController
@RequestMapping("/hello")
public class HelloController {@GetMapping("demo")@PreAuthorize("@custAu.hasPermission('role1')")public String genPubKey() {return System.currentTimeMillis()+" hello,world";}}
五、测试
拦截是否通过与第二步有关
六、最后
SpringSecurity最近的更新速度蛮快的,网上资料看得晕头转向。
实际上,我们只需要明白它的核心是spring“过滤器”就好。
参考资料:参考