Авторизация через Keycloack
This commit is contained in:
parent
4d24eb9445
commit
e5ffd42fb3
@ -1,9 +1,11 @@
|
||||
using Microsoft.AspNetCore.Authorization;
|
||||
using Microsoft.AspNetCore.Mvc;
|
||||
using Persistence.Repositories;
|
||||
using Persistence.Repository.Data;
|
||||
|
||||
namespace Persistence.API.Controllers;
|
||||
[ApiController]
|
||||
[Authorize]
|
||||
[Route("api/[controller]")]
|
||||
public class DataSaubController : TimeSeriesController<DataSaubDto>
|
||||
{
|
||||
|
@ -1,9 +1,11 @@
|
||||
using Microsoft.AspNetCore.Authorization;
|
||||
using Microsoft.AspNetCore.Mvc;
|
||||
using Persistence.Models;
|
||||
using Persistence.Repositories;
|
||||
|
||||
namespace Persistence.API.Controllers;
|
||||
[ApiController]
|
||||
[Authorize]
|
||||
[Route("api/[controller]")]
|
||||
public class TimeSeriesController<TDto> : ControllerBase, ITimeSeriesDataApi<TDto>
|
||||
where TDto : class, ITimeSeriesAbstractDto, new()
|
||||
@ -27,10 +29,8 @@ public class TimeSeriesController<TDto> : ControllerBase, ITimeSeriesDataApi<TDt
|
||||
[HttpGet("datesRange")]
|
||||
public async Task<IActionResult> GetDatesRangeAsync(CancellationToken token)
|
||||
{
|
||||
//var result = await this.timeSeriesDataCashedRepository.GetDatesRangeAsync(token);
|
||||
//return Ok(result);
|
||||
|
||||
return null;
|
||||
var result = await this.timeSeriesDataRepository.GetDatesRangeAsync(token);
|
||||
return Ok(result);
|
||||
}
|
||||
|
||||
[HttpPost]
|
||||
|
88
Persistence.API/DependencyInjection.cs
Normal file
88
Persistence.API/DependencyInjection.cs
Normal file
@ -0,0 +1,88 @@
|
||||
using Microsoft.AspNetCore.Authentication.JwtBearer;
|
||||
using Microsoft.IdentityModel.Tokens;
|
||||
using Microsoft.OpenApi.Any;
|
||||
using Microsoft.OpenApi.Models;
|
||||
using System.Text.Json.Nodes;
|
||||
|
||||
namespace Persistence.API;
|
||||
|
||||
public static class DependencyInjection
|
||||
{
|
||||
public static void AddSwagger(this IServiceCollection services, IConfiguration configuration)
|
||||
{
|
||||
services.AddSwaggerGen(c =>
|
||||
{
|
||||
c.MapType<TimeSpan>(() => new OpenApiSchema { Type = "string", Example = new OpenApiString("0.00:00:00") });
|
||||
c.MapType<DateOnly>(() => new OpenApiSchema { Type = "string", Format = "date" });
|
||||
c.MapType<JsonValue>(() => new OpenApiSchema
|
||||
{
|
||||
AnyOf = new OpenApiSchema[]
|
||||
{
|
||||
new OpenApiSchema {Type = "string", Format = "string" },
|
||||
new OpenApiSchema {Type = "number", Format = "int32" },
|
||||
new OpenApiSchema {Type = "number", Format = "float" },
|
||||
}
|
||||
});
|
||||
|
||||
c.CustomOperationIds(e =>
|
||||
{
|
||||
return $"{e.ActionDescriptor.RouteValues["action"]}";
|
||||
});
|
||||
|
||||
c.SwaggerDoc("v1", new OpenApiInfo { Title = "Persistence web api", Version = "v1" });
|
||||
c.AddSecurityDefinition("Keycloack", new OpenApiSecurityScheme
|
||||
{
|
||||
Description = @"JWT Authorization header using the Bearer scheme. Enter 'Bearer' [space] and then your token in the text input below. Example: 'Bearer 12345abcdef'",
|
||||
Name = "Authorization",
|
||||
In = ParameterLocation.Header,
|
||||
Type = SecuritySchemeType.OAuth2,
|
||||
Flows = new OpenApiOAuthFlows
|
||||
{
|
||||
Implicit = new OpenApiOAuthFlow
|
||||
{
|
||||
AuthorizationUrl = new Uri(configuration["Authentication:AuthorizationUrl"]),
|
||||
}
|
||||
}
|
||||
});
|
||||
|
||||
c.AddSecurityRequirement(new OpenApiSecurityRequirement()
|
||||
{
|
||||
{
|
||||
new OpenApiSecurityScheme
|
||||
{
|
||||
Reference = new OpenApiReference
|
||||
{
|
||||
Type = ReferenceType.SecurityScheme,
|
||||
Id = "Keycloack"
|
||||
},
|
||||
Scheme = "Bearer",
|
||||
Name = "Bearer",
|
||||
In = ParameterLocation.Header,
|
||||
},
|
||||
new List<string>()
|
||||
}
|
||||
});
|
||||
|
||||
//var xmlFile = $"{Assembly.GetExecutingAssembly().GetName().Name}.xml";
|
||||
//var xmlPath = Path.Combine(AppContext.BaseDirectory, xmlFile);
|
||||
//var includeControllerXmlComment = true;
|
||||
//c.IncludeXmlComments(xmlPath, includeControllerXmlComment);
|
||||
//c.IncludeXmlComments(Path.Combine(AppContext.BaseDirectory, "AsbCloudApp.xml"), includeControllerXmlComment);
|
||||
});
|
||||
}
|
||||
|
||||
public static void AddJWTAuthentication(this IServiceCollection services, IConfiguration configuration)
|
||||
{
|
||||
services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme)
|
||||
.AddJwtBearer(o =>
|
||||
{
|
||||
o.RequireHttpsMetadata = false;
|
||||
o.Audience = configuration["Authentication:Audience"];
|
||||
o.MetadataAddress = configuration["Authentication:MetadataAddress"]!;
|
||||
o.TokenValidationParameters = new TokenValidationParameters
|
||||
{
|
||||
ValidIssuer = configuration["Authentication:ValidIssuer"],
|
||||
};
|
||||
});
|
||||
}
|
||||
}
|
26
Persistence.API/Extensions.cs
Normal file
26
Persistence.API/Extensions.cs
Normal file
@ -0,0 +1,26 @@
|
||||
using System.ComponentModel;
|
||||
using System.Security.Claims;
|
||||
|
||||
namespace Persistence.API;
|
||||
|
||||
public static class Extensions
|
||||
{
|
||||
public static T GetUserId<T>(this ClaimsPrincipal principal)
|
||||
{
|
||||
if (principal == null)
|
||||
throw new ArgumentNullException(nameof(principal));
|
||||
|
||||
var loggedInUserId = principal.FindFirstValue(ClaimTypes.NameIdentifier);
|
||||
|
||||
if (String.IsNullOrEmpty(loggedInUserId))
|
||||
throw new ArgumentNullException(nameof(loggedInUserId));
|
||||
|
||||
var result = TypeDescriptor.GetConverter(typeof(T)).ConvertFromInvariantString(loggedInUserId);
|
||||
|
||||
if (result is null)
|
||||
throw new ArgumentNullException(nameof(result));
|
||||
|
||||
return (T)result;
|
||||
|
||||
}
|
||||
}
|
@ -8,6 +8,7 @@
|
||||
</PropertyGroup>
|
||||
|
||||
<ItemGroup>
|
||||
<PackageReference Include="Microsoft.AspNetCore.Authentication.JwtBearer" Version="8.0.10" />
|
||||
<PackageReference Include="Microsoft.VisualStudio.Azure.Containers.Tools.Targets" Version="1.19.6" />
|
||||
<PackageReference Include="Swashbuckle.AspNetCore" Version="6.4.0" />
|
||||
</ItemGroup>
|
||||
|
@ -19,9 +19,10 @@ public class Startup
|
||||
services.AddControllers();
|
||||
// Learn more about configuring Swagger/OpenAPI at https://aka.ms/aspnetcore/swashbuckle
|
||||
services.AddEndpointsApiExplorer();
|
||||
services.AddSwaggerGen();
|
||||
services.AddPersistenceDbContext(Configuration);
|
||||
services.AddSwagger(Configuration);
|
||||
services.AddInfrastructure();
|
||||
services.AddPersistenceDbContext(Configuration);
|
||||
services.AddJWTAuthentication(Configuration);
|
||||
}
|
||||
|
||||
public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
|
||||
@ -32,7 +33,8 @@ public class Startup
|
||||
|
||||
app.UseRouting();
|
||||
|
||||
//app.UseAuthorization();
|
||||
app.UseAuthentication();
|
||||
app.UseAuthorization();
|
||||
|
||||
app.UseEndpoints(endpoints =>
|
||||
{
|
||||
|
@ -6,7 +6,13 @@
|
||||
}
|
||||
},
|
||||
"ConnectionStrings": {
|
||||
"DefaultConnection": "Host=localhost;Database=persistence;Username=postgres;Password=q;Persist Security Info=True",
|
||||
"DefaultConnection": "Host=localhost;Database=persistence;Username=postgres;Password=q;Persist Security Info=True"
|
||||
},
|
||||
"AllowedHosts": "*"
|
||||
"AllowedHosts": "*",
|
||||
"Authentication": {
|
||||
"MetadataAddress": "http://localhost:8080/realms/TestRealm/.well-known/openid-configuration",
|
||||
"Audience": "account",
|
||||
"ValidIssuer": "http://localhost:8080/realms/TestRealm",
|
||||
"AuthorizationUrl": "http://localhost:8080/realms/TestRealm/protocol/openid-connect/auth"
|
||||
}
|
||||
}
|
||||
|
Loading…
Reference in New Issue
Block a user