gateway+auth2给个springboot案例代码
时间: 2023-12-27 16:02:37 浏览: 149
基于Springboot+VUE的谷歌验证码生成器+源代码+文档说明
这里提供一个基于 Spring Boot 的 Gateway + OAuth2 的示例代码,代码中使用了 Spring Security OAuth2 和 Spring Cloud Gateway,实现了基于 Access Token 的鉴权和路由转发。具体代码如下:
1. 添加依赖
```xml
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-security</artifactId>
</dependency>
<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>
```
2. 添加配置
```yaml
spring:
security:
oauth2:
client:
registration:
my-client:
client-id: my-client-id
client-secret: my-client-secret
scope: read,write
redirect-uri: "{baseUrl}/login/oauth2/code/{registrationId}"
authorization-grant-type: authorization_code
client-name: "My Client"
provider:
my-auth-server:
authorization-uri: http://localhost:8080/oauth/authorize
token-uri: http://localhost:8080/oauth/token
user-info-uri: http://localhost:8080/userinfo
user-name-attribute: name
server:
port: 8081
spring:
cloud:
gateway:
routes:
- id: resource
uri: http://localhost:8082
predicates:
- Path=/resource/**
filters:
- TokenRelay=
```
3. 添加安全配置
```java
@Configuration
@EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter {
@Override
protected void configure(HttpSecurity http) throws Exception {
http.authorizeRequests()
.antMatchers("/login/**", "/logout/**", "/webjars/**").permitAll()
.anyRequest().authenticated()
.and()
.oauth2Login()
.and()
.logout().logoutSuccessUrl("/");
}
@Bean
public SecurityWebFilterChain securityWebFilterChain(ServerHttpSecurity http) {
return http.authorizeExchange()
.pathMatchers("/actuator/**").permitAll()
.anyExchange().authenticated()
.and()
.oauth2Login()
.and()
.build();
}
}
```
4. 启动类添加注解
```java
@SpringBootApplication
@EnableDiscoveryClient
@EnableOAuth2Sso
public class GatewayApplication {
public static void main(String[] args) {
SpringApplication.run(GatewayApplication.class, args);
}
}
```
这个示例代码中,我们通过配置 OAuth2 客户端和认证服务器,实现了基于 Access Token 的鉴权。同时,我们还配置了路由规则和过滤器,将请求转发到相应的服务中。需要注意的是,在实际应用中,我们还需要对 Access Token 进行签名验证和防伪处理,以提高系统的安全性和可靠性。
阅读全文