Springdoc Swagger UI集成OAuth2认证

这篇具有很好参考价值的文章主要介绍了Springdoc Swagger UI集成OAuth2认证。希望对大家有所帮助。如果存在错误或未考虑完全的地方,请大家不吝赐教,您也可以点击"举报违法"按钮提交疑问。

引言

之前的文章讲过OAuth2体系,以授权码流程为例(参见下图),
其中资源服务器(Resource Server)作为服务的提供者,
用户在客户端应用完成授权流程后,客户端应用需要携带AccessToken请求资源服务器
也即是要想访问资源服务器就需要提供正确的Authorization: Bearer AccessToken
如此在将资源服务器接入Swagger UI后,是无法直接访问其后端API的,
例如直接访问会返回Http Status 401,除非在Swagger UI中接入正确的AccessToken。
swagger对接oauth2,# springboot,OAuth2.0 & OIDC 1.0,swagger,oauth2,springdoc
接来下结合Springdoc & OpenAPI 3.0介绍3种支持Resource Server接入Swagger UI并支持OAuth2的方式。

注: 关于Springdoc和OpenAPI 3.0的更多说明可参见我之前的文章:
SpringBoot应用生成RESTful API文档 - Swagger 2.0、OAS 3.0、Springfox、Springdoc、Smart-doc

注:
本文Springdoc Swagger UI集成OAuth2认证示例的具体代码可参见:
https://gitee.com/luoex/spring-cloud-demo/tree/develop/api-doc-demo/springdoc-oas3-oauth2
本文使用的OAuth2 AuthServer具体代码可参见:
https://gitee.com/luoex/oauth2-auth-server-oidc/tree/main/samples/oauth2-auth-server-oidc-minimal

方式1:Bearer Token

此种方式较为简单,即直接配置Swagger UI支持自定义Bearer token,具体配置如下:
代码配置:

import io.swagger.v3.oas.annotations.OpenAPIDefinition;
import io.swagger.v3.oas.annotations.enums.SecuritySchemeIn;
import io.swagger.v3.oas.annotations.enums.SecuritySchemeType;
import io.swagger.v3.oas.annotations.info.Info;
import io.swagger.v3.oas.annotations.security.*;
import io.swagger.v3.oas.annotations.servers.Server;


/**
 * OAS 3.0 配置
 *
 * @author luohq
 * @date 2023-02-26
 */
@OpenAPIDefinition(
        info = @Info(
                title = "Springdoc OAS3.0 - OAuth2 Resource Server - RESTful API",
                description = "Springdoc OAS3.0 - OAuth2 Resource Server - RESTful API",
                version = "v1"
        ),
        servers = {@Server(url = "http://springdoc-resource-server:8080")},
        security = @SecurityRequirement(name = "Bearer access_token")
)
@SecurityScheme(
        name = "Bearer access_token",
        type = SecuritySchemeType.HTTP,
        in = SecuritySchemeIn.HEADER,
        scheme = "bearer",
        description = "直接将有效的access_token填入下方,后续该access_token将作为Bearer access_token"
)
public class OpenApiBearerConfig {
}

设置Resource Server的Swagger-UI访问Host为:
http://springdoc-resource-server:8080
启动后访问Swagger UI:
http://springdoc-resource-server:8080/swagger-ui/index.html

注:
本地开发调试需配置本地Host:
127.0.0.1 springdoc-resource-server
后文示例均通过该Host访问示例Swagger UI。

swagger对接oauth2,# springboot,OAuth2.0 & OIDC 1.0,swagger,oauth2,springdoc
点击右侧的Authorize按钮,即可触发Swagger UI的认证流程,
在Bearer Token方式中点击Authorize按钮会弹出如下输入框:
swagger对接oauth2,# springboot,OAuth2.0 & OIDC 1.0,swagger,oauth2,springdoc
在输入框中输入有效的access_token后点击下方的Authorize按钮即可完成,
之后在Swagger UI中点击Try it out -> Execute 发送测试请求时,均会携带请求头:
Authorization: Bearer {your_input_token_value}
如此便可通过Resource Server对access_token的校验,正常获得请求结果。
swagger对接oauth2,# springboot,OAuth2.0 & OIDC 1.0,swagger,oauth2,springdoc

方式2:标准OAuth2授权码流程

此种方式Swagger UI作为OAuth2客户端,通过标准的授权码流程接入,
设置Resource Server的Swagger-UI访问Host为:
http://springdoc-resource-server:8080
Swagger-UI授权码回调地址为:http://{swagger-ui-host}:{port}/swagger-ui/oauth2-redirect.html
即:http://springdoc-resource-server:8080/swagger-ui/oauth2-redirect.html

切记 需在OAuth2 Client注册信息中指定该redirect_uri ,否则由Swagger-UI跳转到OAuth2 授权端点(即登录页)时报错Http 400。
swagger对接oauth2,# springboot,OAuth2.0 & OIDC 1.0,swagger,oauth2,springdoc

代码配置:

import io.swagger.v3.oas.annotations.OpenAPIDefinition;
import io.swagger.v3.oas.annotations.enums.SecuritySchemeType;
import io.swagger.v3.oas.annotations.info.Info;
import io.swagger.v3.oas.annotations.security.*;
import io.swagger.v3.oas.annotations.servers.Server;


/**
 * OAS 3.0 配置
 *
 * @author luohq
 * @date 2023-02-26
 */
@OpenAPIDefinition(
        info = @Info(
                title = "Springdoc OAS3.0 - OAuth2 Resource Server - RESTful API",
                description = "Springdoc OAS3.0 - OAuth2 Resource Server - RESTful API",
                version = "v1"
        ),
        servers = {@Server(url = "http://springdoc-resource-server:8080")},
        security = @SecurityRequirement(name = "OAuth2 Flow", scopes = {"openid", "phone", "email", "profile", "roles"})
)
@SecurityScheme(
        name = "OAuth2 Flow",
        type = SecuritySchemeType.OAUTH2,
        flows = @OAuthFlows(
                authorizationCode = @OAuthFlow(
                        authorizationUrl = "${springdoc.swagger-ui.oauth.authorization-url}",
                        tokenUrl = "${springdoc.swagger-ui.oauth.token-url}",
                        scopes = {
                                //此处需根据Client注册时支持的Scopes进行配置
                                //openid,phone,email,profile,roles
                                @OAuthScope(name = "openid", description = "OpenId Connect"),
                                @OAuthScope(name = "phone", description = "手机号"),
                                @OAuthScope(name = "email", description = "电子邮件"),
                                @OAuthScope(name = "profile", description = "用户身份信息"),
                                @OAuthScope(name = "roles", description = "角色"),
                        }
                )
        ),
        description = "OAuth2授权码认证流程,<br/>根据需要选择下方的Scopes。"
)
public class OpenApiOAuth2Config {
}

application.yaml配置:

# springdoc配置
springdoc:
  swagger-ui:
    oauth:
      # 接入的Client凭证信息
      client-id: luo-oauth2-client1
      client-secret: luo-oauth2-client1-secret
      # Swagger UI上默认选中的scopes
      scopes:
        - openid
        - phone
        - email
        - profile
      #  OAuth2端点(绝对路径)
      authorization-url: http://oauth2-server:9000/oauth2/authorize
      token-url: http://oauth2-server:9000/oauth2/token

启动后访问Swagger UI:
http://springdoc-resource-server:8080/swagger-ui/index.html
点击右侧的Authorize按钮,即可触发Swagger UI的OAuth2 授权码认证流程,
swagger对接oauth2,# springboot,OAuth2.0 &amp; OIDC 1.0,swagger,oauth2,springdoc
如上图,弹框中已默认填入application.yaml中配置好的client_id和client_secret,
同时设置了Scopes的默认选中,可根据需求调整Scopes的选择,
之后点击Authorize按钮,即在新弹出的Tab页中重定向到OAuth2认证服务器端AuthServer,
swagger对接oauth2,# springboot,OAuth2.0 &amp; OIDC 1.0,swagger,oauth2,springdoc
完成登录后,AuthServer登录页会重定到Swagger UI的授权码回调处理页面:
http://springdoc-resource-server:8080/swagger-ui/oauth2-redirect.html
Swagger UI的授权码回调处理页获取授权码,并自动关闭AuthServer Tab页,
然后交由原Swagger UI页面通过授权码换取access_token:

注:
Swagger UI在浏览器端直接调用OAuth2 AuthServer的Token端点,由于两者不在同一域名下,直接调用会报CORS错误
所以需在AuthServer端设置允许Origin: http://springdoc-resource-server:8080跨域访问。

swagger对接oauth2,# springboot,OAuth2.0 &amp; OIDC 1.0,swagger,oauth2,springdoc

之后在Swagger UI中点击Try it out -> Execute 发送测试请求时,均会携带请求头:
Authorization: Bearer {access_token}
如此便可通过Resource Server对access_token的校验,正常获得请求结果。
swagger对接oauth2,# springboot,OAuth2.0 &amp; OIDC 1.0,swagger,oauth2,springdoc

方式3:集成OIDC发现端点

此种方式Swagger UI同样作为OAuth2客户端,只不过通过OIDC发现端点获取支持的OAuth2授权流程、端点URL及权限范围Scopes等,
例如测试使用的OAuth2 AuthServer提供OIDC发现端点:
http://oauth2-server:9000/.well-known/openid-configuration
其响应结果如下:

{
    //发布URI
    "issuer": "http://oauth2-server:9000",
    //授权端点
    "authorization_endpoint": "http://oauth2-server:9000/oauth2/authorize",
    //Token端点
    "token_endpoint": "http://oauth2-server:9000/oauth2/token",
    //Token端点认证方法
    "token_endpoint_auth_methods_supported": [
        "client_secret_basic",
        "client_secret_post",
        "none"
    ],
     //支持的授权流程
    "grant_types_supported": [
        "authorization_code",
        "client_credentials",
        "refresh_token"
    ],
     //支持的授权范围
    "scopes_supported": [
        "openid"
    ],

    "jwks_uri": "http://oauth2-server:9000/oauth2/jwks",
    "userinfo_endpoint": "http://oauth2-server:9000/userinfo",
    "response_types_supported": [
        "code"
    ],   
    "subject_types_supported": [
        "public"
    ],
    "id_token_signing_alg_values_supported": [
        "RS256"
    ],   
    "end_session_endpoint": "http://oauth2-server:9000/logout"
}

如此可以识别出该AuthServer支持的授权流程包括:

  • authorization_code
  • client_credentials
  • refresh_token

相关端点URL为:

  • 授权端点 - “authorization_endpoint”: “http://oauth2-server:9000/oauth2/authorize”
  • Token端点 - “token_endpoint”: “http://oauth2-server:9000/oauth2/token”

支持的权限范围Scopes:

  • openid

具体集成的代码配置:

import io.swagger.v3.oas.annotations.OpenAPIDefinition;
import io.swagger.v3.oas.annotations.enums.SecuritySchemeType;
import io.swagger.v3.oas.annotations.info.Info;
import io.swagger.v3.oas.annotations.security.SecurityRequirement;
import io.swagger.v3.oas.annotations.security.SecurityScheme;
import io.swagger.v3.oas.annotations.servers.Server;


/**
 * OAS 3.0 配置
 *
 * @author luohq
 * @date 2023-02-26
 */
@OpenAPIDefinition(
        info = @Info(
                title = "Springdoc OAS3.0 - OAuth2 Resource Server - RESTful API",
                description = "Springdoc OAS3.0 - OAuth2 Resource Server - RESTful API",
                version = "v1"
        ),
        servers = {@Server(url = "http://springdoc-resource-server:8080")},
        security = @SecurityRequirement(name = "OIDC Flow", scopes = {"openid"})
)
@SecurityScheme(
        name = "OIDC Flow",
        type = SecuritySchemeType.OPENIDCONNECT,
        openIdConnectUrl = "${springdoc.swagger-ui.oauth.oidc-url}",
        description = "OpenIdConnect认证流程,<br/>由OIDC发现端点自动识别支持的授权流程,<br/>根据需要选择下方的Scopes。"
)
public class OpenApiOidcConfig {
}

application.yaml配置:

# springdoc配置
springdoc:
  swagger-ui:
    oauth:
      # 接入的Client凭证信息
      client-id: luo-oauth2-client1
      client-secret: luo-oauth2-client1-secret
      # Swagger UI上默认选中的scopes
      scopes:
        - openid
      #  OIDC发现端点(绝对路径)
      oidc-url: http://oauth2-server:9000/.well-known/openid-configuration

注:
Swagger UI集成OIDC同样需要配置OAuth2 client-id和client-secret,
但仅需配置OIDC发现端点URl即可,无需同集成OAuth2模式时配置authorization-url、token-url及需要支持的Scopes,
Swagger UI可通过解析OIDC发现端点自动识别出OAuth2 AuthServer支持的授权流程、端点URL、权限范围Scopes等。

设置Resource Server的Swagger-UI访问Host为:
http://springdoc-resource-server:8080
Swagger-UI授权码回调地址为:http://{swagger-ui-host}:{port}/swagger-ui/oauth2-redirect.html
即:http://springdoc-resource-server:8080/swagger-ui/oauth2-redirect.html

同集成OAuth2模式时一样,切记 需在OAuth2 Client注册信息中指定该redirect_uri
否则由Swagger-UI跳转到OAuth2 授权端点(即登录页)时报错Http 400。

启动后访问Swagger UI:
http://springdoc-resource-server:8080/swagger-ui/index.html
点击右侧的Authorize按钮,即可触发Swagger UI的OIDC认证流程(识别出3种,选择第一条授权码流程即可),
授权码认证流程同之前方式2中流程一样,可参见之前方式2中的介绍。
swagger对接oauth2,# springboot,OAuth2.0 &amp; OIDC 1.0,swagger,oauth2,springdoc

扩展:同时支持多种认证方式

Swagger UI支持同时集成多种认证方式,例如同时支持上面提到的3中方式,具体集成如下。

代码配置:

import io.swagger.v3.oas.annotations.OpenAPIDefinition;
import io.swagger.v3.oas.annotations.enums.SecuritySchemeIn;
import io.swagger.v3.oas.annotations.enums.SecuritySchemeType;
import io.swagger.v3.oas.annotations.info.Info;
import io.swagger.v3.oas.annotations.security.*;
import io.swagger.v3.oas.annotations.servers.Server;


/**
 * OAS 3.0 配置
 *
 * @author luohq
 * @date 2023-02-26
 */
@OpenAPIDefinition(
        info = @Info(
                title = "Springdoc OAS3.0 - OAuth2 Resource Server - RESTful API",
                description = "Springdoc OAS3.0 - OAuth2 Resource Server - RESTful API",
                version = "v1"
        ),
        servers = {@Server(url = "http://springdoc-resource-server:8080")},
        //集成多种认证模式
        security = {
                @SecurityRequirement(name = "Bearer access_token"),
                @SecurityRequirement(name = "OAuth2 Flow", scopes = {"openid", "phone", "email", "profile", "roles"}),
                @SecurityRequirement(name = "OIDC Flow", scopes = {"openid"})
        }
)
@SecurityScheme(
        name = "Bearer access_token",
        type = SecuritySchemeType.HTTP,
        in = SecuritySchemeIn.HEADER,
        scheme = "bearer",
        description = "直接将有效的access_token填入下方,后续该access_token将作为Bearer access_token"
)
@SecurityScheme(
        name = "OAuth2 Flow",
        type = SecuritySchemeType.OAUTH2,
        flows = @OAuthFlows(
                authorizationCode = @OAuthFlow(
                        authorizationUrl = "${springdoc.swagger-ui.oauth.authorization-url}",
                        tokenUrl = "${springdoc.swagger-ui.oauth.token-url}",
                        scopes = {
                                //此处需根据Client注册时支持的Scopes进行配置
                                //openid,phone,email,profile,roles
                                @OAuthScope(name = "openid", description = "OpenId Connect"),
                                @OAuthScope(name = "phone", description = "手机号"),
                                @OAuthScope(name = "email", description = "电子邮件"),
                                @OAuthScope(name = "profile", description = "用户身份信息"),
                                @OAuthScope(name = "roles", description = "角色"),
                        }
                )
        ),
        description = "OAuth2授权码认证流程,<br/>根据需要选择下方的Scopes。"
)
@SecurityScheme(
        name = "OIDC Flow",
        type = SecuritySchemeType.OPENIDCONNECT,
        openIdConnectUrl = "${springdoc.swagger-ui.oauth.oidc-url}",
        description = "OpenIdConnect认证流程,<br/>由OIDC发现端点自动识别支持的授权流程,<br/>根据需要选择下方的Scopes。"
)
public class OpenApiComboConfig {
}

application.yaml配置:

# springdoc配置
springdoc:
  swagger-ui:
    oauth:
      # 接入的Client凭证信息
      client-id: luo-oauth2-client1
      client-secret: luo-oauth2-client1-secret
      # Swagger UI上默认选中的scopes
      scopes:
        - openid
        - phone
        - email
        - profile
      #  OAuth2端点(绝对路径)
      authorization-url: http://oauth2-server:9000/oauth2/authorize
      token-url: http://oauth2-server:9000/oauth2/token
      #  OIDC发现端点(绝对路径)
      oidc-url: http://oauth2-server:9000/.well-known/openid-configuration

参考:
https://swagger.io/docs/specification/authentication/openid-connect-discovery/
https://gitee.com/mirrors_OAI/OpenAPI-Specification/blob/3.0.1/versions/3.0.1.md#security-scheme-object
https://springdoc.org/
https://github.com/springdoc文章来源地址https://www.toymoban.com/news/detail-785873.html

到了这里,关于Springdoc Swagger UI集成OAuth2认证的文章就介绍完了。如果您还想了解更多内容,请在右上角搜索TOY模板网以前的文章或继续浏览下面的相关文章,希望大家以后多多支持TOY模板网!

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处: 如若内容造成侵权/违法违规/事实不符,请点击违法举报进行投诉反馈,一经查实,立即删除!

领支付宝红包赞助服务器费用

相关文章

  • 【Spring Boot】SpringBoot 2.6.6 集成 SpringDoc 1.6.9 生成swagger接口文档

    【Spring Boot】SpringBoot 2.6.6 集成 SpringDoc 1.6.9 生成swagger接口文档

    之前常用的SpringFox在2020年停止更新了,新项目集成SpringFox出来一堆问题,所以打算使用更活跃的SpringDoc,这里简单介绍一下我这边SpringBoot2.6.6集成SpringDoc1.6.9的demo。 官网链接 maven为例: 代码如下(示例): 默认路径: UI界面 http://localhost:9527/swagger-ui/index.html json界面 http:/

    2024年02月09日
    浏览(14)
  • Springboot 2.7 集成 Swagger 增强版接口框架 Knife4j 4.3 + springdoc OpenApi 3.0

    Springboot 2.7 集成 Swagger 增强版接口框架 Knife4j 4.3 + springdoc OpenApi 3.0

    Swagger 作为一款服务端接口文档自动生成框架,早已深入人心,并且在市场上得到了广泛的应用。然而,Swagger 3.0 也就是 OpenApi 3.0 规范发布之后便停止了更新维护,出道就是巅峰。Knife4j 作为 Swagger 的增强版,是对 Swagger UI 做了优化,同时还有很多增强的功能。伴随着 Swagge

    2024年02月08日
    浏览(18)
  • Spring Boot 3.x 引入springdoc-openapi (内置Swagger UI、webmvc-api)

    Spring Boot 3.x 引入springdoc-openapi (内置Swagger UI、webmvc-api)

    接触的原因 因开发自己的项目时,写接口文档很繁琐,查到后端都在用 swagger 等接口工具来记录接口文档,于是学习了一下,本文记录个人配置过程,有问题欢迎指正交流😁 Swagger: Swagger是一种Rest API的表示方式,它是标准的、语言无关的工具,这种表示方式不仅人可读,

    2024年04月27日
    浏览(10)
  • Spring Authorization Server入门 (八) Spring Boot引入Security OAuth2 Client对接认证服务

    Spring Authorization Server入门 (八) Spring Boot引入Security OAuth2 Client对接认证服务

    在之前的文章中实现了一个认证服务,并且添加了一些自定义的内容,现在暂时没想到认证服务的新内容,本篇文章就先写一下客户端对接的吧,水一篇。 当用户通过客户端去访问一个受限的资源时,客户端会检测是否有登录信息,没有登录信息会重定向至认证服务器去请求

    2024年02月21日
    浏览(17)
  • swagger 3.0.0 集成 springboot 2.6+ 生成doc.html 和swagger-ui

    swagger 3.0.0 集成 springboot 2.6+ 生成doc.html 和swagger-ui

    1.项目中引入pom.xml依赖 特别说明: doc.html模式 swagger-bootstrap-ui只支持Swagger 2 knife4j是swagger-bootstrap-ui的升级版,支持Swagger 3。 2.创建Swagger2Config配置类 3.启动类输出文档地址 项目运行后 控制台输出log见下图 点击任意文档链接都可以进入对应的文档

    2024年02月12日
    浏览(12)
  • 关于Springboot集成swagger2出现的swagger-resouces和ui请求的404问题

    关于Springboot集成swagger2出现的swagger-resouces和ui请求的404问题

    本项目集成的是增强版的Swagger文档,使用的增强版的UI com.github.xiaoymin 按照上面的配置,在本地测试效果是正常的 在红色标记的地方是正常显示的,但是按照这个配置打war包部署到服务器或者本地的tomcat中就会出现404的现象。 出现上面的这种情况时,看过很多网上的帖子说

    2024年04月17日
    浏览(13)
  • Swagger UI及其集成到Spring Boot应用中

    作者:禅与计算机程序设计艺术 Swagger 是一款开源、功能丰富的 API 概述文档工具。它能够帮助我们快速、清晰地定义、结构化和展示我们的 API,同时也支持多种开发语言,如 Java、JavaScript、Python等。在 Spring Boot 中,使用 Swagger 可以极大方便 API 的测试、调试以及提供给其他

    2024年02月04日
    浏览(7)
  • 后端项目开发:集成接口文档(swagger-ui)

    swagger集成文档具有功能丰富、及时更新、整合简单,内嵌于应用的特点。 由于后台管理和前台接口均需要接口文档,所以在工具包构建BaseSwaggerConfig基类。 1.引入依赖 2.需要添加Swagger配置类。 将需要配置的字段提取出来,单独作为一类 前台接口和后台管理的包的配置,只需

    2024年02月11日
    浏览(10)
  • SpringBoot集成Swagger-Bootstrap-UI,页面更清爽!(1)

    SpringBoot集成Swagger-Bootstrap-UI,页面更清爽!(1)

    springfox-swagger2 2.9.2 com.github.xiaoymin swagger-bootstrap-ui 1.9.6 二、添加配置类 package com.blog.tutorial.config; import com.git 需要zi料+ 绿色徽【vip1024b】 hub.xiaoymin.swaggerbootstrapui.annotations.EnableSwaggerBootstrapUI; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configur

    2024年04月27日
    浏览(8)
  • Springboot3.0整合swagger,废弃Springfox改用Springdoc

    Springboot3.0整合swagger,废弃Springfox改用Springdoc

    Automated JSON API documentation for API\\\'s built with Spring 官网地址:springfox.io springdoc-openapi java library helps to automate the generation of API documentation using spring boot projects. 官网地址:https://springdoc.org/v2/ 注意 :使用的是V2版本,这个版本支持springboot3.0 之前springboot3.0之前我用的都是Springfox来集

    2023年04月09日
    浏览(12)

觉得文章有用就打赏一下文章作者

支付宝扫一扫打赏

博客赞助

微信扫一扫打赏

请作者喝杯咖啡吧~博客赞助

支付宝扫一扫领取红包,优惠每天领

二维码1

领取红包

二维码2

领红包