BotSharp/src/Infrastructure/BotSharp.OpenAPI/BotSharpOpenApiExtensions.cs

181 lines
5.5 KiB
C#
Raw Normal View History

2024-01-11 00:57:30 +00:00
using BotSharp.Abstraction.Messaging.JsonConverters;
using BotSharp.Core.Users.Services;
using Microsoft.AspNetCore.Authentication.JwtBearer;
2024-01-10 14:18:59 +00:00
using Microsoft.AspNetCore.Builder;
2024-01-11 00:57:30 +00:00
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.Hosting;
using Microsoft.IdentityModel.Tokens;
using Microsoft.OpenApi.Models;
using Swashbuckle.AspNetCore.SwaggerGen;
2024-01-11 00:57:30 +00:00
using System.IdentityModel.Tokens.Jwt;
2023-12-19 13:16:43 +00:00
namespace BotSharp.OpenAPI;
public static class BotSharpOpenApiExtensions
{
2024-01-11 00:57:30 +00:00
private static string policy = "BotSharpCorsPolicy";
/// <summary>
/// Add Swagger/OpenAPI
/// </summary>
/// <param name="services"></param>
/// <param name="config"></param>
/// <returns></returns>
public static IServiceCollection AddBotSharpOpenAPI(this IServiceCollection services,
IConfiguration config,
2024-01-11 00:57:30 +00:00
string[] origins,
IHostEnvironment env,
bool enableValidation)
{
services.AddScoped<IUserIdentity, UserIdentity>();
// Add bearer authentication
services.AddAuthentication(options =>
{
options.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme;
options.DefaultChallengeScheme = JwtBearerDefaults.AuthenticationScheme;
options.DefaultScheme = JwtBearerDefaults.AuthenticationScheme;
}).AddJwtBearer(o =>
{
o.TokenValidationParameters = new TokenValidationParameters
{
ValidIssuer = config["Jwt:Issuer"],
ValidAudience = config["Jwt:Audience"],
IssuerSigningKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(config["Jwt:Key"])),
ValidateIssuer = enableValidation,
ValidateAudience = enableValidation,
2024-01-11 04:16:13 +00:00
ValidateLifetime = enableValidation && !env.IsDevelopment(),
2024-01-11 00:57:30 +00:00
ValidateIssuerSigningKey = enableValidation
};
if (!enableValidation)
{
o.TokenValidationParameters.SignatureValidator = (string token, TokenValidationParameters parameters) =>
new JwtSecurityToken(token);
}
});
// Add services to the container.
services.AddControllers()
.AddJsonOptions(options =>
{
options.JsonSerializerOptions.Converters.Add(new RichContentJsonConverter());
options.JsonSerializerOptions.Converters.Add(new TemplateMessageJsonConverter());
});
// Learn more about configuring Swagger/OpenAPI at https://aka.ms/aspnetcore/swashbuckle
services.AddEndpointsApiExplorer();
services.AddSwaggerGen(
c =>
{
c.AddSecurityDefinition("Bearer", new OpenApiSecurityScheme
{
In = ParameterLocation.Header,
Description = "Please insert JWT with Bearer into field",
Name = "Authorization",
Type = SecuritySchemeType.ApiKey
});
c.AddSecurityRequirement(new OpenApiSecurityRequirement {
{
new OpenApiSecurityScheme
{
Reference = new OpenApiReference
{
Type = ReferenceType.SecurityScheme,
Id = "Bearer"
}
},
Array.Empty<string>()
}
});
}
);
2024-01-11 00:57:30 +00:00
services.AddHttpContextAccessor();
services.AddCors(options =>
{
options.AddPolicy(policy,
builder => builder.WithOrigins(origins)
.AllowAnyMethod()
.AllowAnyHeader()
.AllowCredentials());
});
return services;
}
2024-01-10 14:18:59 +00:00
/// <summary>
/// Use Swagger/OpenAPI
/// </summary>
/// <param name="services"></param>
/// <param name="config"></param>
/// <returns></returns>
2024-01-11 00:57:30 +00:00
public static IApplicationBuilder UseBotSharpOpenAPI(this IApplicationBuilder app, IHostEnvironment env)
2023-12-19 13:16:43 +00:00
{
2024-01-10 14:18:59 +00:00
if (app == null)
{
throw new ArgumentNullException(nameof(app));
}
2024-01-11 00:57:30 +00:00
app.UseCors(policy);
2024-01-10 14:18:59 +00:00
app.UseSwagger();
2024-01-11 00:57:30 +00:00
if (env.IsDevelopment())
2024-01-10 14:18:59 +00:00
{
app.UseSwaggerUI();
2024-01-11 00:57:30 +00:00
app.UseDeveloperExceptionPage();
2024-01-10 14:18:59 +00:00
}
2024-01-11 00:57:30 +00:00
app.UseAuthentication();
app.UseRouting();
2024-01-11 00:57:30 +00:00
app.UseAuthorization();
app.UseEndpoints(
endpoints =>
{
endpoints.MapDefaultControllerRoute();
});
2024-01-10 14:18:59 +00:00
return app;
}
2023-12-19 13:16:43 +00:00
2024-01-10 14:18:59 +00:00
/// <summary>
/// Host BotSharp UI built in adapter-static
/// </summary>
/// <param name="app"></param>
/// <returns></returns>
/// <exception cref="ArgumentNullException"></exception>
public static IApplicationBuilder UseBotSharpUI(this IApplicationBuilder app, bool isDevelopment = false)
{
if (app == null)
{
throw new ArgumentNullException(nameof(app));
}
2023-12-19 13:16:43 +00:00
2024-01-10 14:18:59 +00:00
// app.UseFileServer();
app.UseDefaultFiles();
app.UseStaticFiles();
2024-01-11 00:57:30 +00:00
app.UseEndpoints(
endpoints =>
{
// For SPA static file routing
endpoints.MapFallbackToFile("/index.html");
});
2024-01-10 14:18:59 +00:00
app.UseSpa(config =>
{
if (isDevelopment)
{
config.UseProxyToSpaDevelopmentServer("http://localhost:5015");
}
});
2023-12-19 13:16:43 +00:00
2024-01-10 14:18:59 +00:00
return app;
2023-12-19 13:16:43 +00:00
}
}