SpringBoot3集成Spring Authorization Server和Spring Cloud Gateway实现网关统一认证

1. 概述

在微服务开发过程中,通常都会使用Spring Cloud Gateway构建统一的API网关,在访问微服务之前都会先校验访问者是否有权限访问资源,实现方式有很多,这里主要介绍Spring Cloud Gateway集成OAuth2.1如何实现网关统一认证。
Spring Cloud Gateway在认证过程中既可以作为OAuth Client,也可以作为OAuth Resource Server
作为OAuth Client流程如下:
oauth client
作为OAuth Resource Server流程如下:
oauth resource server
本文主要以基于OAuth Client实现,会涉及到三个微服务,一个认证中心服务,一个网关Client服务,一个后台资源服务

2. 搭建认证中心

认证中心的搭建可以参考SpringBoot3集成Spring Authorization Server搭建服务认证中心,不同的是在application.yml中配置如下属性:

server:
  port: 9000
spring:
  security:
    oauth2:
      authorizationserver:
        client:
          client-server-oidc:
            registration:
              client-id: client-server
              client-secret: '{noop}secret'
              client-authentication-methods:
                - client_secret_basic
              authorization-grant-types:
                - authorization_code
                - refresh_token
                - client_credentials
              redirect-uris:
                - http://127.0.0.1:8010/login/oauth2/code/client-server-oidc
              scopes:
                - openid
                - profile
              client-name: client-server
            require-authorization-consent: true

3. 搭建后台资源服务

3.1. 引入核心依赖

<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-security</artifactId>
</dependency>
<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-oauth2-resource-server</artifactId>
</dependency>

3.2. 编写application.yml

server:
  port: 8000
spring:
  security:
    oauth2:
      resourceserver:
        jwt:
          issuer-uri: http://127.0.0.1:9000

3.3. 编写ResourceServerConfig

@Configuration
@EnableWebSecurity
@EnableMethodSecurity(jsr250Enabled = true, securedEnabled = true)
public class ResourceServerConfig {

    @Bean
    SecurityFilterChain securityFilterChain(HttpSecurity http) throws Exception {
        http.authorizeHttpRequests((authorize) -> authorize.anyRequest().authenticated())
                .oauth2ResourceServer((oauth2Resource) -> oauth2Resource.jwt(Customizer.withDefaults()));
        return http.build();
    }
}

3.4. 编写ResourceController

编写一个接口用于网关调用

@RestController
public class ResourceController {

    @GetMapping(value = "/resources")
    public String[] getResources() {
        return new String[] {"Resource 1", "Resource 2", "Resource 3"};
    }
}

4. 搭建Gateway Client

4.1. 引入核心依赖

<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.boot</groupId>
    <artifactId>spring-boot-starter-oauth2-client</artifactId>
</dependency>
<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-oauth2-resource-server</artifactId>
</dependency>

4.2. 编写application.yml

server:
  port: 8010
spring:
  cloud:
    gateway:
      default-filters:
        - TokenRelay=
      routes:
        - id: backend_resource_route
          uri: http://127.0.0.1:8000
          predicates:
            - Path=/resources/**
  security:
    oauth2:
      resourceserver:
        jwt:
          issuer-uri: http://127.0.0.1:9000
      client:
        provider:
          oauth-server:
            issuer-uri: http://127.0.0.1:9000
            user-info-uri: ${spring.security.oauth2.client.provider.oauth-server.issuer-uri}/user
            authorization-uri: ${spring.security.oauth2.client.provider.oauth-server.issuer-uri}/oauth2/authorize
            token-uri: ${spring.security.oauth2.client.provider.oauth-server.issuer-uri}/oauth2/token
        registration:
          client-server-oidc:
            provider: oauth-server
            client-id: client-server
            client-secret: secret
            client-name: client-server-oidc
            authorization-grant-type: authorization_code
            redirect-uri: http://127.0.0.1:8010/login/oauth2/code/{registrationId}
            scope:
              - profile
              - openid

4.3. 编写WebSecurityConfig

@Configuration
@EnableWebFluxSecurity
@EnableReactiveMethodSecurity
public class WebSecurityConfig {

    @Bean
    SecurityWebFilterChain defaultSecurityWebFilterChain(ServerHttpSecurity http) {
        http.authorizeExchange((authorize) -> authorize.anyExchange().authenticated());
        http.oauth2Login(Customizer.withDefaults());
        http.oauth2ResourceServer((oauth2Resource) -> oauth2Resource.jwt(Customizer.withDefaults()));
        http.csrf((csrf) -> csrf.disable());
        http.cors((cors) -> cors.disable());
        return http.build();
    }
}

5. 测试验证

依次启动认证中心服务,后台资源服务和网关Client服务,在浏览器输入http://127.0.0.1:8010/resources,会进入登录页面,输入用户名和密码admin/123456,授权服务后,页面会返回后台资源服务接口返回的数据
后台资源

  • 22
    点赞
  • 13
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
目标检测(Object Detection)是计算机视觉领域的一个核心问题,其主要任务是找出图像中所有感兴趣的目标(物体),并确定它们的类别和位置。以下是对目标检测的详细阐述: 一、基本概念 目标检测的任务是解决“在哪里?是什么?”的问题,即定位出图像中目标的位置并识别出目标的类别。由于各类物体具有不同的外观、形状和姿态,加上成像时光照、遮挡等因素的干扰,目标检测一直是计算机视觉领域最具挑战性的任务之一。 二、核心问题 目标检测涉及以下几个核心问题: 分类问题:判断图像中的目标属于哪个类别。 定位问题:确定目标在图像中的具体位置。 大小问题:目标可能具有不同的大小。 形状问题:目标可能具有不同的形状。 三、算法分类 基于深度学习的目标检测算法主要分为两大类: Two-stage算法:先进行区域生成(Region Proposal),生成有可能包含待检物体的预选框(Region Proposal),再通过卷积神经网络进行样本分类。常见的Two-stage算法包括R-CNN、Fast R-CNN、Faster R-CNN等。 One-stage算法:不用生成区域提议,直接在网络中提取特征来预测物体分类和位置。常见的One-stage算法包括YOLO系列(YOLOv1、YOLOv2、YOLOv3、YOLOv4、YOLOv5等)、SSD和RetinaNet等。 四、算法原理 以YOLO系列为例,YOLO将目标检测视为回归问题,将输入图像一次性划分为多个区域,直接在输出层预测边界框和类别概率。YOLO采用卷积网络来提取特征,使用全连接层来得到预测值。其网络结构通常包含多个卷积层和全连接层,通过卷积层提取图像特征,通过全连接层输出预测结果。 五、应用领域 目标检测技术已经广泛应用于各个领域,为人们的生活带来了极大的便利。以下是一些主要的应用领域: 安全监控:在商场、银行
Spring Cloud Gateway是一个基于Spring Boot 2.x的API网关,可以作为微服务架构中的统一入口,提供路由、转发、负载均衡、限流、降级、统一认证和鉴权等功能。在实现统一认证和鉴权时,可以结合Spring Security和JWT来实现。 具体实现步骤如下: 1. 引入Spring Security和JWT的依赖 在Spring Cloud Gateway的pom.xml文件中,引入Spring Security和JWT的依赖: ``` <dependency> <groupId>org.springframework.security</groupId> <artifactId>spring-security-web</artifactId> <version>${spring-security.version}</version> </dependency> <dependency> <groupId>org.springframework.security</groupId> <artifactId>spring-security-config</artifactId> <version>${spring-security.version}</version> </dependency> <dependency> <groupId>io.jsonwebtoken</groupId> <artifactId>jjwt</artifactId> <version>${jjwt.version}</version> </dependency> ``` 2. 配置Spring Security 在Spring Cloud Gateway的配置类中,配置Spring Security: ``` @Configuration @EnableWebFluxSecurity public class SecurityConfig { @Autowired private JwtAuthenticationManager jwtAuthenticationManager; @Bean public SecurityWebFilterChain securityWebFilterChain(ServerHttpSecurity http) { return http.csrf().disable() .authorizeExchange() .pathMatchers("/login").permitAll() .anyExchange().authenticated() .and() .addFilterAt(new JwtAuthenticationFilter(jwtAuthenticationManager), SecurityWebFiltersOrder.AUTHENTICATION) .build(); } } ``` 在上面的配置中,首先禁用了CSRF防护,然后配置了登录接口不需要认证,其它接口都需要认证。最后添加了一个JWT认证过滤器。 3. 配置JWT 在Spring Cloud Gateway的配置类中,配置JWT: ``` @Configuration public class JwtConfig { @Value("${jwt.secret}") private String secret; @Value("${jwt.expiration}") private Long expiration; @Bean public JwtAuthenticationManager jwtAuthenticationManager() { return new JwtAuthenticationManager(secret); } @Bean public JwtTokenGenerator jwtTokenGenerator() { return new JwtTokenGenerator(secret, expiration); } } ``` 在上面的配置中,配置了JWT的密钥和过期时间,并创建了JWT的管理器和生成器。 4. 实现登录接口 实现登录接口,生成JWT并返回给客户端: ``` @RestController public class LoginController { @Autowired private JwtTokenGenerator jwtTokenGenerator; @PostMapping("/login") public Mono<ResponseEntity<Map<String, String>>> login(@RequestBody LoginRequest loginRequest) { // 验证用户名和密码 if (validateUsernameAndPassword(loginRequest)) { // 生成JWT String token = jwtTokenGenerator.generateToken(loginRequest.getUsername()); // 返回JWT Map<String, String> responseBody = new HashMap<>(); responseBody.put("token", token); return Mono.just(ResponseEntity.ok(responseBody)); } else { return Mono.just(ResponseEntity.status(HttpStatus.UNAUTHORIZED).build()); } } private boolean validateUsernameAndPassword(LoginRequest loginRequest) { // 验证用户名和密码逻辑 } } ``` 在上面的代码中,先验证用户名和密码是否正确,如果正确则生成JWT并返回给客户端,否则返回401未授权状态码。 5. 实现JWT认证过滤器 实现JWT认证过滤器,从请求头中获取JWT并验证: ``` public class JwtAuthenticationFilter extends AuthenticationWebFilter { public JwtAuthenticationFilter(JwtAuthenticationManager jwtAuthenticationManager) { super(jwtAuthenticationManager); } @Override protected Mono<Void> onAuthSuccess(Authentication authentication, ServerWebExchange exchange) { return super.onAuthSuccess(authentication, exchange); } @Override protected Mono<Void> onAuthFailure(AuthenticationException e, ServerWebExchange exchange) { return super.onAuthFailure(e, exchange); } @Override public Mono<Void> filter(ServerWebExchange exchange, AuthenticationFilterChain chain) { String token = extractToken(exchange.getRequest().getHeaders().getFirst("Authorization")); if (StringUtils.isEmpty(token)) { return chain.filter(exchange); } else { JwtAuthenticationToken jwtAuthenticationToken = new JwtAuthenticationToken(token); return super.filter(exchange, chain) .subscriberContext(ReactiveSecurityContextHolder.withAuthentication(jwtAuthenticationToken)); } } private String extractToken(String header) { // 从Authorization头中提取JWT } } ``` 在上面的代码中,先从请求头中提取JWT,如果JWT为空则直接调用下一个过滤器,否则创建JwtAuthenticationToken并将其设置到SecurityContext中。 6. 实现JWT认证管理器 实现JWT认证管理器,验证JWT是否正确: ``` public class JwtAuthenticationManager implements ReactiveAuthenticationManager { private final String secret; public JwtAuthenticationManager(String secret) { this.secret = secret; } @Override public Mono<Authentication> authenticate(Authentication authentication) { String token = authentication.getCredentials().toString(); try { Jws<Claims> claimsJws = Jwts.parser().setSigningKey(secret).parseClaimsJws(token); String username = claimsJws.getBody().getSubject(); return Mono.just(new JwtAuthenticationToken(username, token)); } catch (JwtException e) { return Mono.error(e); } } } ``` 在上面的代码中,使用JWT解析器解析JWT,并验证签名和过期时间,如果验证通过则创建JwtAuthenticationToken。 7. 实现JWT认证令牌 实现JWT认证令牌: ``` public class JwtAuthenticationToken extends AbstractAuthenticationToken { private final String token; private final String username; public JwtAuthenticationToken(String token) { super(Collections.emptyList()); this.token = token; this.username = null; } public JwtAuthenticationToken(String username, String token) { super(Collections.emptyList()); this.token = token; this.username = username; setAuthenticated(true); } @Override public Object getCredentials() { return token; } @Override public Object getPrincipal() { return username; } } ``` 在上面的代码中,实现了AbstractAuthenticationToken的两个抽象方法,并添加了一个token和username属性。 8. 配置路由规则 最后,配置路由规则,启用Spring Cloud Gateway: ``` @Configuration public class GatewayConfig { @Autowired private JwtTokenGenerator jwtTokenGenerator; @Bean public RouteLocator customRouteLocator(RouteLocatorBuilder builder) { return builder.routes() .route("login", r -> r.path("/login") .uri("http://localhost:8080/login")) .route("hello", r -> r.path("/hello") .filters(f -> f.requestHeader("Authorization", "Bearer " + jwtTokenGenerator.generateToken("user"))) .uri("http://localhost:8081/hello")) .build(); } } ``` 在上面的配置中,配置了两个路由规则,一个是登录接口,另一个是hello接口,hello接口需要通过JWT认证才能访问。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值