说明 springboot 版本 2.0.3
源码地址:点击跳转

系列

  这篇讲解如何自定义鉴权过程,实现根据数据库查询出的 url 和 method 是否匹配当前请求的 url 和 method 来决定有没有权限。security 鉴权过程如下:

一、 重写 metadataSource 类

  1. 编写 MyGranteAuthority 类,让权限包含 url 和 method 两个部分。
public class MyGrantedAuthority implements GrantedAuthority {
private String method;
private String url; public MyGrantedAuthority(String method, String url) {
this.method = method;
this.url = url;
} @Override
public String getAuthority() {
return url;
} public String getMethod() {
return method;
} public String getUrl() {
return url;
} @Override
public boolean equals(Object obj) {
if(this==obj) return true;
if(obj==null||getClass()!= obj.getClass()) return false;
MyGrantedAuthority grantedAuthority = (MyGrantedAuthority)obj;
if(this.method.equals(grantedAuthority.getMethod())&&this.url.equals(grantedAuthority.getUrl()))
return true;
return false;
}
}
  1. 编写 MyConfigAttribute 类,实现 ConfigAttribute 接口,代码如下:

public class MyConfigAttribute implements ConfigAttribute {
private HttpServletRequest httpServletRequest;
private MyGrantedAuthority myGrantedAuthority; public MyConfigAttribute(HttpServletRequest httpServletRequest) {
this.httpServletRequest = httpServletRequest;
} public MyConfigAttribute(HttpServletRequest httpServletRequest, MyGrantedAuthority myGrantedAuthority) {
this.httpServletRequest = httpServletRequest;
this.myGrantedAuthority = myGrantedAuthority;
} public HttpServletRequest getHttpServletRequest() {
return httpServletRequest;
} @Override
public String getAttribute() {
return myGrantedAuthority.getUrl();
} public MyGrantedAuthority getMyGrantedAuthority() {
return myGrantedAuthority;
}
}
  1. 编写 MySecurityMetadataSource 类,获取当前 url 所需要的权限
@Component
public class MySecurityMetadataSource implements FilterInvocationSecurityMetadataSource { private Logger log = LoggerFactory.getLogger(this.getClass()); @Autowired
private JurisdictionMapper jurisdictionMapper;
private List<Jurisdiction> jurisdictions; private void loadResource() {
this.jurisdictions = jurisdictionMapper.selectAllPermission();
} @Override
public Collection<ConfigAttribute> getAttributes(Object object) throws IllegalArgumentException {
if (jurisdictions == null) this.loadResource();
HttpServletRequest request = ((FilterInvocation) object).getRequest();
Set<ConfigAttribute> allConfigAttribute = new HashSet<>();
AntPathRequestMatcher matcher;
for (Jurisdiction jurisdiction : jurisdictions) {
//使用AntPathRequestMatcher比较可让url支持ant风格,例如/user/*/a
//*匹配一个或多个字符,**匹配任意字符或目录
matcher = new AntPathRequestMatcher(jurisdiction.getUrl(), jurisdiction.getMethod());
if (matcher.matches(request)) {
ConfigAttribute configAttribute = new MyConfigAttribute(request,new MyGrantedAuthority(jurisdiction.getMethod(),jurisdiction.getUrl()));
allConfigAttribute.add(configAttribute);
//这里是获取到一个权限就返回,根据校验规则也可获取多个然后返回
return allConfigAttribute;
}
}
//未匹配到,说明无需权限验证
return null;
} @Override
public Collection<ConfigAttribute> getAllConfigAttributes() {
return null;
} @Override
public boolean supports(Class<?> clazz) {
return FilterInvocation.class.isAssignableFrom(clazz);
}
}

二、 编写 MyAccessDecisionManager 类

  实现 AccessDecisionManager 接口以实现权限判断,直接 return 说明验证通过,如不通过需要抛出对应错误,代码如下:

@Component
public class MyAccessDecisionManager implements AccessDecisionManager{
private Logger log = LoggerFactory.getLogger(this.getClass()); @Override
public void decide(Authentication authentication, Object object, Collection<ConfigAttribute> configAttributes)
throws AccessDeniedException, InsufficientAuthenticationException {
//无需验证放行
if(configAttributes==null || configAttributes.size()==0)
return;
if(!authentication.isAuthenticated()){
throw new InsufficientAuthenticationException("未登录");
}
Collection<? extends GrantedAuthority> authorities = authentication.getAuthorities();
for(ConfigAttribute attribute : configAttributes){
MyConfigAttribute urlConfigAttribute = (MyConfigAttribute)attribute;
for(GrantedAuthority authority: authorities){
MyGrantedAuthority myGrantedAuthority = (MyGrantedAuthority)authority;
if(urlConfigAttribute.getMyGrantedAuthority().equals(myGrantedAuthority))
return;
}
}
throw new AccessDeniedException("无权限");
} @Override
public boolean supports(ConfigAttribute attribute) {
return true;
} @Override
public boolean supports(Class<?> clazz) {
return true;
}
}

三、 编写 MyFilterSecurityInterceptor 类

  该类继承 AbstractSecurityInterceptor 类,实现 Filter 接口,代码如下:

@Component
public class MyFilterSecurityInterceptor extends AbstractSecurityInterceptor implements Filter { //注入上面编写的两个类
@Autowired
private MySecurityMetadataSource mySecurityMetadataSource; @Autowired
public void setMyAccessDecisionManager(MyAccessDecisionManager myAccessDecisionManager) {
super.setAccessDecisionManager(myAccessDecisionManager);
} @Override
public void init(FilterConfig arg0) throws ServletException {
} @Override
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
FilterInvocation fi = new FilterInvocation(request, response, chain);
invoke(fi);
} public void invoke(FilterInvocation fi) throws IOException, ServletException {
//这里进行权限验证
InterceptorStatusToken token = super.beforeInvocation(fi);
try {
fi.getChain().doFilter(fi.getRequest(), fi.getResponse());
} finally {
super.afterInvocation(token, null);
}
} @Override
public void destroy() {
} @Override
public Class<?> getSecureObjectClass() {
return FilterInvocation.class;
} @Override
public SecurityMetadataSource obtainSecurityMetadataSource() {
return this.mySecurityMetadataSource;
}
}

四、 加入到 security 的过滤器链中

.addFilterBefore(urlFilterSecurityInterceptor,FilterSecurityInterceptor.class)

完成

本篇原创发布于:https://www.tapme.top/blog/detail/2018-08-22-10-38

springboot+security整合(3)自定义鉴权的更多相关文章

  1. springboot+security整合(2)自定义校验

    说明 springboot 版本 2.0.3源码地址:点击跳转 系列 springboot+security 整合(1) springboot+security 整合(2) springboot+se ...

  2. SpringBoot整合SpringSecurityOauth2实现鉴权-动态权限

    写在前面 思考:为什么需要鉴权呢? 系统开发好上线后,API接口会暴露在互联网上会存在一定的安全风险,例如:爬虫.恶意访问等.因此,我们需要对非开放API接口进行用户鉴权,鉴权通过之后再允许调用. 准 ...

  3. springboot+security整合(1)

    说明 springboot 版本 2.0.3源码地址:点击跳转 系列 springboot+security 整合(1) springboot+security 整合(2) springboot+se ...

  4. Shiro(4)默认鉴权与自定义鉴权

    =========默认鉴权======== 过滤链中定义: <!-- 过滤链定义 --> <property name="filterChainDefinitions&qu ...

  5. Spring Cloud注册中心Eureka设置访问权限并自定义鉴权页面

    原文:https://blog.csdn.net/a823007573/article/details/88971496 使用Spring Security实现鉴权 1. 导入Spring Secur ...

  6. 使用SpringSecurity Oauth2.0实现自定义鉴权中心

    Oauth2.0是什么不在赘述,本文主要介绍如何使用SpringSecurity Oauth2.0实现自定义的用户校验 1.鉴权中心服务 首先,列举一下我们需要用到的依赖,本文采用的是数据库保存用户信 ...

  7. 「快学springboot」集成Spring Security实现鉴权功能

    Spring Security介绍 Spring Security是Spring全家桶中的处理身份和权限问题的一员.Spring Security可以根据使用者的需要定制相关的角色身份和身份所具有的权 ...

  8. Spring Security 接口认证鉴权入门实践指南

    目录 前言 SpringBoot 示例 SpringBoot pom.xml SpringBoot application.yml SpringBoot IndexController SpringB ...

  9. springboot oauth 鉴权之——授权码authorization_code鉴权

    近期一直在研究鉴权方面的各种案例,这几天有空,写一波总结及经验. 第一步:什么是 OAuth鉴权 OAuth2是工业标准的授权协议.OAuth2取代了在2006创建的原始OAuthTM协议所做的工作. ...

随机推荐

  1. ubuntu之路——day17.2 RGB图像的卷积、多个filter的输出、单个卷积层的标记方法

    和单层图像的卷积类似,只需要对每一个filter构成的三层立方体上的每一个数字与原图像对应位置的数字相乘相加求和即可. 在这个时候可以分别设置filter的R.G.B三层,可以同时检测纵向或横向边缘, ...

  2. HBase 介绍

    HBase的列族式存储 列族式存储的概念 HBase Table的组成 Table = RowKey + Family + Column + Timestamp + Value 数据存储模式 (Row ...

  3. [转]CSS3 使用 calc() 计算高度 vh px

    1.px 像素,我们在网页布局中一般都是用px. 2.百分比 百分比一般宽泛的讲是相对于父元素,自适应网页布局越来越多,百分比也经常用到了. 3.Viewport    viewport:可视窗口,也 ...

  4. Freemarke

    本文介绍了freemarker的集成.FTL指令.内建函数.运算符等常用操作. 1.为什么要使用网页静态化技术 网页静态化解决方案在实际开发中运用比较多,例如新闻网站,门户网站中的新闻频道或者是文章类 ...

  5. windows下用navicat远程链接虚拟机Linux下MySQL数据库(转)

    原文地址:https://www.cnblogs.com/blogforly/p/5997553.html 今天想用navicat远程连接虚拟机中的MySQL数据库,一直连不上,在网上搜索了一下,发现 ...

  6. git初次登陆使用

    一. 安装git 二. 在当前项目根目录点击鼠标右键,出来下图: 点击进入git命令行界面. 三.初始化项目 git init 四. 添加所有文件到项目中 git add . 五. 尝试提交所有文件 ...

  7. matlab学习笔记10_5 通用字符串操作和比较函数

    一起来学matlab-matlab学习笔记10 10_5 通用字符串操作和比较函数 觉得有用的话,欢迎一起讨论相互学习~Follow Me 参考书籍 <matlab 程序设计与综合应用>张 ...

  8. Nginx - 代理后端通过域名访问

    目录- 前言- Nginx 根据域名反向代理- Nginx proxy_pass 关于 '/' 的作用 1. 前言 接到一个需求,通过nginx 代理互联网上某一个页面,刚开始的时候觉得很简单的,直接 ...

  9. MySQL之SQL语句的使用

    SQL使用 mysql中的基本逻辑对象 mysql有这么几种对象 mysqld--->库---->表---->记录(由行和列组成)一条记录中的一列叫做字段 什么是关系型数据库 表与表 ...

  10. 【视频开发】【CUDA开发】英伟达CUVID硬解,并通过FFmpeg读取文件

    虽然FFmpeg本身有cuvid硬解,但是找不到什么好的资料,英伟达的SDK比较容易懂,参考FFmpeg源码,将NVIDIA VIDEO CODEC SDK的数据获取改为FFmpeg获取,弥补原生SD ...