Compare commits

...

18 Commits

Author SHA1 Message Date
max
e8739defad Merge branch 'main' into feature/base_authority 2025-08-02 16:41:45 +02:00
max
3a9c499aab [CHANGE] Remove old ASP auth project 2025-08-02 16:27:16 +02:00
max
e4690dfe22 [WORKFLOW] Updated gitea instance url & added packing for logging libs
All checks were successful
Build C# Library / build (push) Successful in 1m17s
2025-08-02 16:10:48 +02:00
max
525d82ca27 [CHANGE] Workflow change path
Some checks failed
Build C# Library / build (push) Failing after 1m7s
2025-08-02 16:05:36 +02:00
max
ac664f16ce [CHANGE] Corrected project to pack
Some checks failed
Build C# Library / build (push) Failing after 57s
2025-08-02 16:03:31 +02:00
max
c3f58eb172 [ADD] Workflow pack to nuget package and publish to Gitea packages
Some checks failed
Build C# Library / build (push) Failing after 57s
2025-08-02 16:00:16 +02:00
max
ce4139d100 [CHANGE] Updated workflow dotnet version -> 8.0.x
All checks were successful
Build C# Library / build (push) Successful in 1m2s
2025-08-02 15:47:14 +02:00
max
582fe194b9 [ADD] Workflow: build on main push
Some checks failed
Build C# Library / build (push) Failing after 1m4s
2025-08-02 15:00:20 +02:00
max
333cf66cb4 [WIP] 2025-05-18 22:36:12 +02:00
max
217c55df00 [WIP] 2025-05-18 18:03:40 +02:00
max
b3763fb795 [WIP] Start impl auth handler 2025-05-18 01:01:07 +02:00
max
c225576c44 [WIP] Update AuthenticationService info 2025-05-18 00:35:04 +02: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
46 changed files with 415 additions and 870 deletions

View File

@@ -0,0 +1,50 @@
name: Build C# Library
run-name: Build Library project
on:
push:
branches:
- main
jobs:
build:
runs-on: ubuntu-latest
steps:
- name: Checkout repository
uses: actions/checkout@v4
- name: Setup .NET SDK
uses: actions/setup-dotnet@v3
with:
dotnet-version: '8.0.x'
- name: Restore dependencies
run: dotnet restore
- name: Build library
run: dotnet build --configuration Release
- name: Pack DotBased
run: dotnet pack ./DotBased/DotBased.csproj --configuration Release -o ./artifacts
- name: Pack DotBased.Logging.MEL
run: dotnet pack ./DotBased.Logging.MEL/DotBased.Logging.MEL.csproj --configuration Release -o ./artifacts
- name: Pack DotBased.Logging.Serilog
run: dotnet pack ./DotBased.Logging.Serilog/DotBased.Logging.Serilog.csproj --configuration Release -o ./artifacts
- name: Publish library to Gitea NuGet
run: |
dotnet nuget add source \
--username $GITEA_USER \
--password $GITEA_TOKEN \
--store-password-in-clear-text \
--name gitea \
https://git.netzbyte.com/api/packages/$GITEA_USER/nuget/index.json
dotnet nuget push ./artifacts/*.nupkg --source gitea --skip-duplicate
env:
GITEA_USER: max
GITEA_TOKEN: ${{ secrets.PACKAGES_TOKEN }}

View File

@@ -1,98 +0,0 @@
using System.Collections.ObjectModel;
using DotBased.ASP.Auth.Domains.Auth;
using Microsoft.AspNetCore.Components.Authorization;
namespace DotBased.ASP.Auth;
public class AuthDataCache
{
public AuthDataCache(BasedAuthConfiguration configuration)
{
_configuration = configuration;
}
private readonly BasedAuthConfiguration _configuration;
private readonly AuthStateCacheCollection<AuthenticationStateModel, AuthenticationState> _authenticationStateCollection = [];
public ResultOld PurgeSessionState(string id) => _authenticationStateCollection.Remove(id) ? ResultOld.Ok() : ResultOld.Failed("Failed to purge session state from cache! Or the session was not cached...");
public void CacheSessionState(AuthenticationStateModel stateModel, AuthenticationState? state = null) => _authenticationStateCollection[stateModel.Id] =
new AuthStateCacheNode<AuthenticationStateModel, AuthenticationState>(stateModel, state);
public ResultOld<Tuple<AuthenticationStateModel, AuthenticationState?>> RequestSessionState(string id)
{
if (!_authenticationStateCollection.TryGetValue(id, out var node))
return ResultOld<Tuple<AuthenticationStateModel, AuthenticationState?>>.Failed("No cached object found!");
string failedMsg;
if (node.StateModel != null)
{
if (node.IsValidLifespan(_configuration.CachedAuthSessionLifespan))
return ResultOld<Tuple<AuthenticationStateModel, AuthenticationState?>>.Ok(new Tuple<AuthenticationStateModel, AuthenticationState?>(node.StateModel, node.State));
failedMsg = $"Session has invalid lifespan, removing entry: [{id}] from cache!";
}
else
failedMsg = $"Returned object is null, removing entry: [{id}] from cache!";
_authenticationStateCollection.Remove(id);
return ResultOld<Tuple<AuthenticationStateModel, AuthenticationState?>>.Failed(failedMsg);
}
}
public class AuthStateCacheNode<TStateModel, TState> where TStateModel : class where TState : class
{
public AuthStateCacheNode(TStateModel stateModel, TState? state)
{
StateModel = stateModel;
State = state;
}
public TStateModel? StateModel { get; private set; }
public TState? State { get; private set; }
public DateTime DateCached { get; private set; } = DateTime.Now;
public void UpdateObject(TStateModel obj)
{
StateModel = obj;
DateCached = DateTime.Now;
}
/// <summary>
/// Checks if the cached object is within the given lifespan.
/// </summary>
/// <param name="lifespan">The max. lifespan</param>
public bool IsValidLifespan(TimeSpan lifespan) => DateCached.Add(lifespan) > DateTime.Now;
public override bool Equals(object? obj)
{
if (obj is AuthStateCacheNode<TStateModel, TState> cacheObj)
return StateModel != null && StateModel.Equals(cacheObj.StateModel);
return false;
}
public override int GetHashCode() => typeof(TStateModel).GetHashCode();
public override string ToString() => typeof(TStateModel).ToString();
}
public class AuthStateCacheCollection<TStateModel, TState> : KeyedCollection<string, AuthStateCacheNode<TStateModel, TState>> where TStateModel : class where TState : class
{
protected override string GetKeyForItem(AuthStateCacheNode<TStateModel, TState> item) => item.StateModel?.ToString() ?? string.Empty;
public new AuthStateCacheNode<TStateModel, TState>? this[string id]
{
get => TryGetValue(id, out AuthStateCacheNode<TStateModel, TState>? nodeValue) ? nodeValue : null;
set
{
if (value == null)
return;
if (TryGetValue(id, out AuthStateCacheNode<TStateModel, TState>? nodeValue))
Remove(nodeValue);
Add(value);
}
}
public void Insert(AuthStateCacheNode<TStateModel, TState> node)
{
if (Contains(node))
Remove(node);
Add(node);
}
}

View File

@@ -1,13 +0,0 @@
namespace DotBased.ASP.Auth.Services;
public class AuthenticationService
{
public AuthenticationService()
{
/*
* - Login
* - Logout
* - Register
*/
}
}

View File

@@ -1,65 +0,0 @@
namespace DotBased.ASP.Auth;
public class BasedAuthConfiguration
{
/// <summary>
/// Allow users to registrate.
/// </summary>
public bool AllowRegistration { get; set; }
//TODO: Callback when a user registers, so the application can handle sending emails or generate a code to complete the registration.
//TODO: Callback for validation email, phone number
/// <summary>
/// Allow no passwords on users, not recommended!
/// </summary>
public bool AllowEmptyPassword { get; set; } = false;
/// <summary>
/// This path is used for redirecting to the login page.
/// </summary>
public string LoginPath { get; set; } = string.Empty;
/// <summary>
/// The path that will be used if the logout is requested.
/// </summary>
public string LogoutPath { get; set; } = string.Empty;
/// <summary>
/// The page that the client will be redirected to after logging out.
/// </summary>
public string LoggedOutPath { get; set; } = string.Empty;
/// <summary>
/// The max age before a AuthenticationState will expire (default: 7 days).
/// </summary>
public TimeSpan AuthenticationStateMaxAgeBeforeExpire { get; set; } = TimeSpan.FromDays(7);
/// <summary>
/// How long a session state will be cached (default: 15 min)
/// </summary>
public TimeSpan CachedAuthSessionLifespan { get; set; } = TimeSpan.FromMinutes(15);
/// <summary>
/// Can be used to seed a default user and/or group for first time use.
/// </summary>
public Action<IAuthDataRepository>? SeedData { get; set; }
public Type? AuthDataRepositoryType { get; private set; }
public void SetDataRepositoryType<TDataProviderType>() where TDataProviderType : IAuthDataRepository =>
AuthDataRepositoryType = typeof(TDataProviderType);
public Type? SessionStateProviderType { get; private set; }
public void SetSessionStateProviderType<TSessionStateProviderType>()
where TSessionStateProviderType : ISessionStateProvider =>
SessionStateProviderType = typeof(TSessionStateProviderType);
}
public class BasedPasswordOptions
{
}
public class BasedUserOptions
{
}
public class BasedLockoutOptions
{
}

View File

@@ -1,13 +0,0 @@
using Microsoft.AspNetCore.Components;
using Microsoft.AspNetCore.Components.Web;
namespace DotBased.ASP.Auth;
public static class BasedAuthDefaults
{
public const string AuthenticationScheme = "DotBasedAuthentication";
public const string StorageKey = "dotbased_session";
public static IComponentRenderMode InteractiveServerWithoutPrerender { get; } =
new InteractiveServerRenderMode(prerender: false);
}

View File

@@ -1,40 +0,0 @@
using System.Security.Claims;
using DotBased.Logging;
using Microsoft.AspNetCore.Components.Authorization;
using Microsoft.AspNetCore.Components.Server;
using Microsoft.AspNetCore.Components.Server.ProtectedBrowserStorage;
using ILogger = DotBased.Logging.ILogger;
namespace DotBased.ASP.Auth;
// RevalidatingServerAuthenticationStateProvider
// AuthenticationStateProvider
// Handles roles
public class BasedServerAuthenticationStateProvider : ServerAuthenticationStateProvider
{
public BasedServerAuthenticationStateProvider(BasedAuthConfiguration configuration, ProtectedLocalStorage localStorage, SecurityService securityService)
{
_config = configuration;
_localStorage = localStorage;
_securityService = securityService;
_logger = LogService.RegisterLogger<BasedServerAuthenticationStateProvider>();
}
private BasedAuthConfiguration _config;
private readonly ProtectedLocalStorage _localStorage;
private readonly SecurityService _securityService;
private readonly ILogger _logger;
private readonly AuthenticationState _anonState = new(new ClaimsPrincipal());
public override async Task<AuthenticationState> GetAuthenticationStateAsync()
{
_logger.Debug("Getting authentication state...");
var sessionIdResult = await _localStorage.GetAsync<string>(BasedAuthDefaults.StorageKey);
if (!sessionIdResult.Success || sessionIdResult.Value == null)
return _anonState;
_logger.Debug("Found state [{State}], getting session from {Service}", sessionIdResult.Value, nameof(SecurityService));
var stateResult = await _securityService.GetAuthenticationStateFromSessionAsync(sessionIdResult.Value);
return stateResult is { Success: true, Value: not null } ? stateResult.Value : _anonState;
}
}

View File

@@ -1,25 +0,0 @@
using DotBased.ASP.Auth.Domains.Identity;
namespace DotBased.ASP.Auth.Domains.Auth;
public class AuthenticationStateModel
{
public AuthenticationStateModel(UserModel user)
{
UserId = user.Id;
}
public string Id { get; set; } = Guid.NewGuid().ToString();
public string UserId { get; set; }
public DateTime CreationDate { get; set; } = DateTime.Now;
public override bool Equals(object? obj)
{
if (obj is AuthenticationStateModel authStateModel)
return authStateModel.Id == Id;
return false;
}
// ReSharper disable once NonReadonlyMemberInGetHashCode
public override int GetHashCode() => Id.GetHashCode();
public override string ToString() => Id;
}

View File

@@ -1,8 +0,0 @@
namespace DotBased.ASP.Auth.Domains.Auth;
public class PermissionModel
{
public string Name { get; set; } = string.Empty;
public string Description { get; set; } = string.Empty;
public string Permission { get; set; } = string.Empty;
}

View File

@@ -1,12 +0,0 @@
using DotBased.Objects;
namespace DotBased.ASP.Auth.Domains.Auth;
public class RoleModel
{
public string Id { get; set; } = Guid.NewGuid().ToString();
public string Name { get; set; } = string.Empty;
public string Description { get; set; } = string.Empty;
public List<PermissionModel> Permissions { get; set; } = [];
public List<DbObjectAttribute<IConvertible>> Attributes { get; set; } = [];
}

View File

@@ -1,8 +0,0 @@
namespace DotBased.ASP.Auth.Domains.Identity;
public class GroupItemModel
{
public string Id { get; set; } = Guid.NewGuid().ToString();
public string Name { get; set; } = string.Empty;
public string Description { get; set; } = string.Empty;
}

View File

@@ -1,13 +0,0 @@
using DotBased.ASP.Auth.Domains.Auth;
using DotBased.Objects;
namespace DotBased.ASP.Auth.Domains.Identity;
public class GroupModel
{
public string Id { get; set; } = Guid.NewGuid().ToString();
public string Name { get; set; } = string.Empty;
public string Description { get; set; } = string.Empty;
public List<RoleModel> Roles { get; set; } = [];
public List<DbObjectAttribute<IConvertible>> Attributes { get; set; } = [];
}

View File

@@ -1,10 +0,0 @@
namespace DotBased.ASP.Auth.Domains.Identity;
public class UserItemModel
{
public string Id { get; set; } = string.Empty;
public string UserName { get; set; } = string.Empty;
public string Email { get; set; } = string.Empty;
public string Name { get; set; } = string.Empty;
public string FamilyName { get; set; } = string.Empty;
}

View File

@@ -1,31 +0,0 @@
using DotBased.ASP.Auth.Domains.Auth;
using DotBased.Objects;
namespace DotBased.ASP.Auth.Domains.Identity;
public class UserModel
{
public string UserName { get; set; } = string.Empty;
public string PasswordHash { get; set; } = string.Empty;
public string Email { get; set; } = string.Empty;
public string PhoneNumber { get; set; } = string.Empty;
public string Name { get; set; } = string.Empty;
public string FamilyName { get; set; } = string.Empty;
public DateTime Dob { get; set; }
public string Id { get; set; } = Guid.NewGuid().ToString();
public bool Enabled { get; set; }
public bool EmailValidated { get; set; }
public bool PhoneNumberConfirmed { get; set; }
public bool Lockout { get; set; }
public DateTime LockoutEnd { get; set; }
public DateTime CreationStamp { get; set; }
public DateTime SecurityStamp { get; set; }
public DateTime ConcurrencyStamp { get; set; }
public int AccessFailedCount { get; set; }
public bool ExternalAuthentication { get; set; }
public List<GroupModel> Groups { get; set; } = [];
public List<RoleModel> Roles { get; set; } = [];
public List<DbObjectAttribute<IConvertible>> Attributes { get; set; } = [];
}

View File

@@ -1,8 +0,0 @@
namespace DotBased.ASP.Auth.Domains;
public class LoginModel
{
public string UserName { get; set; } = string.Empty;
public string Email { get; set; } = string.Empty;
public string Password { get; set; } = string.Empty;
}

View File

@@ -1,10 +0,0 @@
namespace DotBased.ASP.Auth.Domains;
public class RegisterModel
{
public string UserName { get; set; } = string.Empty;
public string Email { get; set; } = string.Empty;
public string Password { get; set; } = string.Empty;
public string Name { get; set; } = string.Empty;
public string FamilyName { get; set; } = string.Empty;
}

View File

@@ -1,21 +0,0 @@
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<TargetFramework>net8.0</TargetFramework>
<ImplicitUsings>enable</ImplicitUsings>
<Nullable>enable</Nullable>
</PropertyGroup>
<ItemGroup>
<ProjectReference Include="..\DotBased\DotBased.csproj" />
</ItemGroup>
<ItemGroup>
<FrameworkReference Include="Microsoft.AspNetCore.App" />
</ItemGroup>
<ItemGroup>
<Folder Include="Models\Auth\States\" />
<Folder Include="Models\Repositories\" />
</ItemGroup>
</Project>

View File

@@ -1,55 +0,0 @@
using DotBased.ASP.Auth.Services;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Components.Authorization;
using Microsoft.Extensions.DependencyInjection;
namespace DotBased.ASP.Auth;
public static class DotBasedAuthDependencyInjection
{
/// <summary>
/// Use the DotBased authentication implementation
/// </summary>
/// <remarks>Use UseBasedServerAuth()!</remarks>
/// <param name="services">Service collection</param>
/// <param name="configurationAction">DotBased auth configuration</param>
public static IServiceCollection AddBasedServerAuth(this IServiceCollection services, Action<BasedAuthConfiguration>? configurationAction = null)
{
var Configuration = new BasedAuthConfiguration();
configurationAction?.Invoke(Configuration);
services.AddSingleton<BasedAuthConfiguration>(Configuration);
if (Configuration.AuthDataRepositoryType == null)
throw new ArgumentNullException(nameof(Configuration.AuthDataRepositoryType), $"No '{nameof(IAuthDataRepository)}' configured!");
services.AddScoped(typeof(IAuthDataRepository), Configuration.AuthDataRepositoryType);
services.AddSingleton<AuthDataCache>();
services.AddScoped<SecurityService>();
services.AddScoped<AuthenticationStateProvider, BasedServerAuthenticationStateProvider>();
services.AddAuthentication(options =>
{
options.DefaultScheme = BasedAuthDefaults.AuthenticationScheme;
});
services.AddAuthorization();
services.AddCascadingAuthenticationState();
return services;
}
public static WebApplication UseBasedServerAuth(this WebApplication app)
{
app.UseAuthentication();
app.UseAuthorization();
// Data
var authConfig = app.Services.GetService<BasedAuthConfiguration>();
if (authConfig == null)
throw new NullReferenceException($"{nameof(BasedAuthConfiguration)} is null!");
if (authConfig.AuthDataRepositoryType == null)
throw new NullReferenceException($"{nameof(authConfig.AuthDataRepositoryType)} is null, cannot instantiate an instance of {nameof(IAuthDataRepository)}");
var dataProvider = (IAuthDataRepository?)Activator.CreateInstance(authConfig.AuthDataRepositoryType);
if (dataProvider != null) authConfig.SeedData?.Invoke(dataProvider);
return app;
}
}

View File

@@ -1,22 +0,0 @@
using DotBased.ASP.Auth.Domains.Auth;
using DotBased.ASP.Auth.Domains.Identity;
namespace DotBased.ASP.Auth;
public interface IAuthDataRepository
{
public Task<ResultOld> CreateUserAsync(UserModel user);
public Task<ResultOld> UpdateUserAsync(UserModel user);
public Task<ResultOld> DeleteUserAsync(UserModel user);
public Task<ResultOld<UserModel>> GetUserAsync(string id, string email, string username);
public Task<ListResultOld<UserItemModel>> GetUsersAsync(int start = 0, int amount = 30, string search = "");
public Task<ResultOld> CreateGroupAsync(GroupModel group);
public Task<ResultOld> UpdateGroupAsync(GroupModel group);
public Task<ResultOld> DeleteGroupAsync(GroupModel group);
public Task<ResultOld<GroupModel>> GetGroupAsync(string id);
public Task<ListResultOld<GroupItemModel>> GetGroupsAsync(int start = 0, int amount = 30, string search = "");
public Task<ResultOld> CreateAuthenticationStateAsync(AuthenticationStateModel authenticationState);
public Task<ResultOld> UpdateAuthenticationStateAsync(AuthenticationStateModel authenticationState);
public Task<ResultOld> DeleteAuthenticationStateAsync(AuthenticationStateModel authenticationState);
public Task<ResultOld<AuthenticationStateModel>> GetAuthenticationStateAsync(string id);
}

View File

@@ -1,8 +0,0 @@
namespace DotBased.ASP.Auth;
public interface ISessionStateProvider
{
public const string SessionStateName = "BasedServerSession";
public Task<ResultOld<string>> GetSessionStateAsync();
public Task<ResultOld> SetSessionStateAsync(string state);
}

View File

@@ -1,107 +0,0 @@
using System.Diagnostics.CodeAnalysis;
using DotBased.ASP.Auth.Domains.Auth;
using DotBased.ASP.Auth.Domains.Identity;
using DotBased.Extensions;
namespace DotBased.ASP.Auth;
/// <summary>
/// In memory data provider, for testing only!
/// </summary>
[SuppressMessage("ReSharper", "CollectionNeverUpdated.Local")]
public class MemoryAuthDataRepository : IAuthDataRepository
{
public async Task<ResultOld> CreateUserAsync(UserModel user)
{
if (MemoryData.users.Any(x => x.Id == user.Id || x.Email == user.Email))
return ResultOld.Failed("User already exists.");
MemoryData.users.Add(user);
return ResultOld.Ok();
}
public async Task<ResultOld> UpdateUserAsync(UserModel user)
{
if (MemoryData.users.All(x => x.Id != user.Id))
return ResultOld.Failed("User does not exist!");
return ResultOld.Ok();
}
public Task<ResultOld> DeleteUserAsync(UserModel user)
{
throw new NotImplementedException();
}
public async Task<ResultOld<UserModel>> GetUserAsync(string id, string email, string username)
{
UserModel? userModel = null;
if (!id.IsNullOrEmpty())
userModel = MemoryData.users.FirstOrDefault(u => u.Id.Equals(id, StringComparison.OrdinalIgnoreCase));
if (!email.IsNullOrEmpty())
userModel = MemoryData.users.FirstOrDefault(u => u.Email.Equals(email, StringComparison.OrdinalIgnoreCase));
if (!username.IsNullOrEmpty())
userModel = MemoryData.users.FirstOrDefault(u => u.UserName.Equals(username, StringComparison.OrdinalIgnoreCase));
return userModel != null ? ResultOld<UserModel>.Ok(userModel) : ResultOld<UserModel>.Failed("No user found!");
}
public Task<ListResultOld<UserItemModel>> GetUsersAsync(int start = 0, int amount = 30, string search = "")
{
throw new NotImplementedException();
}
public Task<ResultOld> CreateGroupAsync(GroupModel group)
{
throw new NotImplementedException();
}
public Task<ResultOld> UpdateGroupAsync(GroupModel group)
{
throw new NotImplementedException();
}
public Task<ResultOld> DeleteGroupAsync(GroupModel group)
{
throw new NotImplementedException();
}
public Task<ResultOld<GroupModel>> GetGroupAsync(string id)
{
throw new NotImplementedException();
}
public Task<ListResultOld<GroupItemModel>> GetGroupsAsync(int start = 0, int amount = 30, string search = "")
{
throw new NotImplementedException();
}
public async Task<ResultOld> CreateAuthenticationStateAsync(AuthenticationStateModel authenticationState)
{
if (MemoryData.AuthenticationStates.Contains(authenticationState)) return ResultOld.Failed("Item already exists!");
MemoryData.AuthenticationStates.Add(authenticationState);
return ResultOld.Ok();
}
public Task<ResultOld> UpdateAuthenticationStateAsync(AuthenticationStateModel authenticationState)
{
throw new NotImplementedException();
}
public async Task<ResultOld> DeleteAuthenticationStateAsync(AuthenticationStateModel authenticationState)
{
MemoryData.AuthenticationStates.Remove(authenticationState);
return ResultOld.Ok();
}
public async Task<ResultOld<AuthenticationStateModel>> GetAuthenticationStateAsync(string id)
{
var item = MemoryData.AuthenticationStates.FirstOrDefault(x => x.Id == id);
if (item == null) return ResultOld<AuthenticationStateModel>.Failed("Could not get the session state!");
return ResultOld<AuthenticationStateModel>.Ok(item);
}
}
internal static class MemoryData
{
public static readonly List<UserModel> users = [];
public static readonly List<GroupModel> Groups = [];
public static readonly List<AuthenticationStateModel> AuthenticationStates = [];
}

View File

@@ -1,11 +0,0 @@
namespace DotBased.ASP.Auth.Models.Configuration;
public class AuthConfiguration
{
public CacheConfiguration Cache { get; set; } = new();
public LockoutConfiguration Lockout { get; set; } = new();
public PasswordConfiguration Password { get; set; } = new();
public ProviderConfiguration Provider { get; set; } = new();
public RepositoryConfiguration Repository { get; set; } = new();
public UserConfiguration User { get; set; } = new();
}

View File

@@ -1,6 +0,0 @@
namespace DotBased.ASP.Auth.Models.Configuration;
public class CacheConfiguration
{
}

View File

@@ -1,6 +0,0 @@
namespace DotBased.ASP.Auth.Models.Configuration;
public class LockoutConfiguration
{
}

View File

@@ -1,6 +0,0 @@
namespace DotBased.ASP.Auth.Models.Configuration;
public class PasswordConfiguration
{
}

View File

@@ -1,6 +0,0 @@
namespace DotBased.ASP.Auth.Models.Configuration;
public class ProviderConfiguration
{
}

View File

@@ -1,6 +0,0 @@
namespace DotBased.ASP.Auth.Models.Configuration;
public class RepositoryConfiguration
{
}

View File

@@ -1,6 +0,0 @@
namespace DotBased.ASP.Auth.Models.Configuration;
public class UserConfiguration
{
}

View File

@@ -1,9 +0,0 @@
namespace DotBased.ASP.Auth.Managers;
public class SecurityManager
{
public SecurityManager()
{
}
}

View File

@@ -1,137 +0,0 @@
using System.Security.Claims;
using DotBased.ASP.Auth.Domains;
using DotBased.ASP.Auth.Domains.Auth;
using DotBased.ASP.Auth.Domains.Identity;
using DotBased.Extensions;
using DotBased.Logging;
using Microsoft.AspNetCore.Components.Authorization;
using Microsoft.AspNetCore.Components.Server.ProtectedBrowserStorage;
namespace DotBased.ASP.Auth;
public class SecurityService
{
public SecurityService(IAuthDataRepository authDataRepository, AuthDataCache dataCache, ProtectedLocalStorage localStorage)
{
_authDataRepository = authDataRepository;
_dataCache = dataCache;
_localStorage = localStorage;
_logger = LogService.RegisterLogger<SecurityService>();
}
private readonly IAuthDataRepository _authDataRepository;
private readonly AuthDataCache _dataCache;
private readonly ProtectedLocalStorage _localStorage;
private readonly ILogger _logger;
public async Task<ResultOld<AuthenticationState>> GetAuthenticationStateFromSessionAsync(string id)
{
if (id.IsNullOrEmpty())
return ResultOld<AuthenticationState>.Failed("No valid id!");
AuthenticationStateModel? authStateModel = null;
var stateCache = _dataCache.RequestSessionState(id);
if (!stateCache.Success || stateCache.Value == null)
{
var stateResult = await _authDataRepository.GetAuthenticationStateAsync(id);
if (stateResult is { Success: true, Value: not null })
{
authStateModel = stateResult.Value;
_dataCache.CacheSessionState(authStateModel);
}
}
else
{
if (stateCache.Value.Item2 != null)
return ResultOld<AuthenticationState>.Ok(stateCache.Value.Item2);
authStateModel = stateCache.Value.Item1;
}
if (authStateModel == null)
return ResultOld<AuthenticationState>.Failed("Failed to get auth state!");
var userResult = await _authDataRepository.GetUserAsync(authStateModel.UserId, string.Empty, string.Empty);
if (userResult is not { Success: true, Value: not null })
return ResultOld<AuthenticationState>.Failed("Failed to get user from state!");
var claims = new List<Claim>()
{
new(ClaimTypes.Sid, userResult.Value.Id),
new(ClaimTypes.Name, userResult.Value.Name),
new(ClaimTypes.NameIdentifier, userResult.Value.UserName),
new(ClaimTypes.Surname, userResult.Value.FamilyName),
new(ClaimTypes.Email, userResult.Value.Email)
};
claims.AddRange(userResult.Value.Groups.Select(group => new Claim(ClaimTypes.GroupSid, group.Id)));
claims.AddRange(userResult.Value.Roles.Select(role => new Claim(ClaimTypes.Role, role.Name)));
claims.AddRange(userResult.Value.Groups.Select(g => g.Roles).SelectMany(gRolesList => gRolesList, (_, role) => new Claim(ClaimTypes.Role, role.Name)));
var claimsIdentity = new ClaimsIdentity(claims, BasedAuthDefaults.AuthenticationScheme);
var authState = new AuthenticationState(new ClaimsPrincipal(claimsIdentity));
_dataCache.CacheSessionState(authStateModel, authState);
return ResultOld<AuthenticationState>.Ok(authState);
}
public async Task<ResultOld<AuthenticationStateModel>> LoginAsync(LoginModel login)
{
try
{
UserModel? user = null;
ResultOld<UserModel> usrResultOld;
if (!login.UserName.IsNullOrEmpty())
{
usrResultOld = await _authDataRepository.GetUserAsync(string.Empty, string.Empty, login.UserName);
if (usrResultOld is { Success: true, Value: not null })
user = usrResultOld.Value;
}
else if (!login.Email.IsNullOrEmpty())
{
usrResultOld = await _authDataRepository.GetUserAsync(string.Empty, login.Email, string.Empty);
if (usrResultOld is { Success: true, Value: not null })
user = usrResultOld.Value;
}
else
return ResultOld<AuthenticationStateModel>.Failed("Username & Email is empty, cannot login!");
if (user == null || !usrResultOld.Success)
return ResultOld<AuthenticationStateModel>.Failed("No user found!");
if (user.PasswordHash != login.Password) //TODO: Hash password and compare
return ResultOld<AuthenticationStateModel>.Failed("Login failed, invalid password.");
var state = new AuthenticationStateModel(user);
var authResult = await _authDataRepository.CreateAuthenticationStateAsync(state);
if (!authResult.Success)
return ResultOld<AuthenticationStateModel>.Failed("Failed to store session to database!");
_dataCache.CacheSessionState(state);
await _localStorage.SetAsync(BasedAuthDefaults.StorageKey, state.Id);
return ResultOld<AuthenticationStateModel>.Ok(state);
}
catch (Exception e)
{
_logger.Error(e, "Failed to login!");
return ResultOld<AuthenticationStateModel>.Failed("Login failed, exception thrown!");
}
}
public async Task<ResultOld> LogoutAsync(string state)
{
try
{
if (state.IsNullOrEmpty())
return ResultOld.Failed($"Argument {nameof(state)} is empty!");
var stateResult = await _authDataRepository.GetAuthenticationStateAsync(state);
if (!stateResult.Success || stateResult.Value == null)
return stateResult;
var authState = stateResult.Value;
_dataCache.PurgeSessionState(state);
var updatedStateResult = await _authDataRepository.DeleteAuthenticationStateAsync(authState);
if (updatedStateResult.Success) return updatedStateResult;
_logger.Warning(updatedStateResult.Message);
return updatedStateResult;
}
catch (Exception e)
{
_logger.Error(e, "Failed to logout!");
return ResultOld.Failed("Failed to logout, exception thrown!");
}
}
}

View File

@@ -4,15 +4,20 @@ public static class AuthorityDefaults
{
public static class Scheme
{
public static class Authority
{
public const string AuthenticationScheme = "AuthorityLogin";
}
public static class Cookie
{
public const string Default = "Authority.Scheme.Cookie";
public const string AuthenticationScheme = "AuthorityCookie";
public const string CookieName = "AuthorityAuth";
}
public static class Token
{
public const string Default = "Authority.Scheme.Token";
public const string AuthenticationScheme = "AuthorityToken";
public const string TokenName = "AuthorityAuthToken";
}
}
@@ -22,6 +27,14 @@ public static class AuthorityDefaults
public const string Default = "/";
public const string Login = "/auth/login";
public const string Logout = "/auth/logout";
public const string Challenge = "/auth/challenge";
public const string Forbidden = "/forbidden";
public const string Info = "/info";
}
public static class ClaimTypes
{
public const string Attribute = "Authority.Attribute";
public const string AuthenticatedScheme = "Authority.Scheme.Authenticated";
}
}

View File

@@ -1,4 +1,5 @@
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;
@@ -33,21 +34,41 @@ public static class AuthorityProviderExtensions
return new AuthorityBuilder(services);
}
public static AuthenticationBuilder AddAuthorityAuth(this AuthorityBuilder builder) => AddAuthorityAuth(builder, _ => { });
public static AuthenticationBuilder AddAuthorityAuth(this AuthorityBuilder builder, Action<AuthorityAuthenticationOptions> configureOptions)
{
ArgumentNullException.ThrowIfNull(configureOptions);
builder.Services.Configure(configureOptions);
builder.Services.AddScoped<IAuthenticationService, AuthorityAuthenticationService>();
var authBuilder = builder.Services.AddAuthentication();
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 AddAuthorityCookie(this AuthenticationBuilder builder, string scheme = AuthorityDefaults.Scheme.Cookie.Default)
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.AddCookie(options =>
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;
@@ -63,17 +84,12 @@ public static class AuthorityProviderExtensions
return builder;
}
public static AuthenticationBuilder AddAuthorityToken(this AuthenticationBuilder builder, string scheme = AuthorityDefaults.Scheme.Token.Default)
public static AuthenticationBuilder AddAuthorityToken(this AuthenticationBuilder builder, string scheme)
{
return builder;
}
public static AuthorityBuilder AddAuthorityRepository<TRepository>(this AuthorityBuilder authorityBuilder) where TRepository : class
{
return authorityBuilder;
}
public static AuthorityBuilder MapAuthorityEndpoints(this AuthorityBuilder builder)
{
return builder;

View File

@@ -1,10 +1,59 @@
using System.Text.Json;
using DotBased.AspNet.Authority.Models.Data.System;
using DotBased.AspNet.Authority.Services;
using Microsoft.AspNetCore.Authentication;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
namespace DotBased.AspNet.Authority.Controllers;
[ApiController]
[Route("[controller]")]
public class AuthorityController : ControllerBase
public class AuthorityController(IAuthenticationService authenticationService) : ControllerBase
{
[HttpGet(AuthorityDefaults.Paths.Login)]
[AllowAnonymous]
public async Task<ActionResult> LoginFromSchemeAsync([FromQuery(Name = "s")] string? scheme, [FromQuery(Name = "ss")] string? sessionScheme)
{
await authenticationService.AuthenticateAsync(HttpContext, scheme);
return Ok();
}
[HttpGet(AuthorityDefaults.Paths.Challenge)]
[AllowAnonymous]
public IActionResult ChallengeLogin([FromQuery(Name = "s")] string? scheme, [FromQuery(Name = "returnUrl")] string returnUrl = "/")
{
return Challenge(scheme, returnUrl);
}
[HttpGet(AuthorityDefaults.Paths.Logout)]
public async Task<ActionResult> LogoutAsync()
{
await HttpContext.SignOutAsync();
return Ok();
}
[HttpGet(AuthorityDefaults.Paths.Info)]
[AllowAnonymous]
public async Task<ActionResult<JsonDocument>> GetAuthorityInfoAsync()
{
if (authenticationService is not AuthorityAuthenticationService authService)
{
return BadRequest();
}
var schemesInfos = authService.GetAllSchemeInfos();
var info = new AuthorityInformation
{
IsAuthenticated = false,
SchemeInformation = new SchemeInformation
{
DefaultScheme = authService.Options.DefaultScheme ?? "Unknown",
AvailableSchemes = schemesInfos.ToList()
}
};
return Ok(info);
}
}

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>
@@ -22,10 +20,7 @@
</ItemGroup>
<ItemGroup>
<PackageReference Include="Microsoft.AspNetCore.Authentication" Version="2.3.0" />
<PackageReference Include="Microsoft.AspNetCore.Authentication.Cookies" Version="2.3.0" />
<PackageReference Include="Microsoft.AspNetCore.Mvc" Version="2.3.0" />
<PackageReference Include="Microsoft.Extensions.Options" Version="9.0.0" />
<PackageReference Include="Microsoft.Extensions.Options" Version="8.0.2" />
</ItemGroup>
</Project>

View File

@@ -1,38 +0,0 @@
using System.Security.Claims;
using Microsoft.AspNetCore.Authentication;
using Microsoft.AspNetCore.Http;
namespace DotBased.AspNet.Authority.Handlers;
public class AuthorityAuthenticationHandler : IAuthenticationHandler, IAuthenticationSignInHandler, IAuthenticationSignOutHandler
{
public Task InitializeAsync(AuthenticationScheme scheme, HttpContext context)
{
throw new NotImplementedException();
}
public Task<AuthenticateResult> AuthenticateAsync()
{
throw new NotImplementedException();
}
public Task ChallengeAsync(AuthenticationProperties properties)
{
throw new NotImplementedException();
}
public Task ForbidAsync(AuthenticationProperties properties)
{
throw new NotImplementedException();
}
public Task SignOutAsync(AuthenticationProperties properties)
{
throw new NotImplementedException();
}
public Task SignInAsync(ClaimsPrincipal user, AuthenticationProperties properties)
{
throw new NotImplementedException();
}
}

View File

@@ -0,0 +1,102 @@
using System.Buffers.Text;
using System.Net.Http.Headers;
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;
using Microsoft.Extensions.Primitives;
namespace DotBased.AspNet.Authority.Handlers;
/// <summary>
/// Handles authentication for Authority logins.
/// </summary>
public class AuthorityLoginAuthenticationHandler(IOptionsMonitor<AuthorityLoginOptions> options,
ILoggerFactory logger,
UrlEncoder encoder,
AuthorityManager manager) : AuthenticationHandler<AuthorityLoginOptions>(options, logger, encoder)
{
// Validate credentials
protected override async Task<AuthenticateResult> HandleAuthenticateAsync()
{
var authResult = GetBasicAuthorization(out var email, out var password);
if (authResult != null || string.IsNullOrEmpty(email) || string.IsNullOrEmpty(password))
{
return AuthenticateResult.Fail(authResult ?? "Failed to get basic authorization from header.");
}
var userResult = await manager.GetUserByEmailAsync(email);
if (userResult is { IsSuccess: false, Error: not null })
{
return AuthenticateResult.Fail(userResult.Error.Description);
}
var user = userResult.Value;
var passwordValidateResult = await manager.ValidatePasswordAsync(user, password);
if (!passwordValidateResult.IsSuccess)
{
return AuthenticateResult.Fail(passwordValidateResult.Error?.Description ?? "Failed to validate password.");
}
var identityClaims = new List<Claim>();
var rolesResult = await manager.GetAllUserRolesAsync(user);
if (rolesResult.IsSuccess)
{
var roles = rolesResult.Value;
foreach (var authorityRole in roles)
{
identityClaims.Add(new Claim(ClaimTypes.Role, authorityRole.Name));
}
}
var principal = new ClaimsPrincipal(new ClaimsIdentity(identityClaims, Scheme.Name));
var ticket = new AuthenticationTicket(principal, Scheme.Name);
var result = AuthenticateResult.Success(ticket);
return result;
}
private string? GetBasicAuthorization(out string? email, out string? password)
{
email = null;
password = null;
if (StringValues.IsNullOrEmpty(Context.Request.Headers.Authorization))
{
return "Missing authorization header";
}
var basicAuth = string.Empty;
foreach (var authorizationValue in Context.Request.Headers.Authorization)
{
if (string.IsNullOrWhiteSpace(authorizationValue))
{
continue;
}
if (AuthenticationHeaderValue.TryParse(authorizationValue, out var basicAuthHeader) && !string.IsNullOrWhiteSpace(basicAuthHeader.Parameter))
{
basicAuth = basicAuthHeader.Parameter;
}
}
if (!Base64.IsValid(basicAuth))
{
return "Invalid basic authorization data!";
}
var base64Auth = Convert.FromBase64String(basicAuth);
var decodedAuth = System.Text.Encoding.UTF8.GetString(base64Auth);
var parts = decodedAuth.Split(':');
if (parts.Length != 2)
{
return "No email and/or password found!";
}
email = parts[0];
password = parts[1];
return null;
}
}

View File

@@ -36,6 +36,22 @@ public partial class AuthorityManager
return errors.Count > 0 ? ValidationResult.Fail(errors) : ValidationResult.Success();
}
public async Task<Result<AuthorityUser>> GetUserByEmailAsync(string email)
{
if (string.IsNullOrEmpty(email))
{
return ResultError.Fail("No email given.");
}
var user = await userRepository.GetUserByEmailAsync(email);
if (user == null)
{
return ResultError.Fail("No user found with given email.");
}
return user;
}
public async Task<Result<QueryItems<AuthorityUserItem>>> SearchUsersAsync(string query, int maxResults = 20, int offset = 0, CancellationToken cancellationToken = default)
{
var result = await UserRepository.GetUsersAsync(maxResults, offset, query, cancellationToken);

View File

@@ -1,10 +0,0 @@
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,25 @@
using DotBased.AspNet.Authority.Models.Data.Auth;
using DotBased.AspNet.Authority.Models.Options.Auth;
namespace DotBased.AspNet.Authority.Models.Data.System;
public class AuthorityInformation
{
public string ServerName { get; set; } = "Authority.Server";
public bool IsAuthenticated { get; set; }
public List<AuthenticationType> AuthenticationTypes { get; set; } = [];
public List<AuthenticationSessionType> SessionTypes { get; set; } = [];
public SchemeInformation? SchemeInformation { get; set; }
public AuthenticatedInformation? AuthenticatedInformation { get; set; }
}
public class SchemeInformation
{
public string? DefaultScheme { get; set; }
public List<SchemeInfo> AvailableSchemes { get; set; } = [];
}
public class AuthenticatedInformation
{
public string? AuthenticatedScheme { get; set; }
}

View File

@@ -5,4 +5,28 @@ 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 string? Endpoint { get; set; }
}
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

@@ -1,20 +1,56 @@
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) : AuthenticationService(schemes, handlers, transform)
public class AuthorityAuthenticationService(
IAuthenticationSchemeProvider schemes,
IAuthenticationHandlerProvider handlers,
IClaimsTransformation transform,
IOptions<AuthenticationOptions> options,
IOptions<AuthorityAuthenticationOptions> authorityOptions) : AuthenticationService(schemes, handlers, transform, options)
{
public override Task SignInAsync(HttpContext context, string scheme, ClaimsPrincipal principal, AuthenticationProperties properties)
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;
// Validate credentials
// Used internally by ASP.NET Core to determine if a user is authenticated. Can also be called manually to inspect authentication status.
public override Task<AuthenticateResult> AuthenticateAsync(HttpContext context, string? scheme)
{
return base.AuthenticateAsync(context, scheme);
}
// Trigger login - Redirects to provider (OIDC, etc.)
// Used when access to a resource requires authentication, but the user has not provided valid credentials.
public override Task ChallengeAsync(HttpContext context, string? scheme, AuthenticationProperties? properties)
{
return base.ChallengeAsync(context, scheme, properties);
}
// Log user in, set cookie/token
// Called after successfully validating user credentials (e.g., after login form submission), to establish an authenticated session.
public override Task SignInAsync(HttpContext context, string? scheme, ClaimsPrincipal principal, AuthenticationProperties? properties)
{
//TODO: Get from query parameters which auth scheme to use or fallback to configured default.
return base.SignInAsync(context, scheme, principal, properties);
}
public override Task SignOutAsync(HttpContext context, string scheme, AuthenticationProperties properties)
// Log out user and end auth session, remove cookie/token
public override Task SignOutAsync(HttpContext context, string? scheme, AuthenticationProperties? properties)
{
//TODO: Figure out which type of auth is used and logout with the scheme.
return base.SignOutAsync(context, scheme, properties);
}
// Deny access, return 403/return forbid page
// Used when a user is authenticated but lacks required roles/claims/permissions.
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

@@ -8,8 +8,6 @@ Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "DotBased.Logging.Serilog",
EndProject
Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "Modules", "Modules", "{2156FB93-C252-4B33-8A0C-73C82FABB163}"
EndProject
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "DotBased.ASP.Auth", "DotBased.ASP.Auth\DotBased.ASP.Auth.csproj", "{CBD4111D-F1CA-466A-AC73-9EAB7F235B3D}"
EndProject
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "DotBased.Logging.MEL", "DotBased.Logging.MEL\DotBased.Logging.MEL.csproj", "{D4D9B584-A524-4CBB-9B61-9CD65ED4AF0D}"
EndProject
Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "Test", "Test", "{DBDB4538-85D4-45AC-9E0A-A684467AEABA}"
@@ -22,8 +20,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
@@ -44,10 +40,6 @@ Global
{EBBDAF9A-BFC7-4BDC-8C51-0501B59A1DDC}.Debug|Any CPU.Build.0 = Debug|Any CPU
{EBBDAF9A-BFC7-4BDC-8C51-0501B59A1DDC}.Release|Any CPU.ActiveCfg = Release|Any CPU
{EBBDAF9A-BFC7-4BDC-8C51-0501B59A1DDC}.Release|Any CPU.Build.0 = Release|Any CPU
{CBD4111D-F1CA-466A-AC73-9EAB7F235B3D}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{CBD4111D-F1CA-466A-AC73-9EAB7F235B3D}.Debug|Any CPU.Build.0 = Debug|Any CPU
{CBD4111D-F1CA-466A-AC73-9EAB7F235B3D}.Release|Any CPU.ActiveCfg = Release|Any CPU
{CBD4111D-F1CA-466A-AC73-9EAB7F235B3D}.Release|Any CPU.Build.0 = Release|Any CPU
{D4D9B584-A524-4CBB-9B61-9CD65ED4AF0D}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{D4D9B584-A524-4CBB-9B61-9CD65ED4AF0D}.Debug|Any CPU.Build.0 = Debug|Any CPU
{D4D9B584-A524-4CBB-9B61-9CD65ED4AF0D}.Release|Any CPU.ActiveCfg = Release|Any CPU
@@ -64,10 +56,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
@@ -75,13 +63,11 @@ Global
EndGlobalSection
GlobalSection(NestedProjects) = preSolution
{EBBDAF9A-BFC7-4BDC-8C51-0501B59A1DDC} = {2156FB93-C252-4B33-8A0C-73C82FABB163}
{CBD4111D-F1CA-466A-AC73-9EAB7F235B3D} = {2156FB93-C252-4B33-8A0C-73C82FABB163}
{D4D9B584-A524-4CBB-9B61-9CD65ED4AF0D} = {2156FB93-C252-4B33-8A0C-73C82FABB163}
{BADA4BAF-142B-47A8-95FC-B25E1D3D0020} = {DBDB4538-85D4-45AC-9E0A-A684467AEABA}
{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

@@ -27,4 +27,9 @@ public class WeatherController : ControllerBase
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;
@@ -24,12 +25,52 @@ builder.Logging.AddDotBasedLoggerProvider(LogService.Options);
builder.Services.AddControllers();
builder.Services.AddAuthority().AddAuthorityContext(options =>
builder.Services.AddAuthority()
.AddAuthorityContext(options =>
{
options.UseSqlite("Data Source=dev-authority.db", c => c.MigrationsAssembly("TestWebApi"));
}).AddAuthorityAuth()
.AddAuthorityCookie()
.AddAuthorityToken();
})
.MapAuthorityEndpoints()
.AddAuthorityAuth(options =>
{
options.DefaultScheme = AuthorityDefaults.Scheme.Authority.AuthenticationScheme;
options.DefaultAuthenticateScheme = AuthorityDefaults.Scheme.Authority.AuthenticationScheme;
options.DefaultSignInScheme = AuthorityDefaults.Scheme.Cookie.AuthenticationScheme;
options.DefaultSignOutScheme = AuthorityDefaults.Scheme.Cookie.AuthenticationScheme;
options.SchemeInfoMap = [
new SchemeInfo
{
Scheme = AuthorityDefaults.Scheme.Authority.AuthenticationScheme,
Description = "Authority password login",
Type = SchemeType.Authentication,
AuthenticationType = "Password",
Endpoint = AuthorityDefaults.Paths.Login
},
/*new SchemeInfo
{
Scheme = "OIDC",
Description = "Authentik OIDC login",
Type = SchemeType.Authentication,
AuthenticationType = "OpenIdConnect",
Endpoint = AuthorityDefaults.Paths.Challenge
},*/
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
@@ -62,9 +103,4 @@ ILogger SetupSerilog()
.MinimumLevel.Verbose()
.WriteTo.Console(outputTemplate: BasedSerilog.OutputTemplate);
return logConfig.CreateLogger();
}
public record WeatherForecast(DateOnly Date, int TemperatureC, string? Summary)
{
public int TemperatureF => 32 + (int)(TemperatureC / 0.5556);
}

View File

@@ -25,4 +25,8 @@
<ProjectReference Include="..\DotBased\DotBased.csproj" />
</ItemGroup>
<ItemGroup>
<Folder Include="Migrations\" />
</ItemGroup>
</Project>