SpringCloud Alibaba二十五 | 网关Restful接口拦截

简介: SpringCloud Alibaba二十五 | 网关Restful接口拦截

前言


之前在 集成RBAC授权 的文章中提到了SpringCloud可以「基于路径匹配器授权」在网关层进行用户权限校验,这种方式的实现原理是Springcloud Gateway接受到请求后根据 ReactiveAuthorizationManager#check(Mono<Authentication> authenticationMono, AuthorizationContext authorizationContext) 方法基于 AntPathMatcher校验当前访问的URL是否在用户拥有的权限URL中,如果能匹配上则说明拥有访问权限并放行到后端服务,否则提示用户无访问权限。

具体实现方式在上面文章中有阐述,如果有不清楚的可以再次查阅。 文章地址:

http://javadaily.cn/articles/2020/08/07/1596772909329.html

不过之前的实现方式有个问题,就是不支持restful风格的url路径。

例如一个微服务有如下API

GET     /v1/pb/user

POST   /v1/pb/user

PUT    /v1/pb/user

这样在网关通过 request.getURI().getPath()方法获取到用户请求路径的时候都是同一个地址,给一个用户授予 /v1/pb/user权限后他就拥有了 GETPUTPOST三种不同权限,很显然这样不能满足精细权限控制。本章内容我们就来解决这个Restful接口拦截的问题,使其能支持精细化的权限控制。


场景演示


我们看下实际的案例,演示下这种场景。在 account-service模块下增加一个博客用户管理功能,有如下的接口方法:

接口URL HTTP方法 接口说明
/blog/user POST 保存用户
/blog/user/{id} GET 查询用户
/blog/user/{id} DELETE 删除用户
/blog/user/{id} PUT 更新用户信息

然后我们在 sys_permission表中添加2个用户权限,再将其授予给用户角色

在网关层的校验方法中可以看到已经增加了2个权限

由于DELETE 和 PUT对应的权限路径都是 /blog/user/{id},这样就是当给用户授予了查询权限后此用户也拥有了删除和更新的权限。


解决方案


看到这里大部分同学应该想到了,要想实现Restful风格的精细化权限管理单单通过URL路径是不行的,需要搭配Method一起使用。

最关键的点就是「需要给权限表加上方法字段,然后在网关校验的时候即判断请求路径又匹配请求方法。」 实现步骤如下:

  • 修改权限表,新增方法字段

  • loadUserByUsername()方法构建用户权限的时候将权限对应的Method也拼接在权限上,关键代码如下:
@Override
public UserDetails loadUserByUsername(String userName) throws UsernameNotFoundException {
 //获取本地用户
 SysUser sysUser = sysUserMapper.selectByUserName(userName);
 if(sysUser != null){
  //获取当前用户的所有角色
  List<SysRole> roleList = sysRoleService.listRolesByUserId(sysUser.getId());
  sysUser.setRoles(roleList.stream().map(SysRole::getRoleCode).collect(Collectors.toList()));
  List<Integer> roleIds = roleList.stream().map(SysRole::getId).collect(Collectors.toList());
  //获取所有角色的权限
  List<SysPermission> permissionList = sysPermissionService.listPermissionsByRoles(roleIds);
  //拼接method
  List<String> permissionUrlList = permissionList.stream()
                    .map(item -> "["+item.getMethod()+"]"+item.getUrl())
                    .collect(Collectors.toList());
  sysUser.setPermissions(permissionUrlList);
  //构建oauth2的用户
  return buildUserDetails(sysUser);
 }else{
  throw  new UsernameNotFoundException("用户["+userName+"]不存在");
 }
}

通过上面的代码构建的用户权限如下:

[GET]/account-service/blog/user/{id}

[POST]/account-service/blog/user

可以通过代码调试查看:

  • 权限校验方法AccessManager#check(),校验[MEHOTD]RequestPath 格式
@Override
public Mono<AuthorizationDecision> check(Mono<Authentication> authenticationMono, AuthorizationContext authorizationContext) {
 ServerWebExchange exchange = authorizationContext.getExchange();
 ServerHttpRequest request = exchange.getRequest();
 //请求资源
 String requestPath = request.getURI().getPath();
 //拼接method
 String methodPath = "["+request.getMethod()+"]" + requestPath;
 // 1. 对应跨域的预检请求直接放行
 if(request.getMethod() == HttpMethod.OPTIONS){
  return Mono.just(new AuthorizationDecision(true));
 }
 // 是否直接放行
 if (permitAll(requestPath)) {
  return Mono.just(new AuthorizationDecision(true));
 }
 return authenticationMono.map(auth -> new AuthorizationDecision(checkAuthorities(auth, methodPath)))
   .defaultIfEmpty(new AuthorizationDecision(false));
}

校验方法 checkAuthorities()

private boolean checkAuthorities(Authentication auth, String requestPath) {
 if(auth instanceof OAuth2Authentication){
  OAuth2Authentication authentication = (OAuth2Authentication) auth;
  String clientId = authentication.getOAuth2Request().getClientId();
  log.info("clientId is {}",clientId);
  //用户的权限集合
  Collection<? extends GrantedAuthority> authorities = auth.getAuthorities();
  return authorities.stream()
    .map(GrantedAuthority::getAuthority)
    //ROLE_开头的为角色,需要过滤掉
    .filter(item -> !item.startsWith(CloudConstant.ROLE_PREFIX))
    .anyMatch(permission -> ANT_PATH_MATCHER.match(permission, requestPath));
 }
 return true;
}


  • 这样当请求Delete方法时就会提示没有权限

这里还有另外一种方案,实现的原理跟上面差不多,只简单提一下。

首先还是得在权限表中新增METHOD字段,这是必须的。

然后项目中使用的权限类是 SimpleGrantedAuthority,这个只能存储一个权限字段,我们可以自定义一个权限实体类,让其可以存储url 和 method。

@Data
public class MethodGrantedAuthority implements GrantedAuthority {
    private String method;
    private String url;
    public MethodGrantedAuthority(String method, String url){
        this.method = method;
        this.url = url;
    }
    @Override
    public String getAuthority() {
        return "["+method+"]" + url;
    }
}

UserDetailServiceImpl中构建用户权限时使用自定义的 MethodGrantedAuthority

网关层校验的方法还是需要跟上面一样,既校验Method 又 校验 URL。

以上就解决了在网关层校验Restful风格的用户权限校验,希望对你有所帮助!

目录
相关文章
|
2天前
|
算法 NoSQL API
SpringCloud&Gateway网关限流
SpringCloud&Gateway网关限流
42 7
|
2天前
|
负载均衡 Java 网络架构
在SpringCloud2023中快速集成SpringCloudGateway网关
本文主要简单介绍SpringCloud2023实战中SpringCoudGateway的搭建。后续的文章将会介绍在微服务中使用熔断Sentinel、鉴权OAuth2、SSO等技术。
40 2
在SpringCloud2023中快速集成SpringCloudGateway网关
|
2天前
|
JSON Go 数据格式
golang学习7,glang的web的restful接口结构体传参
golang学习7,glang的web的restful接口结构体传参
|
2天前
|
JSON Go 数据格式
golang学习6,glang的web的restful接口传参
golang学习6,glang的web的restful接口传参
|
2天前
|
JSON Go 数据格式
golang学习5,glang的web的restful接口
golang学习5,glang的web的restful接口
|
2天前
|
前端开发 API 网络架构
RESTful接口与http协议状态表述
该文介绍了RESTful风格API的好处和设计原则。RESTful API以资源为中心,通过HTTP方法(GET, POST, PUT, DELETE)表示操作,利用状态码反馈操作结果。它简化了客户端与服务端的交互,提供了一种通用规范,减少沟通成本。设计要点包括:URI描述资源,HTTP方法体现操作,使用标准HTTP状态码,GET不改变数据,使用复数名词,支持复杂资源关系,可选实现HATEOAS,以及接口版本管理。
|
2天前
|
NoSQL Java API
java一行代码实现RESTFul接口
Spring Data REST是构建在Spring Data之上的库,可自动将repository转换为REST服务,支持JPA、MongoDB、Neo4j、GemFire和Cassandra。无需手动创建Service和Controller层。要开始,需配置JPA数据源,创建实体类和Repository接口。快速实现REST接口,只需引入spring-boot-starter-data-rest Maven依赖,并在Repository接口上添加@RepositoryRestResource注解。
|
2天前
|
Java API Nacos
第十二章 Spring Cloud Alibaba Sentinel
第十二章 Spring Cloud Alibaba Sentinel
29 0
|
2天前
|
存储 前端开发 Java
第十一章 Spring Cloud Alibaba nacos配置中心
第十一章 Spring Cloud Alibaba nacos配置中心
28 0
|
2天前
|
消息中间件 SpringCloudAlibaba Java
第十章 SpringCloud Alibaba 之 Nacos discovery
第十章 SpringCloud Alibaba 之 Nacos discovery
10 0