Skip to content

Commit

Permalink
优化Swagger支持,完善OAuth2.0配置
Browse files Browse the repository at this point in the history
  • Loading branch information
nnhy committed Nov 2, 2024
1 parent c5f8467 commit 8cfef9c
Show file tree
Hide file tree
Showing 8 changed files with 56 additions and 29 deletions.
4 changes: 2 additions & 2 deletions CubeDemo/CubeDemo.csproj
Original file line number Diff line number Diff line change
Expand Up @@ -5,8 +5,8 @@
<AssemblyTitle>魔方WebApi</AssemblyTitle>
<Description>魔方前后端分离版本的后端WebApi</Description>
<Company>新生命开发团队</Company>
<Copyright>©2002-2023 NewLife</Copyright>
<VersionPrefix>5.5</VersionPrefix>
<Copyright>©2002-2024 NewLife</Copyright>
<VersionPrefix>6.1</VersionPrefix>
<VersionSuffix>$([System.DateTime]::Now.ToString(`yyyy.MMdd`))</VersionSuffix>
<Version>$(VersionPrefix).$(VersionSuffix)</Version>
<FileVersion>$(Version)</FileVersion>
Expand Down
8 changes: 6 additions & 2 deletions NewLife.Cube.Swagger/SwaggerConfigureOptions.cs
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@
using Microsoft.AspNetCore.Mvc.Controllers;
using Microsoft.Extensions.Options;
using Microsoft.OpenApi.Models;
using NewLife.Reflection;
using Swashbuckle.AspNetCore.SwaggerGen;

namespace NewLife.Cube.Swagger;
Expand Down Expand Up @@ -34,10 +35,13 @@ public void Configure(SwaggerGenOptions options)
var area = controller.ControllerTypeInfo.GetCustomAttribute<AreaAttribute>();
if (area != null)
{
var type = area.GetType();
var asm = AssemblyX.Create(type.Assembly);
info = new OpenApiInfo
{
Title = area.GetType().GetDisplayName(),
Description = area.GetType().GetDescription()?.Replace("\n", "<br/>")
Title = type.GetDisplayName(),
Description = type.GetDescription()?.Replace("\n", "<br/>"),
Version = asm.FileVersion,
};
break;
}
Expand Down
22 changes: 17 additions & 5 deletions NewLife.Cube.Swagger/SwaggerService.cs
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@
using Microsoft.Extensions.Options;
using Microsoft.OpenApi.Models;
using NewLife.Cube.Entity;
using NewLife.Reflection;
using Swashbuckle.AspNetCore.SwaggerGen;

namespace NewLife.Cube.Swagger;
Expand All @@ -26,7 +27,8 @@ public static IServiceCollection AddCubeSwagger(this IServiceCollection services
var xml = "NewLife.Cube.xml".GetFullPath();
if (File.Exists(xml)) options.IncludeXmlComments(xml, true);

options.SwaggerDoc("v1", new OpenApiInfo { Title = "第三代魔方", Description = "第三代魔方WebApi接口,用于前后端分离。" });
var asm = AssemblyX.Entry;
options.SwaggerDoc("v1", new OpenApiInfo { Title = "第三代魔方", Description = "第三代魔方WebApi接口,用于前后端分离。", Version = asm.FileVersion });
//options.SwaggerDoc("Basic", new OpenApiInfo { Version = "basic", Title = "基础模块" });
//options.SwaggerDoc("Admin", new OpenApiInfo { Version = "admin", Title = "系统管理" });
//options.SwaggerDoc("Cube", new OpenApiInfo { Version = "cube", Title = "魔方管理" });
Expand All @@ -48,8 +50,8 @@ public static IServiceCollection AddCubeSwagger(this IServiceCollection services
var cfg = oauthConfigs[0];
var flow = new OpenApiOAuthFlow
{
AuthorizationUrl = new Uri(cfg.Server),
TokenUrl = new Uri(!cfg.AccessServer.IsNullOrEmpty() ? cfg.AccessServer : cfg.Server),
AuthorizationUrl = new Uri(cfg.Server + "/authorize"),
TokenUrl = new Uri((!cfg.AccessServer.IsNullOrEmpty() ? cfg.AccessServer : cfg.Server) + "/access_token"),
//Scopes = new Dictionary<String, String>
//{
// { "api1", "Access to API #1" }
Expand All @@ -58,10 +60,17 @@ public static IServiceCollection AddCubeSwagger(this IServiceCollection services
options.AddSecurityDefinition("OAuth2", new OpenApiSecurityScheme
{
Type = SecuritySchemeType.OAuth2,
In = ParameterLocation.Query,
Flows = new OpenApiOAuthFlows { AuthorizationCode = flow }
});

//options.OperationFilter<AuthorizeCheckOperationFilter>();
// 声明一个Scheme,注意下面的Id要和上面AddSecurityDefinition中的参数name一致
var scheme = new OpenApiSecurityScheme()
{
Reference = new OpenApiReference() { Type = ReferenceType.SecurityScheme, Id = "OAuth2" }
};
// 注册全局认证(所有的接口都可以使用认证)
options.AddSecurityRequirement(new OpenApiSecurityRequirement() { [scheme] = [] });
}
else
{
Expand All @@ -72,7 +81,7 @@ public static IServiceCollection AddCubeSwagger(this IServiceCollection services
Name = "Authorization",
In = ParameterLocation.Header,
Type = SecuritySchemeType.Http,
Scheme = "bearer"
Scheme = "Bearer"
});
// 声明一个Scheme,注意下面的Id要和上面AddSecurityDefinition中的参数name一致
var scheme = new OpenApiSecurityScheme()
Expand All @@ -96,6 +105,9 @@ public static IApplicationBuilder UseCubeSwagger(this IApplicationBuilder app)
//app.UseSwaggerUI();
app.UseSwaggerUI(options =>
{
var asm = AssemblyX.Entry;
options.DocumentTitle = !asm.Title.IsNullOrEmpty() ? asm.Title : "魔方Web开发平台";

//options.SwaggerEndpoint("/swagger/Basic/swagger.json", "Basic");
//options.SwaggerEndpoint("/swagger/Admin/swagger.json", "Admin");
//options.SwaggerEndpoint("/swagger/Cube/swagger.json", "Cube");
Expand Down
2 changes: 1 addition & 1 deletion NewLife.Cube/Areas/Admin/AdminAreaRegistration.cs
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@ namespace NewLife.Cube.Areas.Admin;
/// <summary>权限管理区域注册</summary>
[DisplayName("系统管理")]
[Description("""
核心功能:用户、角色、菜单,构成基本权限体系。
核心功能:用户、角色、菜单,构成基本权限体系。
核心配置:基本设置、系统设置、魔方设置、数据中间件。
OAuth功能:OAuth配置微信钉钉等多个第三方SSO登录。
安全功能:审计日志、访问规则,保障系统安全。
Expand Down
2 changes: 1 addition & 1 deletion NewLife.Cube/Controllers/CubeController.cs
Original file line number Diff line number Diff line change
Expand Up @@ -21,7 +21,7 @@ namespace NewLife.Cube.Controllers;
[Description("""
魔方向前端控件提供的一些常用接口,例如用户查询与头像获取等。
""")]
[ApiExplorerSettings(GroupName = "Basic")]
//[ApiExplorerSettings(GroupName = "Cube")]
[Route("[controller]/[action]")]
public class CubeController : ControllerBaseX
{
Expand Down
7 changes: 6 additions & 1 deletion NewLife.Cube/Controllers/SsoController.cs
Original file line number Diff line number Diff line change
Expand Up @@ -53,7 +53,7 @@ namespace NewLife.Cube.Controllers;
魔方支持接入微信钉钉等多个第三方OAuth2.0服务。
魔方自身也可以作为OAuth2.0服务端,支持密码式、凭证式、刷新令牌等多种授权模式。
""")]
[ApiExplorerSettings(GroupName = "Basic")]
//[ApiExplorerSettings(GroupName = "Cube")]
[Route("[controller]/[action]")]
public class SsoController : ControllerBaseX
{
Expand Down Expand Up @@ -479,6 +479,7 @@ public virtual ActionResult Auth2(String id)
/// <returns></returns>
[AllowAnonymous]
[HttpGet]
[HttpPost]
public virtual ActionResult Access_Token(String client_id, String client_secret, String code, String grant_type = null)
{
if (client_id.IsNullOrEmpty()) throw new ArgumentNullException(nameof(client_id));
Expand Down Expand Up @@ -534,6 +535,7 @@ public virtual ActionResult Access_Token(String client_id, String client_secret,
/// <returns></returns>
[AllowAnonymous]
[HttpGet]
[HttpPost]
public new virtual ActionResult Token(String client_id, String client_secret, String username, String password, String refresh_token, String grant_type = null)
{
if (client_id.IsNullOrEmpty()) throw new ArgumentNullException(nameof(client_id));
Expand Down Expand Up @@ -600,6 +602,7 @@ public virtual ActionResult Access_Token(String client_id, String client_secret,
/// <returns></returns>
[AllowAnonymous]
[HttpGet]
[HttpPost]
public virtual ActionResult PasswordToken([FromBody] SsoTokenModel model)
{
if (model.client_id.IsNullOrEmpty()) throw new ArgumentNullException(nameof(model.client_id));
Expand Down Expand Up @@ -689,6 +692,7 @@ public virtual ActionResult UserInfo(String access_token)
/// <returns></returns>
[AllowAnonymous]
[HttpGet]
[HttpPost]
public virtual ActionResult Refresh_Token(String client_id, String grant_type, String refresh_token)
{
if (client_id.IsNullOrEmpty()) throw new ArgumentNullException(nameof(client_id));
Expand Down Expand Up @@ -810,6 +814,7 @@ public ActionResult Verify(String access_token, String redirect_uri)
/// <returns></returns>
[AllowAnonymous]
[HttpGet]
[HttpPost]
public virtual ActionResult UserAuth([FromBody] SsoTokenModel model)
{
var client_id = model.client_id;
Expand Down
30 changes: 13 additions & 17 deletions NewLife.Cube/Web/Models/SsoTokenModel.cs
Original file line number Diff line number Diff line change
@@ -1,24 +1,20 @@
using System;
using System.Runtime.Serialization;
namespace NewLife.Cube.Web.Models;

namespace NewLife.Cube.Web.Models
/// <summary>Sso令牌模型</summary>
public class SsoTokenModel
{
/// <summary>Sso令牌模型</summary>
public class SsoTokenModel
{
/// <summary>应用标识</summary>
public String client_id { get; set; }
/// <summary>应用标识</summary>
public String client_id { get; set; }

/// <summary>应用密钥</summary>
public String client_secret { get; set; }
/// <summary>应用密钥</summary>
public String client_secret { get; set; }

/// <summary>用户名。可以是设备编码等唯一使用者标识</summary>
public String UserName { get; set; }
/// <summary>用户名。可以是设备编码等唯一使用者标识</summary>
public String UserName { get; set; }

/// <summary>密码</summary>
public String Password { get; set; }
/// <summary>密码</summary>
public String Password { get; set; }

/// <summary>授权类型</summary>
public String grant_type { get; set; }
}
/// <summary>授权类型</summary>
public String grant_type { get; set; }
}
10 changes: 10 additions & 0 deletions NewLife.CubeNC/Controllers/SsoController.cs
Original file line number Diff line number Diff line change
Expand Up @@ -476,6 +476,8 @@ public virtual ActionResult Auth2(String id)
/// <param name="grant_type">授权类型</param>
/// <returns></returns>
[AllowAnonymous]
[HttpGet]
[HttpPost]
public virtual ActionResult Access_Token(String client_id, String client_secret, String code, String grant_type = null)
{
if (client_id.IsNullOrEmpty()) throw new ArgumentNullException(nameof(client_id));
Expand Down Expand Up @@ -530,6 +532,8 @@ public virtual ActionResult Access_Token(String client_id, String client_secret,
/// <param name="grant_type">授权类型</param>
/// <returns></returns>
[AllowAnonymous]
[HttpGet]
[HttpPost]
public virtual ActionResult Token(String client_id, String client_secret, String username, String password, String refresh_token, String grant_type = null)
{
if (client_id.IsNullOrEmpty()) throw new ArgumentNullException(nameof(client_id));
Expand Down Expand Up @@ -595,6 +599,8 @@ public virtual ActionResult Token(String client_id, String client_secret, String
/// <param name="model">请求模型</param>
/// <returns></returns>
[AllowAnonymous]
[HttpGet]
[HttpPost]
public virtual ActionResult PasswordToken([FromBody] SsoTokenModel model)
{
if (model.client_id.IsNullOrEmpty()) throw new ArgumentNullException(nameof(model.client_id));
Expand Down Expand Up @@ -682,6 +688,8 @@ public virtual ActionResult UserInfo(String access_token)
/// <param name="refresh_token">刷新令牌</param>
/// <returns></returns>
[AllowAnonymous]
[HttpGet]
[HttpPost]
public virtual ActionResult Refresh_Token(String client_id, String grant_type, String refresh_token)
{
if (client_id.IsNullOrEmpty()) throw new ArgumentNullException(nameof(client_id));
Expand Down Expand Up @@ -799,6 +807,8 @@ public ActionResult Verify(String access_token, String redirect_uri)
/// <param name="model">令牌模型</param>
/// <returns></returns>
[AllowAnonymous]
[HttpGet]
[HttpPost]
public virtual ActionResult UserAuth([FromBody] SsoTokenModel model)
{
var client_id = model.client_id;
Expand Down

0 comments on commit 8cfef9c

Please sign in to comment.