目录

  • 背景说明
  • 准备工作
  • 实施步骤
    • pom.xml文件
    • 参数配置
      • zuul配置
      • oauth2配置
    • 编写WebSecurity类
    • 编写ResourceServer类
    • 测试验证

背景说明

zuul在spring cloud里常用于API网关接入,用于对外提供统一服务接口,为外部访问提供鉴权等安全控制,保护内部各微服务资源。而ory hydra是一个开源的轻量化认证管理中心,支持oauth2规范标准,具体可参考这里。我们通过spring security来实现两者的关联,将zuul作为一个resource server, 让其调用认证中心hydra的oauth2 token校验接口来验证请求是否合法。下面按步骤说明实施过程。

准备工作

首先需在hydra里添加oauth2记录。这里的hydra通过docker-compose安装的,4445是hydra的管理端口。通过如下指令添加一个记录: client_id是id_pkce, 支持PKCE认证模式,所以token-endpoint-auth-method为none。

docker-compose -f quickstart.yml exec hydra \hydra clients create \--endpoint http://127.0.0.1:4445/ \--allowed-cors-origins http://localhost \--id id_pkce \--grant-types authorization_code,refresh_token \--response-types code,id_token \ \--scope openid,offline,first_party \ \--callbacks http://localhost/auth/ \--token-endpoint-auth-method none

实施步骤

pom.xml文件

这里列出关键的几个依赖

 <properties><java.version>1.8</java.version><spring-cloud.version>Hoxton.SR8</spring-cloud.version><maven.compiler.source>1.8</maven.compiler.source><maven.compiler.target>1.8</maven.compiler.target>   </properties><dependencyManagement><dependencies><dependency><groupId>org.springframework.cloud</groupId><artifactId>spring-cloud-dependencies</artifactId><version>${spring-cloud.version}</version><type>pom</type><scope>import</scope></dependency></dependencies></dependencyManagement><dependencies><dependency><groupId>org.springframework.cloud</groupId><artifactId>spring-cloud-starter-netflix-zuul</artifactId></dependency><dependency><groupId>org.springframework.cloud</groupId><artifactId>spring-cloud-starter-oauth2</artifactId></dependency><dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-web</artifactId></dependency><dependencies>

参数配置

分两部分,一个是zuul的路由配置,另一个访问oauth2认证中心hydra所需的参数配置。

zuul配置

这里假设有两个路径转发配置,/api/svc1/开头的转微服务msc-1,/api/svc2/开头的转外部连接服务

zuul:routes:svc1:path: /api/svc1/**service-id: msc-1svc2:path: /api/svc2/**url: http://192.168.0.1:10000/api/

oauth2配置

这里的配置用于连接hydra用。192.168.0.2是hydra验证中心的内网IP,端口5000是管理端口4445的外部映射。为安全起见,hydra的管理端口只能内部访问,不能被外部访问。/oauth2/introspect就是hydra的校验token的restful接口

security:oauth2:client:client-id: id_pkceclient-secret: "{noop}"resource:token-info-uri: http://192.168.0.2:5000/oauth2/introspect

编写WebSecurity类

这里配置所有请求都需经过验证

@Configuration
@EnableWebSecurity
public class SecurityConfiguration extends WebSecurityConfigurerAdapter {@Overrideprotected void configure(HttpSecurity http) throws Exception {// @formatter:offhttp.cors().and().authorizeRequests().anyRequest().authenticated().and().csrf().disable();// @formatter:on}
}

编写ResourceServer类

首先定义类

@Configuration
@EnableResourceServer
@Slf4j
public class ResServerConfig extends ResourceServerConfigurerAdapter{

然后实现访问hydra, 注入前面定义的oauth2参数,通过RemoteTokenServices实现。

    @Value("${security.oauth2.client.client-id}")private String clientId;@Value("${security.oauth2.client.client-secret}")private String clientSecret;@Value("${security.oauth2.resource.token-info-uri}")private String tokenCheckUrl;@AutowiredRemoteTokenServices remoteTokenServices;@Overridepublic void configure(ResourceServerSecurityConfigurer resources) throws Exception {remoteTokenServices.setClientId(clientId);remoteTokenServices.setClientSecret(clientSecret);remoteTokenServices.setCheckTokenEndpointUrl(tokenCheckUrl);resources.tokenServices(remoteTokenServices);}

接着配置哪些请求需走oauth2校验,这里定义所有/api开头的请求都要有scope"first_party"。这是前面在hydra创建的oauth2记录的属性之一。

   @Overridepublic void configure(HttpSecurity http) throws Exception {final String[] urlPattern = {"/api/**"};http.sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS).and().requestMatchers().antMatchers(urlPattern).and().authorizeRequests().antMatchers(urlPattern).access("#oauth2.hasScope('first_party')");}
}

测试验证

  1. 做一个get请求/api/showData,通过RestController实现
    @RequestMapping({"/api/showData","/api/**"})public Object showData(){Map<String,String> map = new HashMap<String,String>();map.put("t1","this is test1");map.put("t2","this is test2");return map;}
  1. 直接请求,会返回401错误

  2. 带错误的Bearer token, 返回401错误

  3. 带正确的Bearer token, 返回200 OK

如何在spring cloud zuul里通过ory hydra进行oauth2认证相关推荐

  1. Spring Cloud Zuul的fallback优化

    如何在Zuul中使用fallback功能 我们在项目中使用Spring cloud zuul的时候,有一种这样的需求,就是当我们的zuul进行路由分发时,如果后端服务没有启动,或者调用超时,这时候我们 ...

  2. spring cloud zuul 原理简介和使用

    一 spring cloud zuul 简介 Spring Cloud Zuul 是 Spring Cloud Netflix 子项目的核心组件之一,可以作为微服务架构中的 API 网关使用,支持动态 ...

  3. 《深入理解 Spring Cloud 与微服务构建》第十章 路由网关 Spring Cloud Zuul

    <深入理解 Spring Cloud 与微服务构建>第十章 路由网关 Spring Cloud Zuul 文章目录 <深入理解 Spring Cloud 与微服务构建>第十章 ...

  4. Spring Cloud——API网关服务:Spring Cloud Zuul

    API网关像是整个微服务框架系统的门面一样,所有的客户端访问都需要经过它来进行调度和过滤.它实现了请求路由.负载均衡.校验过滤等功能.zuul包含了hystrix.ribbon.acturator等重 ...

  5. Zuul spring cloud zuul com.netflix.zuul.exception.ZuulException GENERAL解决方案

    Zuul spring cloud zuul com.netflix.zuul.exception.ZuulException GENERAL解决方案 参考文章: (1)Zuul spring clo ...

  6. Spring Cloud Zuul中使用Swagger汇总API接口文档

    有很多读者问过这样的一个问题: 虽然使用Swagger可以为Spring MVC编写的接口生成了API文档,但是在微服务化之后,这些API文档都离散在各个微服务中,是否有办法将这些接口都整合到一个文档 ...

  7. Spring Cloud -Zuul

    服务网关和zuul 一个角色来充当request的请求入口,处理非业务功能的场所(防刷,协议监控) 要素: 稳定性,高可用 性能.并发性 安全性 扩展性 常用的网关方案 Nginx+Lua(性能极高, ...

  8. Spring Cloud Zuul网关 Filter、熔断、重试、高可用的使用方式

    时间过的很快,写springcloud(十):服务网关zuul初级篇还在半年前,现在已经是2018年了,我们继续探讨Zuul更高级的使用方式. 上篇文章主要介绍了Zuul网关使用模式,以及自动转发机制 ...

  9. 关于Spring Cloud Zuul网管上传文件乱码问题

    Spring Cloud Zuul现在对于上传文件有两种处理方式,一种是用spring mvc,另一种是zuulServlet.spring mvc对文件处理不是很好,会导致乱码问题,zuulServ ...

最新文章

  1. python语言实例-采用python进行编程的实例有哪些?
  2. linux ie 插件目录在哪个文件夹里,Linux下的IE浏览器使用方法[图]
  3. 樊登读书分享ppt_樊登读书精华分享-《分手后,成为更好的自己》
  4. 白话基础之虚拟存储器
  5. java反序列化的原理,java – 反序列化的工作原理?
  6. [置顶] Lucene开发实例(一般企业搜索平台完全够用全程)
  7. 爱上Foobar2000抛弃winamp一周年纪念日
  8. hibernate FetchType理解
  9. (转)金融“核武器”即将引爆整个行业
  10. 通过Expression Tree来扩展MVC中的HtmlHelper 和 UrlHelper
  11. 视频教程-WPS Office轻松办公(文字篇)-Office/WPS
  12. 黑眼圈订单系统_大熊猫黑眼圈订单后台
  13. 中国城市名列表及code
  14. 李岩 太极计算机,《高中体育游戏300例》李岩_孔网
  15. java 夏令时标志_Java里面的夏令时 | 学步园
  16. 已解决:ERROR com.rabbitmq.client.impl.ForgivingExceptionHandler - An unexpected connection driver error
  17. 简单数据类型的转换和条件控制语句(if else)的使用
  18. PS学习--图层混合模式详解
  19. Prometheus(一)——概述、监控体系、生态组件、部署
  20. iPhone 双卡双待时代即将来临?

热门文章

  1. js几种倒计时实现方式
  2. 电脑网页的上网记录怎么查
  3. 【语音之家】AI产业沙龙—京东在AI语音方向的技术探索与实践
  4. rp魔兽那个服务器人最多,魔兽世界怀旧服rp服务器什么意思
  5. 快速格式化 和 磁盘碎片整理
  6. 超实用的后台原型,产品王者的摸鱼技巧都在这里
  7. linux: Resource temporarily unavailable 问题解决
  8. 马云野心终于暴露了,刚刚,阿里无人酒店开业,没有一个服务员…
  9. 怎样隐藏计算机文件,电脑里的文件怎么绝对隐藏起来让别人看不到?
  10. 开机黑屏显示html,电脑开机黑屏怎么办,教您电脑开机黑屏的解决方法