Files
simapi-net/SimApiExtensions.cs
T

237 lines
9.4 KiB
C#
Raw Normal View History

2019-12-23 16:32:06 +08:00
using System;
2020-08-05 15:29:56 +08:00
using SimApi.Helpers;
2019-12-23 16:32:06 +08:00
using Microsoft.AspNetCore.Builder;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.OpenApi.Models;
2020-08-05 15:29:56 +08:00
using SimApi.Middlewares;
2020-12-29 17:18:02 +08:00
using Microsoft.AspNetCore.HttpOverrides;
2021-06-28 05:36:54 +08:00
using Microsoft.Extensions.Logging;
using SimApi.Configs;
2021-06-28 05:36:54 +08:00
using SimApi.Logger;
2019-12-23 16:32:06 +08:00
2020-08-05 15:29:56 +08:00
namespace SimApi
2019-12-23 16:32:06 +08:00
{
/// <summary>
/// 加入系统的扩展信息
/// </summary>
public static class SimApiExtensions
2019-12-23 16:32:06 +08:00
{
2020-02-04 16:05:09 +08:00
//**********快捷添加**************
public static IServiceCollection AddSimApi(this IServiceCollection builder,
Action<SimApiOptions> options = null)
2019-12-23 16:32:06 +08:00
{
var simApiOptions = new SimApiOptions();
options?.Invoke(simApiOptions);
// 是否使用SIMAUTH
if (simApiOptions.EnableSimApiAuth)
2020-12-29 17:18:02 +08:00
{
builder.AddScoped<SimApiAuth>();
}
2021-06-05 14:30:52 +08:00
if (simApiOptions.EnableCors)
{
builder.AddCors(cors => cors.AddPolicy("any",
policy => { policy.AllowAnyHeader().AllowAnyMethod().AllowAnyOrigin(); }));
}
// 使用SimApiDoc
if (simApiOptions.EnableSimApiDoc)
{
var docOptions = simApiOptions.SimApiDocOptions;
builder.AddSwaggerGen(x =>
{
foreach (var group in docOptions.ApiGroups)
{
x.SwaggerDoc(group.Id, new OpenApiInfo {Title = group.Name, Description = group.Description});
}
x.EnableAnnotations();
var haveOauth = false;
var haveSimApiAuth = false;
var oauthFlows = new OpenApiOAuthFlows();
foreach (var auth in docOptions.ApiAuth.Type)
{
switch (auth)
{
case "SimApiAuth":
x.AddSecurityRequirement(new OpenApiSecurityRequirement
{
{
new OpenApiSecurityScheme
{
Reference = new OpenApiReference
{Type = ReferenceType.SecurityScheme, Id = "HeaderToken"}
},
new[] {"readAccess", "writeAccess"}
}
});
haveSimApiAuth = true;
break;
case "ClientCredentials":
oauthFlows.ClientCredentials = new OpenApiOAuthFlow
{
TokenUrl = new Uri(docOptions.ApiAuth.TokenUrl, UriKind.RelativeOrAbsolute),
Scopes = docOptions.ApiAuth.Scopes
};
haveOauth = true;
break;
case "Implicit":
oauthFlows.Implicit = new OpenApiOAuthFlow
{
AuthorizationUrl = new Uri(docOptions.ApiAuth.AuthorizationUrl,
UriKind.RelativeOrAbsolute),
Scopes = docOptions.ApiAuth.Scopes
};
haveOauth = true;
break;
case "AuthorizationCode":
oauthFlows.AuthorizationCode = new OpenApiOAuthFlow
{
TokenUrl = new Uri(docOptions.ApiAuth.TokenUrl, UriKind.RelativeOrAbsolute),
AuthorizationUrl = new Uri(docOptions.ApiAuth.AuthorizationUrl,
UriKind.RelativeOrAbsolute),
Scopes = docOptions.ApiAuth.Scopes
};
haveOauth = true;
break;
2021-06-27 10:59:19 +08:00
case "Password":
oauthFlows.Password = new OpenApiOAuthFlow
{
TokenUrl = new Uri(docOptions.ApiAuth.TokenUrl, UriKind.RelativeOrAbsolute),
Scopes = docOptions.ApiAuth.Scopes
};
haveOauth = true;
break;
}
}
if (haveOauth)
{
x.AddSecurityDefinition("oauth2", new OpenApiSecurityScheme
{
Type = SecuritySchemeType.OAuth2,
Flows = oauthFlows,
Description = docOptions.ApiAuth.Description,
In = ParameterLocation.Header
});
x.AddSecurityRequirement(new OpenApiSecurityRequirement
{
{
new OpenApiSecurityScheme
{
Reference = new OpenApiReference
{Type = ReferenceType.SecurityScheme, Id = "oauth2"}
},
new[] {"SimApiAuth"}
}
});
}
if (haveSimApiAuth)
{
x.AddSecurityDefinition("HeaderToken",
new OpenApiSecurityScheme {Name = "Token", In = ParameterLocation.Header});
}
});
}
// 使用Header转发,应对代理后获取真实ip
if (simApiOptions.EnableForwardHeaders)
{
builder.Configure<ForwardedHeadersOptions>(options =>
{
2021-06-03 15:32:17 +08:00
options.ForwardedHeaders = ForwardedHeaders.All;
options.KnownNetworks.Clear();
options.KnownProxies.Clear();
});
}
if (simApiOptions.EnableLowerUrl)
{
builder.AddRouting(options => options.LowercaseUrls = true);
}
if (simApiOptions.EnableSimApiStorage)
{
2021-06-05 12:07:47 +08:00
builder.AddHttpContextAccessor();
builder.AddSingleton<SimApiStorage>();
}
builder.AddSingleton(simApiOptions);
return builder;
2020-02-04 16:05:09 +08:00
}
/// <summary>
2020-08-23 19:51:37 +08:00
/// 使用所有SimApi自定义中间件
2020-02-04 16:05:09 +08:00
/// </summary>
/// <param name="builder"></param>
/// <returns></returns>
public static IApplicationBuilder UseSimApi(this IApplicationBuilder builder)
2020-02-04 16:05:09 +08:00
{
var options = builder.ApplicationServices.GetService<SimApiOptions>();
2021-06-28 05:36:54 +08:00
if (options.EnableLogger)
{
builder.ApplicationServices.GetService<ILoggerFactory>().AddProvider(new SimApiLoggerProvider());
}
2021-06-28 05:45:29 +08:00
var logger = builder.ApplicationServices.GetService<ILogger<SimApiLogger>>();
2021-06-28 05:36:54 +08:00
2021-06-03 17:16:55 +08:00
if (options.EnableForwardHeaders)
{
2021-06-28 05:36:54 +08:00
logger.LogInformation("开始配置ForwardedHeaders...");
2021-06-03 17:16:55 +08:00
builder.UseForwardedHeaders();
}
2021-06-05 14:30:52 +08:00
if (options.EnableCors)
{
2021-06-28 05:36:54 +08:00
logger.LogInformation("开始配置Cors全部允许...");
2021-06-05 14:30:52 +08:00
builder.UseCors("any");
}
if (options.EnableSimApiAuth)
2019-12-23 16:32:06 +08:00
{
2021-06-28 05:36:54 +08:00
logger.LogInformation("开始配置SimApiAuth...");
builder.UseMiddleware<SimApiAuthMiddleware>();
}
if (options.EnableSimApiDoc)
{
2021-06-28 05:36:54 +08:00
logger.LogInformation("开始配置SimApiDoc...");
var docOptions = options.SimApiDocOptions;
2021-06-03 17:16:55 +08:00
builder.UseSwagger(x => x.RouteTemplate = "/swagger/{documentName}.json").UseSwaggerUI(x =>
2019-12-23 16:32:06 +08:00
{
x.DocumentTitle = docOptions.DocumentTitle;
foreach (var group in docOptions.ApiGroups)
2019-12-23 16:32:06 +08:00
{
x.SwaggerEndpoint($"/swagger/{group.Id}.json", name: group.Name);
2019-12-23 16:32:06 +08:00
}
x.EnableValidator();
x.SupportedSubmitMethods(docOptions.SupportedMethod);
x.DisplayRequestDuration();
2019-12-23 16:32:06 +08:00
});
}
2019-12-23 16:32:06 +08:00
if (options.EnableSimApiException)
2020-03-11 23:27:17 +08:00
{
2021-06-28 05:36:54 +08:00
logger.LogInformation("开始配置SimApiException...");
builder.UseMiddleware<SimApiExceptionMiddleware>();
}
2019-12-23 16:32:06 +08:00
2021-06-03 17:16:55 +08:00
//请求一下检测存储错误
if (options.EnableSimApiStorage)
2019-12-23 16:32:06 +08:00
{
2021-06-28 05:36:54 +08:00
logger.LogInformation("开始配置SimApiStorage...");
2021-06-03 17:16:55 +08:00
builder.ApplicationServices.GetService<SimApiStorage>();
}
2019-12-23 16:32:06 +08:00
2021-06-03 17:16:55 +08:00
if (options.EnableLowerUrl)
{
2021-06-28 05:36:54 +08:00
logger.LogInformation("开始配置使用URL小写...");
2021-06-03 15:35:26 +08:00
}
return builder;
2019-12-23 16:32:06 +08:00
}
}
}