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. 【数据结构与算法Python版学习笔记】图——词梯问题 广度优先搜索 BFS

    词梯Word Ladder问题 要求是相邻两个单词之间差异只能是1个字母,如FOOL变SAGE: FOOL >> POOL >> POLL >> POLE > ...

  2. Spring Security Jwt Token 自动刷新

    token的自动刷新 一.功能需求 二.功能分析 1.token 的生成 2.token 的自动延长 3.系统资源的保护 4.用户如何传递 token 三.实现思路 1.生成 token 和 refr ...

  3. 扩展spring data jpa的repository

    在我们编写代码的过程中,spring data jpa为我们的持久层提供的极大的方便,但有时spring data jpa提供的repository并不能完全满足我们开发的需求,因此就需要进行扩展.s ...

  4. Go 里的超时控制

    前言 日常开发中我们大概率会遇到超时控制的场景,比如一个批量耗时任务.网络请求等:一个良好的超时控制可以有效的避免一些问题(比如 goroutine 泄露.资源不释放等). Timer 在 go 中实 ...

  5. AFO记

    希望永远也不要动笔写这个. 发以自勉

  6. NB-IoT的DRX、eDRX、PSM三个模式怎么用?通俗解释,看完就懂!

    面我们讲了不少NB-IOT的应用.软件和硬件设计的变动. (链接在文章末尾). 今天讲讲NB-IoT的三大模式,在各种物联网和智能硬件场景中的使用方法 DRX.eDRx.PSM是什么? DRX虽然叫做 ...

  7. WPF PropertyChanged实现子属性通知

    今天用WPF的View绑定了ViewModel的一个属性类,结果在属性类的子属性修改时,没有通知到UI. 如有要显示一个学生信息,采用WPF MVVM的模式,则前端代码 <StackPanel& ...

  8. python读取、写入txt文本内容

    转载:https://blog.csdn.net/qq_37828488/article/details/100024924 python常用的读取文件函数有三种read().readline().r ...

  9. 前端面试手写代码——JS数组去重

    目录 1 测试用例 2 JS 数组去重4大类型 2.1 元素比较型 2.1.1 双层 for 循环逐一比较(es5常用) 2.1.2 排序相邻比较 2.2 查找元素位置型 2.2.1 indexOf ...

  10. 折腾systemd-nspawn运行centos7

    Archlinux创建Debian/Ubuntu的systemd-nspawn容器是很简单的,因为有debootstrap软件.某天我突然想装个centos7玩玩,搜了半天没发现有什么类似于deboo ...