权限控制(springboot整合security实现权限控制)

圈圈笔记 62

环境:Springboot2.4.12 + Spring Security 5.4.9

本篇主要内容:

基于Web表达式认证授权PreAuthorize高级用法

上一篇:《Spring Security权限控制系列(六)》

基于Web表达式认证授权

本节将展示各种认证的方式方法。

Web安全表达式中引用bean@ComponentpublicclassWebSecurity{publicbooleancheck(Authentication authentication, HttpServletRequest request){// 判断当前登录用户需要拥有bus:news:delete权限SimpleGrantedAuthority auth =newSimpleGrantedAuthority("bus:news:delete") ;returnauthentication.getAuthorities().contains(auth) ; } } http.authorizeRequests().antMatchers("/a/index1").access("@webSecurity.check(authentication,request)") ;Web安全表达式中的路径变量publicbooleancheckUserId(Authentication authentication,intid){if(!(authentication.getPrincipal()instanceofUsers)) {returnfalse; } Users user = (Users)authentication.getPrincipal() ;returnuser.getId().equals(String.valueOf(id)) ; } http.authorizeRequests().antMatchers("/a/index2/{userId}").access("@webSecurity.checkUserId(authentication,userId)") ;多条件表达式http.authorizeRequests().antMatchers("/a/index3").access("hasRole(USERS) and hasIpAddress(192.168.1.0/24)") ;

PreAuthorize高级用法

基于方法参数认证// 验证逻辑publicbooleanhasPermission(Authentication authentication,ObjecttargetDomainObject,Objectpermission) {returntargetDomainObject.equals(permission) ; }@PreAuthorize("hasPermission(role, USERS)")@GetMapping("/index4")publicObjectindex4(Stringrole) {return"index4 - "+ role ; }// 即可以使用对象@PreAuthorize("hasPermission(user, USERS)")publicObjectindex4(Users user)// 访问对象属性@PreAuthorize("hasPermission(user.name, admin)")publicObjectindex4(Users user)基于参数名的访问// 使用@P标记参数@PreAuthorize("u.name == authentication.name") public Object index4(@P("u") Users user)// 使用@Param标记参数@PreAuthorize("n == authentication.name") public Object index4(@Param("n") String name);自定义认证注解

注释可以用于Spring Security方法的任何安全注释。为了与规范保持兼容,JSR-250注释不支持元注释。

@Retention(RetentionPolicy.RUNTIME)@PreAuthorize("u.name == authentication.name") public@interfaceUsersPermission {}// 使用@UsersPermissionpublic Object index4(@P("u") Users user)

自定义认证逻辑

@PreAuthorize("@s.check(bus:news:update)")@GetMapping("/index5")publicObject index5() {return"index5"; }

自定义认证

publicclassAuthorityService{publicbooleancheck(String authority){ Users users = getUsers() ;if(users ==null) {returnfalse; } Collection authorities = users.getAuthorities() ; SimpleGrantedAuthority auth =newSimpleGrantedAuthority(authority) ;returnauthorities.contains(auth) ; }publicUsersgetUsers(){ Authentication authentication = SecurityContextHolder.getContext().getAuthentication() ;if(authentication ==null) {returnnull; } Object r = authentication.getPrincipal() ;if(rinstanceofUsers) {return(Users) r; }returnnull; } }

总结:

基于Web表达式认证授权PreAuthorize高级用法

Spring Security权限控制系列(一)Spring Security权限控制系列(二)Spring Security权限控制系列(三)Spring Security权限控制系列(四)Spring Security权限控制系列(五)Spring Security权限控制系列(六)Spring Security记住我功能实现及源码分析Spring Security 自定义登录成功后的逻辑SpringBoot WebFlux整合Spring Security进行权限认证

上一篇:

下一篇:

  推荐阅读

分享