使用spring cloud 26版本、spring securiry56版本、oauth2、spring cloud gateway实现基于ouath2的统一认证网关
- 添加依赖
在pom文件中添加以下依赖:
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-gateway</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-oauth2</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.security</groupId>
<artifactId>spring-security-oauth2-resource-server</artifactId>
<version>${spring-security-oauth2.version}</version>
</dependency>
- 配置网关
在配置文件中添加以下配置:
spring:
cloud:
gateway:
routes:
- id: service-a
uri: lb://service-a
predicates:
- Path=/service-a/**
filters:
- TokenRelay
- id: service-b
uri: lb://service-b
predicates:
- Path=/service-b/**
filters:
- TokenRelay
security:
oauth2:
resourceserver:
jwt:
issuer-uri: http://localhost:8080/auth/realms/demo
其中,routes配置了要代理的服务,predicates配置了路由规则,filters配置了过滤器。
在这里,我们使用了TokenRelay过滤器来转发令牌。
- 配置认证服务器
在认证服务器的配置文件中添加以下配置:
security:
oauth2:
client:
registration:
service-a:
client-id: service-a
client-secret: secret
scope: read,write
redirect-uri: '{baseUrl}/login/oauth2/code/{registrationId}'
authorization-grant-type: authorization_code
client-name: Service A
service-b:
client-id: service-b
client-secret: secret
scope: read,write
redirect-uri: '{baseUrl}/login/oauth2/code/{registrationId}'
authorization-grant-type: authorization_code
client-name: Service B
provider:
keycloak:
issuer-uri: http://localhost:8080/auth/realms/demo
jwk-set-uri: http://localhost:8080/auth/realms/demo/protocol/openid-connect/certs
其中,registration配置了客户端信息,provider配置了认证服务器的相关信息。
- 配置资源服务器
在资源服务器的配置文件中添加以下配置:
security:
oauth2:
resourceserver:
jwt:
jwk-set-uri: http://localhost:8080/auth/realms/demo/protocol/openid-connect/certs
其中,jwk-set-uri指定了认证服务器的公钥地址。
- 测试
启动认证服务器、服务A、服务B和网关,访问http://localhost:8080/service-a/hello和http://localhost:8080/service-b/hello,如果没有认证,会跳转到认证服务器的登录页面。登录之后,再次访问服务,就能够成功访问了。
原文地址: http://www.cveoy.top/t/topic/b0CK 著作权归作者所有。请勿转载和采集!