1. 引入依赖

在pom.xml文件中引入以下依赖:

<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>
</dependency>

<dependency>
    <groupId>org.springframework.security</groupId>
    <artifactId>spring-security-jwt</artifactId>
</dependency>
  1. 配置网关

在application.yml中配置网关的路由和端口等信息,例如:

server:
  port: 8080

spring:
  cloud:
    gateway:
      discovery:
        locator:
          enabled: true
      routes:
        - id: auth-service
          uri: lb://auth-service
          predicates:
            - Path=/oauth/**
          filters:
            - TokenRelay
        - id: user-service
          uri: lb://user-service
          predicates:
            - Path=/api/**
          filters:
            - TokenRelay

其中,auth-service和user-service分别是认证服务和用户服务的服务名,lb表示使用负载均衡。

  1. 配置OAuth2

配置OAuth2的认证服务器和资源服务器,例如:

spring:
  security:
    oauth2:
      client:
        registration:
          auth-client:
            client-id: client
            client-secret: secret
            scope: read,write
            provider: auth-server
            redirect-uri: "{baseUrl}/login/oauth2/code/{registrationId}"
            authorization-grant-type: authorization_code
        provider:
          auth-server:
            token-uri: http://localhost:8081/oauth/token
            authorization-uri: http://localhost:8081/oauth/authorize
            user-info-uri: http://localhost:8081/user/me
            user-name-attribute: name
      resource:
        jwt:
          jwk-set-uri: http://localhost:8081/.well-known/jwks.json

其中,auth-client是客户端的注册信息,client-id和client-secret是客户端的ID和密钥,scope是客户端的访问权限,provider是认证服务器的名称,redirect-uri是回调地址,authorization-grant-type是授权类型。

provider中配置认证服务器的信息,包括token-uri、authorization-uri和user-info-uri等。

resource中配置资源服务器的信息,包括jwk-set-uri等。

  1. 配置安全

在SecurityConfig中配置安全,例如:

@Configuration
@EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter {

    private final CustomOAuth2UserService customOAuth2UserService;

    public SecurityConfig(CustomOAuth2UserService customOAuth2UserService) {
        this.customOAuth2UserService = customOAuth2UserService;
    }

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http.authorizeRequests()
                .antMatchers("/login/**", "/oauth/**", "/logout/**")
                .permitAll()
                .anyRequest()
                .authenticated()
                .and()
                .oauth2Login()
                .userInfoEndpoint()
                .userService(customOAuth2UserService)
                .and()
                .successHandler((request, response, authentication) -> response.sendRedirect("/"));
    }

    @Bean
    public TokenRelayGatewayFilterFactory tokenRelayGatewayFilterFactory() {
        return new TokenRelayGatewayFilterFactory();
    }
}

其中,configure方法配置了请求的安全策略,permitAll表示不需要认证即可访问的路径,authenticated表示需要认证的路径。

oauth2Login配置OAuth2登录,userService配置自定义的用户服务。

successHandler配置成功登录后的处理,这里是重定向到首页。

  1. 启动应用

在启动认证服务和用户服务后,启动网关,访问http://localhost:8080/oauth/authorize即可进行OAuth2认证,访问http://localhost:8080/api/user/1即可获取用户信息。

使用以下版本spring cloud 26、spring securiry56、oauth2、spring cloud gateway实现基于ouath2的统一认证网关

原文地址: http://www.cveoy.top/t/topic/b0CB 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录