Merge pull request #256 from kiebor/master

Updated OpenAPI definition to add JWT bearer and authentication.
This commit is contained in:
Haiping 2024-01-16 09:07:23 -06:00 committed by GitHub
commit a6761fc90c
No known key found for this signature in database
GPG key ID: 4AEE18F83AFDEB23
2 changed files with 42 additions and 7 deletions

View file

@ -5,6 +5,8 @@ using Microsoft.AspNetCore.Builder;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.Hosting;
using Microsoft.IdentityModel.Tokens;
using Microsoft.OpenApi.Models;
using Swashbuckle.AspNetCore.SwaggerGen;
using System.IdentityModel.Tokens.Jwt;
namespace BotSharp.OpenAPI;
@ -18,8 +20,8 @@ public static class BotSharpOpenApiExtensions
/// <param name="services"></param>
/// <param name="config"></param>
/// <returns></returns>
public static IServiceCollection AddBotSharpOpenAPI(this IServiceCollection services,
IConfiguration config,
public static IServiceCollection AddBotSharpOpenAPI(this IServiceCollection services,
IConfiguration config,
string[] origins,
IHostEnvironment env,
bool enableValidation)
@ -62,7 +64,31 @@ public static class BotSharpOpenApiExtensions
// Learn more about configuring Swagger/OpenAPI at https://aka.ms/aspnetcore/swashbuckle
services.AddEndpointsApiExplorer();
services.AddSwaggerGen();
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>()
}
});
}
);
services.AddHttpContextAccessor();
@ -94,6 +120,7 @@ public static class BotSharpOpenApiExtensions
app.UseCors(policy);
app.UseSwagger();
if (env.IsDevelopment())
{
app.UseSwaggerUI();
@ -103,7 +130,7 @@ public static class BotSharpOpenApiExtensions
app.UseAuthentication();
app.UseRouting();
app.UseAuthorization();
app.UseEndpoints(
@ -150,3 +177,4 @@ public static class BotSharpOpenApiExtensions
return app;
}
}

View file

@ -1,3 +1,5 @@
using System.ComponentModel.DataAnnotations;
namespace BotSharp.OpenAPI.Controllers;
[Authorize]
@ -12,10 +14,15 @@ public class UserController : ControllerBase
[AllowAnonymous]
[HttpPost("/token")]
public async Task<ActionResult<Token>> GetToken()
public async Task<ActionResult<Token>> GetToken([FromHeader(Name = "Authorization")][Required] string authcode)
{
var authcode = Request.Headers["Authorization"].ToString();
var token = await _userService.GetToken(authcode.Split(' ')[1]);
if (authcode.Contains(' '))
{
authcode = authcode.Split(' ')[1];
}
var token = await _userService.GetToken(authcode);
if (token == null)
{
return Unauthorized();