Compare commits

...

10 Commits

Author SHA1 Message Date
Max
9f3bfc7971
Merge 46dbd8c6f5 into 21675300bb 2025-05-09 09:07:54 +00:00
max
46dbd8c6f5 [WIP] 2025-05-05 16:00:18 +02:00
max
05b95c6050 [WIP] Working schemes 2025-05-02 23:50:09 +02:00
max
edf8891ddc [WIP] Reworked auth schemes and added framework reference to Microsoft.AspNetCore.App 2025-05-02 23:27:41 +02:00
max
723c654d70 [REMOVE] Removed unused project 2025-05-02 20:49:08 +02:00
max
e22b7790dd [WIP] Reworking authentication service 2025-04-28 17:11:46 +02:00
max
d69359e937 [WIP] 2025-04-27 23:12:02 +02:00
max
e6d7578d49 [WIP] 2025-04-27 17:28:51 +02:00
max
46cf20893b [CHANGE] Reworking auth schemes & services, handlers, etc. 2025-04-27 17:23:14 +02:00
max
8e72d123fd [CHANGE] Small updates repositories 2025-04-19 23:46:29 +02:00
23 changed files with 427 additions and 108 deletions

View File

@ -7,13 +7,13 @@ namespace DotBased.AspNet.Authority.EFCore;
public static class Extensions
{
public static IServiceCollection AddAuthorityContext(this IServiceCollection services, Action<DbContextOptionsBuilder> options)
public static AuthorityBuilder AddAuthorityContext(this AuthorityBuilder builder, Action<DbContextOptionsBuilder> options)
{
services.AddDbContextFactory<AuthorityContext>(options);
services.AddScoped<IAttributeRepository, AttributeRepository>();
services.AddScoped<IGroupRepository, GroupRepository>();
services.AddScoped<IRoleRepository, RoleRepository>();
services.AddScoped<IUserRepository, UserRepository>();
return services;
builder.Services.AddDbContextFactory<AuthorityContext>(options);
builder.Services.AddScoped<IAttributeRepository, AttributeRepository>();
builder.Services.AddScoped<IGroupRepository, GroupRepository>();
builder.Services.AddScoped<IRoleRepository, RoleRepository>();
builder.Services.AddScoped<IUserRepository, UserRepository>();
return builder;
}
}

View File

@ -1,3 +1,4 @@
using DotBased.AspNet.Authority.EFCore.Models;
using DotBased.AspNet.Authority.Models;
using DotBased.AspNet.Authority.Models.Authority;
using DotBased.AspNet.Authority.Repositories;
@ -37,6 +38,28 @@ public class GroupRepository(IDbContextFactory<AuthorityContext> contextFactory,
return await context.Groups.Where(g => g.Id == groupId).Include(g => g.Attributes).FirstOrDefaultAsync(cancellationToken: cancellationToken);
}
public async Task<bool> AddUsersToGroupAsync(List<AuthorityUser> users, AuthorityGroup group, CancellationToken cancellationToken = default)
{
await using var context = await contextFactory.CreateDbContextAsync(cancellationToken);
if (!context.Groups.Any(g => g.Id == group.Id))
{
return false;
}
var usersToAdd = users.Where(u => !context.UserGroups.Any(ug => ug.UserId == u.Id)).ToList();
if (usersToAdd.Count == 0)
{
return false;
}
foreach (var user in usersToAdd)
{
context.UserGroups.Add(new UserGroups() { UserId = user.Id, GroupId = group.Id });
}
var saveResult = await context.SaveChangesAsync(cancellationToken);
return saveResult > 0;
}
public async Task<List<AuthorityGroup>> GetUserGroupsAsync(AuthorityUser user, CancellationToken cancellationToken = default)
{
await using var context = await contextFactory.CreateDbContextAsync(cancellationToken);
@ -72,22 +95,21 @@ public class GroupRepository(IDbContextFactory<AuthorityContext> contextFactory,
logger.LogError("Group version validation failed.");
return null;
}
var entry = context.Groups.Update(group);
var saveResult = await context.SaveChangesAsync(cancellationToken);
return saveResult != 0 ? entry.Entity : null;
}
public async Task<bool> DeleteGroupAsync(AuthorityGroup group, CancellationToken cancellationToken = default)
public async Task<bool> DeleteGroupsAsync(List<AuthorityGroup> groups, CancellationToken cancellationToken = default)
{
await using var context = await contextFactory.CreateDbContextAsync(cancellationToken);
var currentGroup = await context.Groups.FirstOrDefaultAsync(g => g.Id == group.Id, cancellationToken);
if (currentGroup == null)
{
logger.LogError("Group with id {groupId} not found.", group.Id);
return false;
}
context.Groups.Remove(currentGroup);
var groupIds = groups.Select(g => g.Id).ToList();
context.Groups.RemoveRange(groups);
context.UserGroups.RemoveRange(context.UserGroups.Where(ug => groupIds.Contains(ug.GroupId)));
context.RoleLinks.RemoveRange(context.RoleLinks.Where(rl => groupIds.Contains(rl.LinkId)));
var saveResult = await context.SaveChangesAsync(cancellationToken);
return saveResult != 0;
}

View File

@ -8,7 +8,7 @@ namespace DotBased.AspNet.Authority.EFCore.Repositories;
public class UserRepository(IDbContextFactory<AuthorityContext> contextFactory, ILogger<UserRepository> logger) : RepositoryBase, IUserRepository
{
public async Task<QueryItems<AuthorityUserItem>> GetAuthorityUsersAsync(int limit = 20, int offset = 0, string search = "", CancellationToken cancellationToken = default)
public async Task<QueryItems<AuthorityUserItem>> GetUsersAsync(int limit = 20, int offset = 0, string search = "", CancellationToken cancellationToken = default)
{
await using var context = await contextFactory.CreateDbContextAsync(cancellationToken);
var query = context.Users.AsQueryable();
@ -29,7 +29,7 @@ public class UserRepository(IDbContextFactory<AuthorityContext> contextFactory,
return QueryItems<AuthorityUserItem>.Create(selected, totalCount, limit, offset);
}
public async Task<AuthorityUser?> GetAuthorityUserByIdAsync(Guid id, CancellationToken cancellationToken = default)
public async Task<AuthorityUser?> GetUserByIdAsync(Guid id, CancellationToken cancellationToken = default)
{
await using var context = await contextFactory.CreateDbContextAsync(cancellationToken);
if (id == Guid.Empty)

View File

@ -4,8 +4,29 @@ public static class AuthorityDefaults
{
public static class Scheme
{
public const string AuthenticationScheme = "Authority.Scheme.Authentication";
public const string ExternalScheme = "Authority.Scheme.External";
public static class Authority
{
public const string AuthenticationScheme = "AuthorityLogin";
}
public static class Cookie
{
public const string AuthenticationScheme = "AuthorityCookie";
public const string CookieName = "AuthorityAuth";
}
public static class Token
{
public const string AuthenticationScheme = "AuthorityToken";
public const string TokenName = "AuthorityAuthToken";
}
}
public static class Paths
{
public const string Default = "/";
public const string Login = "/auth/login";
public const string Logout = "/auth/logout";
public const string Forbidden = "/forbidden";
}
}

View File

@ -1,7 +1,11 @@
using DotBased.AspNet.Authority.Crypto;
using DotBased.AspNet.Authority.Handlers;
using DotBased.AspNet.Authority.Managers;
using DotBased.AspNet.Authority.Models.Options;
using DotBased.AspNet.Authority.Models.Options.Auth;
using DotBased.AspNet.Authority.Services;
using DotBased.AspNet.Authority.Validators;
using Microsoft.AspNetCore.Authentication;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.DependencyInjection.Extensions;
@ -9,13 +13,13 @@ namespace DotBased.AspNet.Authority;
public static class AuthorityProviderExtensions
{
public static AuthorityBuilder AddAuthority(this IServiceCollection services, Action<AuthorityOptions>? optionsAction = null)
public static AuthorityBuilder AddAuthority(this IServiceCollection services) => AddAuthority(services, _ => { });
public static AuthorityBuilder AddAuthority(this IServiceCollection services, Action<AuthorityOptions> optionsAction)
{
if (optionsAction != null)
{
services.AddOptions();
services.Configure<AuthorityOptions>(optionsAction);
}
services.AddOptions();
ArgumentNullException.ThrowIfNull(optionsAction);
services.Configure(optionsAction);
services.TryAddScoped<ICryptographer, Cryptographer>();
services.TryAddScoped<IPasswordHasher, PasswordHasher>();
@ -26,32 +30,68 @@ public static class AuthorityProviderExtensions
services.TryAddScoped<IPhoneNumberVerifier, PhoneNumberVerifier>();
services.TryAddScoped<IUserVerifier, UserVerifier>();*/
services.TryAddScoped<AuthorityManager>();
return new AuthorityBuilder(services);
}
public static AuthorityBuilder AddAuthorityRepository<TRepository>(this AuthorityBuilder authorityBuilder) where TRepository : class
public static AuthenticationBuilder AddAuthorityAuth(this AuthorityBuilder builder, Action<AuthorityAuthenticationOptions> configureOptions)
{
return authorityBuilder;
ArgumentNullException.ThrowIfNull(configureOptions);
builder.Services.Configure(configureOptions);
builder.Services.AddScoped<IAuthenticationService, AuthorityAuthenticationService>();
var authorityOptions = new AuthorityAuthenticationOptions();
configureOptions.Invoke(authorityOptions);
var authBuilder = builder.Services.AddAuthentication(options =>
{
options.DefaultScheme = authorityOptions.DefaultScheme;
options.DefaultAuthenticateScheme = authorityOptions.DefaultAuthenticateScheme;
options.DefaultChallengeScheme = authorityOptions.DefaultChallengeScheme;
options.DefaultSignInScheme = authorityOptions.DefaultSignInScheme;
options.DefaultSignOutScheme = authorityOptions.DefaultSignOutScheme;
options.DefaultForbidScheme = authorityOptions.DefaultForbidScheme;
});
return authBuilder;
}
public static AuthenticationBuilder AddAuthorityLoginScheme(this AuthenticationBuilder builder, string scheme) =>
AddAuthorityLoginScheme(builder, scheme, _ => { });
public static AuthenticationBuilder AddAuthorityLoginScheme(this AuthenticationBuilder builder,
string scheme,
Action<AuthorityLoginOptions> configureOptions)
{
builder.AddScheme<AuthorityLoginOptions, AuthorityLoginAuthenticationHandler>(scheme, scheme, configureOptions);
return builder;
}
public static AuthenticationBuilder AddAuthorityCookie(this AuthenticationBuilder builder, string scheme)
{
builder.AddCookie(scheme, options =>
{
options.Cookie.Name = AuthorityDefaults.Scheme.Cookie.CookieName;
options.Cookie.Path = AuthorityDefaults.Paths.Default;
options.Cookie.Expiration = TimeSpan.FromDays(1);
options.Cookie.HttpOnly = true;
options.Cookie.IsEssential = true;
options.LoginPath = AuthorityDefaults.Paths.Login;
options.LogoutPath = AuthorityDefaults.Paths.Logout;
options.AccessDeniedPath = AuthorityDefaults.Paths.Forbidden;
options.SlidingExpiration = true;
//options.SessionStore
});
return builder;
}
public static AuthenticationBuilder AddAuthorityToken(this AuthenticationBuilder builder, string scheme)
{
return builder;
}
public static AuthorityBuilder MapAuthorityEndpoints(this AuthorityBuilder builder)
{
return builder;
}
private static Type GetBaseGenericArgumentType<TModel>(Type baseType)
{
var userGenericBaseTypeDefinition = typeof(TModel).BaseType?.GetGenericTypeDefinition();
if (userGenericBaseTypeDefinition != null && userGenericBaseTypeDefinition == baseType)
{
var userBaseGenericArguments = userGenericBaseTypeDefinition.GetGenericArguments();
if (userBaseGenericArguments.Length <= 0)
{
throw new ArgumentException("Base implementation does not have the required generic argument.", nameof(TModel));
}
return userBaseGenericArguments[0];
}
throw new ArgumentException($"Given object {typeof(TModel).Name} does not have the base implementation type of: {baseType.Name}", nameof(TModel));
}
}

View File

@ -0,0 +1,35 @@
using System.Security.Claims;
using System.Text.Json;
using Microsoft.AspNetCore.Authentication;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
namespace DotBased.AspNet.Authority.Controllers;
[ApiController]
[Route("[controller]")]
public class AuthorityController : ControllerBase
{
[HttpGet("auth/login")]
[AllowAnonymous]
public async Task<ActionResult> LoginFromSchemeAsync([FromQuery(Name = "s")] string? scheme)
{
var cPrincipal = new ClaimsPrincipal();
await HttpContext.SignInAsync(cPrincipal);
return Ok();
}
[HttpGet("auth/logout")]
public async Task<ActionResult> LogoutAsync()
{
await HttpContext.SignOutAsync();
return Ok();
}
[HttpGet("info")]
[AllowAnonymous]
public async Task<ActionResult<JsonDocument>> GetAuthorityInfoAsync()
{
return Ok();
}
}

View File

@ -7,9 +7,7 @@
</PropertyGroup>
<ItemGroup>
<Reference Include="Microsoft.Extensions.DependencyInjection.Abstractions">
<HintPath>..\..\..\.nuget\packages\microsoft.extensions.dependencyinjection.abstractions\8.0.2\lib\net8.0\Microsoft.Extensions.DependencyInjection.Abstractions.dll</HintPath>
</Reference>
<FrameworkReference Include="Microsoft.AspNetCore.App" />
</ItemGroup>
<ItemGroup>
@ -17,12 +15,12 @@
</ItemGroup>
<ItemGroup>
<Folder Include="Models\Data\" />
<Folder Include="Models\Security\" />
<Folder Include="Schemas\" />
</ItemGroup>
<ItemGroup>
<PackageReference Include="Microsoft.Extensions.Options" Version="9.0.0" />
<PackageReference Include="Microsoft.Extensions.Options" Version="8.0.2" />
</ItemGroup>
</Project>

View File

@ -0,0 +1,33 @@
using System.Security.Claims;
using System.Text.Encodings.Web;
using DotBased.AspNet.Authority.Managers;
using DotBased.AspNet.Authority.Models.Options.Auth;
using Microsoft.AspNetCore.Authentication;
using Microsoft.Extensions.Logging;
using Microsoft.Extensions.Options;
namespace DotBased.AspNet.Authority.Handlers;
/// <summary>
/// Handles authentication for Authority logins.
/// </summary>
public class AuthorityLoginAuthenticationHandler(IOptionsMonitor<AuthorityLoginOptions> options,
ILoggerFactory logger,
UrlEncoder encoder,
AuthorityManager manager) : SignInAuthenticationHandler<AuthorityLoginOptions>(options, logger, encoder)
{
protected override Task<AuthenticateResult> HandleAuthenticateAsync()
{
throw new NotImplementedException();
}
protected override Task HandleSignOutAsync(AuthenticationProperties? properties)
{
throw new NotImplementedException();
}
protected override Task HandleSignInAsync(ClaimsPrincipal user, AuthenticationProperties? properties)
{
throw new NotImplementedException();
}
}

View File

@ -38,7 +38,7 @@ public partial class AuthorityManager
public async Task<Result<QueryItems<AuthorityUserItem>>> SearchUsersAsync(string query, int maxResults = 20, int offset = 0, CancellationToken cancellationToken = default)
{
var result = await UserRepository.GetAuthorityUsersAsync(maxResults, offset, query, cancellationToken);
var result = await UserRepository.GetUsersAsync(maxResults, offset, query, cancellationToken);
return result;
}

View File

@ -0,0 +1,7 @@
namespace DotBased.AspNet.Authority.Models.Data.Auth;
public class AuthenticationSessionType
{
public string Id { get; set; } = string.Empty;
public string Description { get; set; } = string.Empty;
}

View File

@ -0,0 +1,16 @@
namespace DotBased.AspNet.Authority.Models.Data.Auth;
public class AuthenticationType
{
public string Id { get; set; } = string.Empty;
public string Name { get; set; } = string.Empty;
public string Provider { get; set; } = string.Empty;
public bool Redirects { get; set; }
public AuthenticationTypePaths Paths { get; set; } = new();
}
public class AuthenticationTypePaths
{
public string Login { get; set; } = string.Empty;
public string Logout { get; set; } = string.Empty;
}

View File

@ -0,0 +1,10 @@
using DotBased.AspNet.Authority.Models.Data.Auth;
namespace DotBased.AspNet.Authority.Models.Data.System;
public class AboutModel
{
public string Name { get; set; } = "Authority.Server";
public List<AuthenticationType> AuthenticationTypes { get; set; } = [];
public List<AuthenticationSessionType> SessionTypes { get; set; } = [];
}

View File

@ -0,0 +1,14 @@
namespace DotBased.AspNet.Authority.Models.Options.Auth;
public class AuthenticationSecurityOptions
{
public SecurityMode SecurityMode { get; set; } = SecurityMode.Normal;
public List<string> AllowedLoginMethods { get; set; } = ["*"];
}
public enum SecurityMode
{
Loose = 0,
Normal = 1,
Strict = 2
}

View File

@ -0,0 +1,31 @@
namespace DotBased.AspNet.Authority.Models.Options.Auth;
public class AuthorityAuthenticationOptions
{
public AuthenticationSecurityOptions Security { get; set; } = new AuthenticationSecurityOptions();
public SessionOptions Session { get; set; } = new SessionOptions();
public string DefaultScheme { get; set; } = string.Empty;
public string DefaultAuthenticateScheme { get; set; } = string.Empty;
public string DefaultChallengeScheme { get; set; } = string.Empty;
public string DefaultForbidScheme { get; set; } = string.Empty;
public string DefaultSignInScheme { get; set; } = string.Empty;
public string DefaultSignOutScheme { get; set; } = string.Empty;
/// <summary>
/// List of schemes that the Authority application will support to authenticate against.
/// </summary>
public List<SchemeInfo> SchemeInfoMap { get; set; } = [];
}
public class SchemeInfo
{
public string Scheme { get; set; } = string.Empty;
public string Description { get; set; } = string.Empty;
public SchemeType Type { get; set; }
public string AuthenticationType { get; set; } = string.Empty;
}
public enum SchemeType
{
Authentication,
SessionStore
}

View File

@ -0,0 +1,8 @@
using Microsoft.AspNetCore.Authentication;
namespace DotBased.AspNet.Authority.Models.Options.Auth;
public class AuthorityLoginOptions : AuthenticationSchemeOptions
{
}

View File

@ -0,0 +1,6 @@
namespace DotBased.AspNet.Authority.Models.Options.Auth;
public class SessionOptions
{
public TimeSpan RefreshInterval { get; set; } = TimeSpan.FromMinutes(30);
}

View File

@ -7,8 +7,9 @@ public interface IGroupRepository
{
public Task<QueryItems<AuthorityGroupItem>> GetGroupsAsync(int limit = 20, int offset = 0, string search = "", CancellationToken cancellationToken = default);
public Task<AuthorityGroup?> GetGroupByIdAsync(string id, CancellationToken cancellationToken = default);
public Task<bool> AddUsersToGroupAsync(List<AuthorityUser> users, AuthorityGroup group, CancellationToken cancellationToken = default);
public Task<List<AuthorityGroup>> GetUserGroupsAsync(AuthorityUser user, CancellationToken cancellationToken = default);
public Task<AuthorityGroup?> CreateGroupAsync(AuthorityGroup group, CancellationToken cancellationToken = default);
public Task<AuthorityGroup?> UpdateGroupAsync(AuthorityGroup group, CancellationToken cancellationToken = default);
public Task<bool> DeleteGroupAsync(AuthorityGroup group, CancellationToken cancellationToken = default);
public Task<bool> DeleteGroupsAsync(List<AuthorityGroup> groups, CancellationToken cancellationToken = default);
}

View File

@ -5,8 +5,8 @@ namespace DotBased.AspNet.Authority.Repositories;
public interface IUserRepository
{
public Task<QueryItems<AuthorityUserItem>> GetAuthorityUsersAsync(int limit = 20, int offset = 0, string search = "", CancellationToken cancellationToken = default);
public Task<AuthorityUser?> GetAuthorityUserByIdAsync(Guid id, CancellationToken cancellationToken = default);
public Task<QueryItems<AuthorityUserItem>> GetUsersAsync(int limit = 20, int offset = 0, string search = "", CancellationToken cancellationToken = default);
public Task<AuthorityUser?> GetUserByIdAsync(Guid id, CancellationToken cancellationToken = default);
public Task<AuthorityUser?> CreateUserAsync(AuthorityUser user, CancellationToken cancellationToken = default);
public Task<AuthorityUser?> UpdateUserAsync(AuthorityUser user, CancellationToken cancellationToken = default);
public Task<bool> DeleteUsersAsync(List<AuthorityUser> users, CancellationToken cancellationToken = default);

View File

@ -0,0 +1,48 @@
using System.Security.Claims;
using DotBased.AspNet.Authority.Models.Options.Auth;
using DotBased.Logging;
using Microsoft.AspNetCore.Authentication;
using Microsoft.AspNetCore.Http;
using Microsoft.Extensions.Options;
namespace DotBased.AspNet.Authority.Services;
public class AuthorityAuthenticationService(
IAuthenticationSchemeProvider schemes,
IAuthenticationHandlerProvider handlers,
IClaimsTransformation transform,
IOptions<AuthenticationOptions> options,
IOptions<AuthorityAuthenticationOptions> authorityOptions) : AuthenticationService(schemes, handlers, transform, options)
{
private readonly ILogger _logger = LogService.RegisterLogger(typeof(AuthorityAuthenticationService));
private readonly AuthorityAuthenticationOptions _options = authorityOptions.Value;
public IReadOnlyCollection<SchemeInfo> GetSchemeInfos(SchemeType schemeType) => _options.SchemeInfoMap.Where(s => s.Type == schemeType).ToList();
public IReadOnlyCollection<SchemeInfo> GetAllSchemeInfos() => _options.SchemeInfoMap;
public override Task<AuthenticateResult> AuthenticateAsync(HttpContext context, string? scheme)
{
return base.AuthenticateAsync(context, scheme);
}
public override Task ChallengeAsync(HttpContext context, string? scheme, AuthenticationProperties? properties)
{
return base.ChallengeAsync(context, scheme, properties);
}
public override Task SignInAsync(HttpContext context, string? scheme, ClaimsPrincipal principal, AuthenticationProperties? properties)
{
return base.SignInAsync(context, scheme, principal, properties);
}
public override Task SignOutAsync(HttpContext context, string? scheme, AuthenticationProperties? properties)
{
return base.SignOutAsync(context, scheme, properties);
}
public override Task ForbidAsync(HttpContext context, string? scheme, AuthenticationProperties? properties)
{
return base.ForbidAsync(context, scheme, properties);
}
}

View File

@ -1,12 +0,0 @@
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<TargetFramework>netstandard2.1</TargetFramework>
<Nullable>enable</Nullable>
</PropertyGroup>
<ItemGroup>
<ProjectReference Include="..\DotBased\DotBased.csproj" />
</ItemGroup>
</Project>

View File

@ -22,8 +22,6 @@ Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "AspNet", "AspNet", "{624E7B
EndProject
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "DotBased.AspNet.Authority", "DotBased.AspNet.Authority\DotBased.AspNet.Authority.csproj", "{A3ADC9AF-39B7-4EC4-8022-946118A8C322}"
EndProject
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "DotBased.Data", "DotBased.Data\DotBased.Data.csproj", "{2DF9FEEF-5A60-4B41-9B5F-F883DCE33EF4}"
EndProject
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "DotBased.AspNet.Authority.EFCore", "DotBased.AspNet.Authority.EFCore\DotBased.AspNet.Authority.EFCore.csproj", "{F1F3F60B-911F-4036-8A2B-CEC18A8F59DD}"
EndProject
Global
@ -64,10 +62,6 @@ Global
{A3ADC9AF-39B7-4EC4-8022-946118A8C322}.Debug|Any CPU.Build.0 = Debug|Any CPU
{A3ADC9AF-39B7-4EC4-8022-946118A8C322}.Release|Any CPU.ActiveCfg = Release|Any CPU
{A3ADC9AF-39B7-4EC4-8022-946118A8C322}.Release|Any CPU.Build.0 = Release|Any CPU
{2DF9FEEF-5A60-4B41-9B5F-F883DCE33EF4}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{2DF9FEEF-5A60-4B41-9B5F-F883DCE33EF4}.Debug|Any CPU.Build.0 = Debug|Any CPU
{2DF9FEEF-5A60-4B41-9B5F-F883DCE33EF4}.Release|Any CPU.ActiveCfg = Release|Any CPU
{2DF9FEEF-5A60-4B41-9B5F-F883DCE33EF4}.Release|Any CPU.Build.0 = Release|Any CPU
{F1F3F60B-911F-4036-8A2B-CEC18A8F59DD}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{F1F3F60B-911F-4036-8A2B-CEC18A8F59DD}.Debug|Any CPU.Build.0 = Debug|Any CPU
{F1F3F60B-911F-4036-8A2B-CEC18A8F59DD}.Release|Any CPU.ActiveCfg = Release|Any CPU
@ -81,7 +75,6 @@ Global
{AC8343A5-7953-4E1D-A926-406BE4D7E819} = {DBDB4538-85D4-45AC-9E0A-A684467AEABA}
{624E7B11-8A18-46E5-AB1F-6AF6097F9D4D} = {2156FB93-C252-4B33-8A0C-73C82FABB163}
{A3ADC9AF-39B7-4EC4-8022-946118A8C322} = {624E7B11-8A18-46E5-AB1F-6AF6097F9D4D}
{2DF9FEEF-5A60-4B41-9B5F-F883DCE33EF4} = {2156FB93-C252-4B33-8A0C-73C82FABB163}
{F1F3F60B-911F-4036-8A2B-CEC18A8F59DD} = {624E7B11-8A18-46E5-AB1F-6AF6097F9D4D}
EndGlobalSection
EndGlobal

View File

@ -0,0 +1,35 @@
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
namespace TestWebApi.Controllers;
[ApiController]
[Route("[controller]")]
[Authorize]
public class WeatherController : ControllerBase
{
private readonly string[] _summaries =
[
"Freezing", "Bracing", "Chilly", "Cool", "Mild", "Warm", "Balmy", "Hot", "Sweltering", "Scorching"
];
[HttpGet("GetWeatherForecast")]
public async Task<ActionResult<List<WeatherForecast>>> GetForecast()
{
var forecast = Enumerable.Range(1, 5).Select(index =>
new WeatherForecast
(
DateOnly.FromDateTime(DateTime.Now.AddDays(index)),
Random.Shared.Next(-20, 55),
_summaries[Random.Shared.Next(_summaries.Length)]
))
.ToList();
await Task.Delay(TimeSpan.FromSeconds(1));
return forecast;
}
public record WeatherForecast(DateOnly Date, int TemperatureC, string? Summary)
{
public int TemperatureF => 32 + (int)(TemperatureC / 0.5556);
}
}

View File

@ -1,5 +1,6 @@
using DotBased.AspNet.Authority;
using DotBased.AspNet.Authority.EFCore;
using DotBased.AspNet.Authority.Models.Options.Auth;
using DotBased.Logging;
using DotBased.Logging.MEL;
using DotBased.Logging.Serilog;
@ -21,20 +22,52 @@ LogService.AddLogAdapter(new BasedSerilogAdapter(serilogLogger));
builder.Logging.ClearProviders();
builder.Logging.AddDotBasedLoggerProvider(LogService.Options);
builder.Services.AddAuthorityContext(options =>
{
options.UseSqlite("Data Source=dev-dotbased.db", c => c.MigrationsAssembly("TestWebApi"));
});
builder.Services.AddAuthority(options =>
{
});
/*builder.Services.AddAuthentication(options =>
builder.Services.AddControllers();
builder.Services.AddAuthority()
.AddAuthorityContext(options =>
{
options.DefaultScheme = BasedAuthenticationDefaults.BasedAuthenticationScheme;
options.DefaultChallengeScheme = BasedAuthenticationDefaults.BasedAuthenticationScheme;
}).AddCookie();*/
options.UseSqlite("Data Source=dev-authority.db", c => c.MigrationsAssembly("TestWebApi"));
})
.MapAuthorityEndpoints()
.AddAuthorityAuth(options =>
{
options.DefaultScheme = AuthorityDefaults.Scheme.Cookie.AuthenticationScheme;
options.DefaultSignInScheme = AuthorityDefaults.Scheme.Authority.AuthenticationScheme;
options.DefaultSignOutScheme = AuthorityDefaults.Scheme.Authority.AuthenticationScheme;
options.SchemeInfoMap = [
new SchemeInfo
{
Scheme = AuthorityDefaults.Scheme.Authority.AuthenticationScheme,
Description = "Authority password login",
Type = SchemeType.Authentication,
AuthenticationType = "Password"
},
/*new SchemeInfo
{
Scheme = "OIDC",
Description = "Authentik OIDC login",
Type = SchemeType.Authentication,
AuthenticationType = "OpenIdConnect"
},*/
new SchemeInfo
{
Scheme = AuthorityDefaults.Scheme.Cookie.AuthenticationScheme,
Description = "Cookie session",
Type = SchemeType.SessionStore
}/*,
new SchemeInfo
{
Scheme = AuthorityDefaults.Scheme.Token.AuthenticationScheme,
Description = "Session token",
Type = SchemeType.SessionStore
}*/
];
})
.AddAuthorityLoginScheme(AuthorityDefaults.Scheme.Authority.AuthenticationScheme)
.AddAuthorityCookie(AuthorityDefaults.Scheme.Cookie.AuthenticationScheme)
.AddAuthorityToken(AuthorityDefaults.Scheme.Token.AuthenticationScheme);
// Add services to the container.
// Learn more about configuring Swagger/OpenAPI at https://aka.ms/aspnetcore/swashbuckle
@ -53,28 +86,13 @@ if (app.Environment.IsDevelopment())
}
app.UseHttpsRedirection();
app.MapControllers();
var summaries = new[]
{
"Freezing", "Bracing", "Chilly", "Cool", "Mild", "Warm", "Balmy", "Hot", "Sweltering", "Scorching"
};
app.MapGet("/weatherforecast", () =>
{
var forecast = Enumerable.Range(1, 5).Select(index =>
new WeatherForecast
(
DateOnly.FromDateTime(DateTime.Now.AddDays(index)),
Random.Shared.Next(-20, 55),
summaries[Random.Shared.Next(summaries.Length)]
))
.ToArray();
return forecast;
})
.WithName("GetWeatherForecast")
.WithOpenApi();
app.UseAuthentication();
app.UseAuthorization();
app.Run();
return;
ILogger SetupSerilog()
{
@ -82,9 +100,4 @@ ILogger SetupSerilog()
.MinimumLevel.Verbose()
.WriteTo.Console(outputTemplate: BasedSerilog.OutputTemplate);
return logConfig.CreateLogger();
}
record WeatherForecast(DateOnly Date, int TemperatureC, string? Summary)
{
public int TemperatureF => 32 + (int)(TemperatureC / 0.5556);
}