介绍
Spring-Cloud-Gatewway
Spring Cloud Gateway是基于Spring Boot 2.x,Spring WebFlux和Project Reactor构建的。结果,当您使用Spring Cloud Gateway时,许多您熟悉的同步库(例如,Spring Data和Spring Security)和模式可能不适用。如果您不熟悉这些项目,建议您在使用Spring Cloud Gateway之前先阅读它们的文档以熟悉一些新概念。
Spring-Security
Spring Security是一个提供身份验证,授权和保护以防止常见攻击的框架。凭借对命令式和响应式应用程序的一流支持,它是用于保护基于Spring的应用程序的事实上的标准。
Spring-Webflux
Spring框架中包含的原始Web框架Spring Web MVC是专门为Servlet API和Servlet容器而构建的。响应式堆栈Web框架Spring WebFlux在稍后的5.0版中添加。它是完全无阻塞的,支持 Reactive Streams背压,并在Netty,Undertow和Servlet 3.1+容器等服务器上运行。
这两个Web框架都反映了其源模块的名称(spring-webmvc和 spring-webflux),并在Spring Framework中并存。每个模块都是可选的。应用程序可以使用一个模块,也可以使用两个模块,在某些情况下,也可以使用两个模块,例如,带有react的Spring MVC控制器WebClient
。
注意
由于Web容器不同,在Gateway项目中使用的WebFlux,是不能和Spring-Web混合使用的。
Spring MVC和 WebFlux 的区别:
编码
项目环境版本
- Spring-Cloud:2020.0.1
- Spring-Boot: 2.4.3
gradle 依赖
1 | java复制代码dependencies { |
Spring-Security配置
spring security设置要采用响应式配置,基于WebFlux中WebFilter实现,与Spring MVC的Security是通过Servlet的Filter实现类似,也是一系列filter组成的过滤链。
Reactor与传统MVC配置对应:
webflux | mvc | 作用 |
---|---|---|
@EnableWebFluxSecurity | @EnableWebSecurity | 开启security配置 |
ServerAuthenticationSuccessHandler | AuthenticationSuccessHandler | 登录成功Handler |
ServerAuthenticationFailureHandler | AuthenticationFailureHandler | 登陆失败Handler |
ReactiveAuthorizationManager | AuthorizationManager | 认证管理 |
ServerSecurityContextRepository | SecurityContextHolder | 认证信息存储管理 |
ReactiveUserDetailsService | UserDetailsService | 用户登录 |
ReactiveAuthorizationManager | AccessDecisionManager | 鉴权管理 |
ServerAuthenticationEntryPoint | AuthenticationEntryPoint | 未认证Handler |
ServerAccessDeniedHandler | AccessDeniedHandler | 鉴权失败Handler |
1. Security核心配置
1 | java复制代码package com.pluto.gateway.security; |
2.用户认证
1 | java复制代码package com.pluto.gateway.security; |
1 | java复制代码package com.pluto.gateway.security; |
3.1 自定义登录成功Handler
1 | java复制代码package com.pluto.gateway.security; |
3.2 自定义登录失败Handler
1 | java复制代码package com.pluto.gateway.security; |
3.3 自定义未认证Handler
1 | java复制代码package com.pluto.gateway.security; |
3.4 自定义鉴权失败Handler
1 | java复制代码package com.pluto.gateway.security; |
4.自定义JWT Token认证管理
1 | java复制代码package com.pluto.gateway.security; |
1 | java复制代码package com.pluto.gateway.security; |
5.自定义鉴权管理
1 | java复制代码package com.pluto.gateway.security; |
Github仓库地址(记得切换到dev-1.0.0分支)
欢迎各位热爱编程的小伙伴一起交流进步,记得点个收藏哦!
本文转载自: 掘金