auth2 如果配置gateway进行访问
时间: 2024-02-01 16:03:50 浏览: 74
springboot整合Oauth2,GateWay实现网关登录授权验证
5星 · 资源好评率100%
如果您使用 Spring Cloud Gateway 来配置 OAuth2 授权和资源服务器,则需要进行以下步骤:
1. 在 Gateway 的 pom.xml 文件中添加以下依赖:
```xml
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-gateway</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-security</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.security</groupId>
<artifactId>spring-security-oauth2-resource-server</artifactId>
</dependency>
```
2. 在 application.yml 或 application.properties 文件中配置 OAuth2 客户端和资源服务器信息,例如:
```yaml
spring:
security:
oauth2:
client:
registration:
your-client-registration-id:
client-id: your-client-id
client-secret: your-client-secret
scope: your-scope
authorization-grant-type: authorization_code
redirect-uri-template: your-redirect-uri-template
client-name: your-client-name
provider:
your-provider-name:
authorization-uri: your-authorization-uri
token-uri: your-token-uri
user-info-uri: your-user-info-uri
user-name-attribute: your-user-name-attribute
resourceserver:
jwt:
issuer-uri: your-issuer-uri
jwk-set-uri: your-jwk-set-uri
```
3. 在 Gateway 配置类中添加 OAuth2 鉴权过滤器,例如:
```java
@Configuration
public class GatewayConfig {
@Bean
public SecurityWebFilterChain securityWebFilterChain(ServerHttpSecurity http) {
http
.authorizeExchange()
.pathMatchers("/oauth2/callback").permitAll()
.anyExchange().authenticated()
.and()
.oauth2Login()
.and()
.oauth2ResourceServer()
.jwt();
return http.build();
}
}
```
这样,您就可以使用 Spring Cloud Gateway 配置 OAuth2 认证和资源服务器了。
阅读全文