spring security 授权方式(自定义)及源码跟踪

​ 这节我们来看看spring security的几种授权方式,及简要的源码跟踪。在初步接触spring security时,为了实现它的授权,特别是它的自定义授权,在网上找了特别多的文章以及例子,觉得好难,但是现在自己尝试结合官方文档及demo来学习,颇有收获。

基于表达式Spel的访问控制

​ Spring Security 使用 Spring EL 进行表达式支持,不了解Spring EL的童鞋自行学习。根据文档https://docs.spring.io/spring-security/site/docs/5.4.9/reference/html5/#el-access 在IDEA中查看SecurityExpressionRoot类的上下继承关系,SecurityExpressionOperations声明了各个表达式接口,最终由WebSecurityExpressionRoot、MethodSecurityExpressionRoot实现各个具体的表达式逻辑。继承关系如下所示:



​ 在这里我们能够知道,最常用的应该就是基于Web\Method这两种方式来进行授权我们的应用。再来看下 SecurityExpressionRoot 类中定义的最基本的 SpEL 有哪些:

​ 我们简单介绍几个表达式接口:

Expression Description
hasRole(String role) 如果当前主体具有指定的角色,则返回 true
hasAnyRole(String… roles) 如果当前主体具有任何提供的角色,则返回 true
hasAuthority(String authority) 如果当前主体具有指定的权限,则返回 true。
hasAnyAuthority(String… authorities) 如果当前主体具有任何提供的权限,则返回 true
authentication 允许直接访问从 SecurityContext 获得的当前 Authentication 对象
principal 允许直接访问代表当前用户的主体对象

授权方式

基于Web/Url的安全表达式

这种方式可以对单个Url进行安全验证,也可以对批量的Url进行安全验证,比如

@Override
protected void configure(HttpSecurity http) throws Exception {
http
.authorizeRequests()
// 针对/admin/api/hello 这个接口要有p1权限
.antMatchers("/admin/api/hello").hasAuthority("p1")
// 对于访问/user/api/** 的接口要有user权限
.antMatchers("/user/api/**").hasRole("USER")
.antMatchers("/app/api/**").permitAll()
.antMatchers("/css/**", "/index").permitAll()
.antMatchers("/user/**").hasRole("USER")
.and()
.formLogin()
.loginPage("/login")
.failureUrl("/login-error")
.permitAll();
}

基于Method的安全表达式

Method Security Expressions

Method security is a bit more complicated than a simple allow or deny rule. Spring Security 3.0 introduced some new annotations in order to allow comprehensive support for the use of expressions.

Spring Security 3.0 引入了一些新的注解,以便全面支持表达式的使用,分别是@PreAuthorize, @PreFilter, @PostAuthorize and @PostFilter相信大家有web开发的基础,不难知道这几个注解的意思。

  • @PreAuthorize:在访问方法前进行鉴权

  • @PreFilter:同上

  • @PostAuthorize:在访问方法后进行鉴权

  • @PostFiltert:同上

    public class AdminController {
    
        @GetMapping("hello")
    @PostAuthorize("hasRole('User')")
    public String hello() {
    return "hello, admin";
    } @GetMapping("p1")
    @PreAuthorize("hasAuthority('p1')")
    public String p1() {
    return "hello, p1";
    }
    }

但是基于方法的需要事先在配置类添加注解,表示开启方法验证。

@EnableGlobalMethodSecurity(securedEnabled = true,prePostEnabled = true)

根据官网介绍还有其他2中方式(基于AOP 、spring security原生的注释@Secure),有兴趣的小伙伴可以自行参阅https://docs.spring.io/spring-security/site/docs/5.4.9/reference/html5/#secure-object-impls

授权原理

​ 根据文档https://docs.spring.io/spring-security/site/docs/5.4.9/reference/html5/#secure-object-impls指出,spring security提供了拦截器来控制安全对象的访问,例如方法调用、web请求。AccessDecisionManager 做出关于是否允许调用继续进行的调用前决定。

​ 查看AccessDecisionManager 接口:

decide(Authentication authentication, Object object, Collection<ConfigAttribute> configAttributes)

参数说明:

  • authentication:当前登录对象主体
  • object: 当前安全保护对象
  • configAttributes:访问当前对象必须要有的权限属性

再看看看它的三个实现类,默认的实现是根据各个实现类的投票机制来决定是否能够访问当前安全保护对象的:

AffirmativeBased:只要configAttributes中有一个权限满足就可以访问当前保护对象

ConsensusBased:满足超过一半的权限就能够访问当前保护对象

UnanimousBased:configAttributes中所有的权限都满足才能访问当前保护对象

由于我们不知道默认是哪个实现类,所以我们在三个类上的decide方法都打上断点,这样我们就能知道默认是哪个实现类了,

内部的投票实现有兴趣的小伙伴自行探索,到这样我们大概就明白spring security默认的授权实现机制了。接着我们根据该机制去实现我们的自定义授权方式。

给出官网的一张原理图

  1. 首先,FilterSecurityInterceptor 从 SecurityContextHolder 获得一个 Authentication
  2. 其次,FilterSecurityInterceptor 从传入 FilterSecurityInterceptor 的 HttpServletRequest、HttpServletResponse 和 FilterChain 创建一个 FilterInvocation
  3. 接下来,它将 FilterInvocation 传递给 SecurityMetadataSource 以获取 ConfigAttributes
  4. 最后,它将 Authentication、FilterInvocation 和 ConfigAttributes 传递给 AccessDecisionManager。
    1. 如果授权被拒绝,则抛出 AccessDeniedException。在这种情况下,ExceptionTranslationFilter 处理 AccessDeniedException
    2. 如果访问被授予,FilterSecurityInterceptor 继续使用允许应用程序正常处理的 FilterChain。

自定义授权方式

​ 根据葫芦画瓢,我们首先需要

1、自定义一个AccessDecisionManager实现类,让它确定到底是否能够鉴权通过,能够访问保护对象;

@Component
public class CustomUrlDecisionManager implements AccessDecisionManager {
@Override
public void decide(Authentication authentication, Object object, Collection<ConfigAttribute> configAttributes) throws AccessDeniedException, InsufficientAuthenticationException {
for (ConfigAttribute configAttribute : configAttributes) {
String needRole = configAttribute.getAttribute();
if ("ROLE_LOGIN".equals(needRole)) {
if (authentication instanceof AnonymousAuthenticationToken) {
throw new AccessDeniedException("尚未登录,请登录!");
}else {
return;
}
}
Collection<? extends GrantedAuthority> authorities = authentication.getAuthorities();
for (GrantedAuthority authority : authorities) {
if (authority.getAuthority().equals(needRole)) {
return;
}
}
}
throw new AccessDeniedException("权限不足,请联系管理员!");
} @Override
public boolean supports(ConfigAttribute attribute) {
return true;
} @Override
public boolean supports(Class<?> clazz) {
return true;
}
}

2、接着实现一个FilterInvocationSecurityMetadataSource实现类,这个类给出访问保护对象具体需要的哪些权限。

/**
* 这个类的作用,主要是根据用户传来的请求地址,分析出请求需要的角色
*/
@Component
public class CustomFilterInvocationSecurityMetadataSource implements FilterInvocationSecurityMetadataSource {
@Autowired
MenuService menuService;
AntPathMatcher antPathMatcher = new AntPathMatcher();
@Override
public Collection<ConfigAttribute> getAttributes(Object object) throws IllegalArgumentException {
String requestUrl = ((FilterInvocation) object).getRequestUrl();
List<Menu> menus = menuService.getAllMenusWithRole();
for (Menu menu : menus) {
if (antPathMatcher.match(menu.getUrl(), requestUrl)) {
List<Role> roles = menu.getRoles();
String[] str = new String[roles.size()];
for (int i = 0; i < roles.size(); i++) {
str[i] = roles.get(i).getName();
}
return SecurityConfig.createList(str);
}
}
return SecurityConfig.createList("ROLE_LOGIN");
} @Override
public Collection<ConfigAttribute> getAllConfigAttributes() {
return null;
} @Override
public boolean supports(Class<?> clazz) {
return true;
}
}

3、将上面2个对象添加到拦截器中,给FilterSecurityInterceptor重新设置它的这2个属性

http.authorizeRequests()
.withObjectPostProcessor(new ObjectPostProcessor<FilterSecurityInterceptor>() {
@Override
public <O extends FilterSecurityInterceptor> O postProcess(O object) {
object.setAccessDecisionManager(customUrlDecisionManager);
object.setSecurityMetadataSource(customFilterInvocationSecurityMetadataSource);
return object;
}
})

​ 相信到这里,小伙伴也能根据自己实际项目需要怎样的授权方式去进行实现了,如果是AOP/@secure方式的则需要再看一下文档说明。好了,spring security的章节就到这里,后面继续学习spring security oauth2的章节。

spring security 授权方式(自定义)及源码跟踪的更多相关文章

  1. spring security之 默认登录页源码跟踪

    spring security之 默认登录页源码跟踪 ​ 2021年的最后2个月,立个flag,要把Spring Security和Spring Security OAuth2的应用及主流程源码研究透 ...

  2. spring security 之自定义表单登录源码跟踪

    ​ 上一节我们跟踪了security的默认登录页的源码,可以参考这里:https://www.cnblogs.com/process-h/p/15522267.html 这节我们来看看如何自定义单表认 ...

  3. spring security 认证源码跟踪

    spring security 认证源码跟踪 ​ 在跟踪认证源码之前,我们先根据官网说明一下security的内部原理,主要是依据一系列的filter来实现,大家可以根据https://docs.sp ...

  4. 涨姿势:Spring Boot 2.x 启动全过程源码分析

    目录 SpringApplication 实例 run 方法运行过程 总结 上篇<Spring Boot 2.x 启动全过程源码分析(一)入口类剖析>我们分析了 Spring Boot 入 ...

  5. Spring Boot 2.x 启动全过程源码分析

    Spring Boot 2.x 启动全过程源码分析 SpringApplication 实例 run 方法运行过程 上面分析了 SpringApplication 实例对象构造方法初始化过程,下面继续 ...

  6. spring MVC cors跨域实现源码解析

    # spring MVC cors跨域实现源码解析 > 名词解释:跨域资源共享(Cross-Origin Resource Sharing) 简单说就是只要协议.IP.http方法任意一个不同就 ...

  7. HTTP严格安全传输(HTTP Strict Transport Security, HSTS)chromuim实现源码分析(一)

    // HTTP strict transport security (HSTS) is defined in// http://tools.ietf.org/html/ietf-websec-stri ...

  8. Spring Boot REST(二)源码分析

    Spring Boot REST(二)源码分析 Spring 系列目录(https://www.cnblogs.com/binarylei/p/10117436.html) SpringBoot RE ...

  9. spring MVC cors跨域实现源码解析 CorsConfiguration UrlBasedCorsConfigurationSource

    spring MVC cors跨域实现源码解析 spring MVC cors跨域实现源码解析 名词解释:跨域资源共享(Cross-Origin Resource Sharing) 简单说就是只要协议 ...

随机推荐

  1. 半天撸一个简易版mybatis

    为什么需要持久层框架? 首先我们先看看使用原生jdbc存在的问题? public static void main(String[] args) { Connection connection = n ...

  2. Linux主机入侵检测

    检查系统信息.用户账号信息 ● 操作系统信息 cat /proc/version 用户信息 用户信息文件 /etc/passwd root:x:0:0:root:/root:/bin/bash 用户名 ...

  3. Hadoop集群的配置(一)

    摘要: hadoop集群配置系列文档,是笔者在实验室真机环境实验后整理而得.以便随后工作所需,做以知识整理,另则与博客园朋友分享实验成果,因为笔者在学习初期,也遇到不少问题.但是网上一些文档大多互相抄 ...

  4. 了解 js 堆内存 、栈内存 。

    js中的堆内存与栈内存 在js引擎中对变量的存储主要有两种位置,堆内存和栈内存. 和java中对内存的处理类似,栈内存主要用于存储各种基本类型的变量,包括Boolean.Number.String.U ...

  5. $dy$讲课总结

    字符串: 1.广义后缀自动机(大小为\(m\))上跑一个长度为\(n\)的串,所有匹配位置及在\(parent\)树上其祖先的数量的和为\(min(n^2,m)\),单次最劣是\(O(m)\). 但是 ...

  6. IC封装的热特性

    ΘJA是结到周围环境的热阻,单位是°C/W.周围环境通常被看作热"地"点.ΘJA取决于IC封装.电路板.空气流通.辐射和系统特性,通常辐射的影响可以忽略.ΘJA专指自然条件下(没有 ...

  7. 对JavaScript中局部变量、全局变量和闭包的理解

    对js中局部变量.全局变量和闭包的理解 局部变量 对于局部变量,js给出的定义是这样的:在 JavaScript函数内部声明的变量(使用 var)是局部变量,所以只能在函数内部访问它.(该变量的作用域 ...

  8. 链表中环的入口结点 牛客网 剑指Offer

    链表中环的入口结点 牛客网 剑指Offer 题目描述 给一个链表,若其中包含环,请找出该链表的环的入口结点,否则,输出null. # class ListNode: # def __init__(se ...

  9. 0x04

    二分: while(l<r) { int mid=(l+r)/2; if(符合条件) r=mid; else l=mid+1; } 固定下二分的写法: 终止条件:l==r: 取mid=(l+r) ...

  10. cf 12B Correct Solution?(贪心)

    题意: 一个数a,一个数b. 现在要将a的每一位上的数字重新整理,生成一个新的不含前导0的数a'. 问a'是否等于b. 思路: a上每一位的数字从小到大排序,找到最小的非零数和第一位交换. 代码: c ...