Compare commits
10 Commits
e6d7578d49
...
333cf66cb4
Author | SHA1 | Date | |
---|---|---|---|
|
333cf66cb4 | ||
|
217c55df00 | ||
|
b3763fb795 | ||
|
c225576c44 | ||
|
46dbd8c6f5 | ||
|
05b95c6050 | ||
|
edf8891ddc | ||
|
723c654d70 | ||
|
e22b7790dd | ||
|
d69359e937 |
@@ -4,15 +4,20 @@ public static class AuthorityDefaults
|
|||||||
{
|
{
|
||||||
public static class Scheme
|
public static class Scheme
|
||||||
{
|
{
|
||||||
|
public static class Authority
|
||||||
|
{
|
||||||
|
public const string AuthenticationScheme = "AuthorityLogin";
|
||||||
|
}
|
||||||
|
|
||||||
public static class Cookie
|
public static class Cookie
|
||||||
{
|
{
|
||||||
public const string Default = "Authority.Scheme.Cookie";
|
public const string AuthenticationScheme = "AuthorityCookie";
|
||||||
public const string CookieName = "AuthorityAuth";
|
public const string CookieName = "AuthorityAuth";
|
||||||
}
|
}
|
||||||
|
|
||||||
public static class Token
|
public static class Token
|
||||||
{
|
{
|
||||||
public const string Default = "Authority.Scheme.Token";
|
public const string AuthenticationScheme = "AuthorityToken";
|
||||||
public const string TokenName = "AuthorityAuthToken";
|
public const string TokenName = "AuthorityAuthToken";
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -22,6 +27,14 @@ public static class AuthorityDefaults
|
|||||||
public const string Default = "/";
|
public const string Default = "/";
|
||||||
public const string Login = "/auth/login";
|
public const string Login = "/auth/login";
|
||||||
public const string Logout = "/auth/logout";
|
public const string Logout = "/auth/logout";
|
||||||
|
public const string Challenge = "/auth/challenge";
|
||||||
public const string Forbidden = "/forbidden";
|
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";
|
||||||
}
|
}
|
||||||
}
|
}
|
@@ -1,4 +1,5 @@
|
|||||||
using DotBased.AspNet.Authority.Crypto;
|
using DotBased.AspNet.Authority.Crypto;
|
||||||
|
using DotBased.AspNet.Authority.Handlers;
|
||||||
using DotBased.AspNet.Authority.Managers;
|
using DotBased.AspNet.Authority.Managers;
|
||||||
using DotBased.AspNet.Authority.Models.Options;
|
using DotBased.AspNet.Authority.Models.Options;
|
||||||
using DotBased.AspNet.Authority.Models.Options.Auth;
|
using DotBased.AspNet.Authority.Models.Options.Auth;
|
||||||
@@ -33,21 +34,41 @@ public static class AuthorityProviderExtensions
|
|||||||
return new AuthorityBuilder(services);
|
return new AuthorityBuilder(services);
|
||||||
}
|
}
|
||||||
|
|
||||||
public static AuthenticationBuilder AddAuthorityAuth(this AuthorityBuilder builder) => AddAuthorityAuth(builder, _ => { });
|
|
||||||
|
|
||||||
public static AuthenticationBuilder AddAuthorityAuth(this AuthorityBuilder builder, Action<AuthorityAuthenticationOptions> configureOptions)
|
public static AuthenticationBuilder AddAuthorityAuth(this AuthorityBuilder builder, Action<AuthorityAuthenticationOptions> configureOptions)
|
||||||
{
|
{
|
||||||
ArgumentNullException.ThrowIfNull(configureOptions);
|
ArgumentNullException.ThrowIfNull(configureOptions);
|
||||||
builder.Services.Configure(configureOptions);
|
builder.Services.Configure(configureOptions);
|
||||||
|
|
||||||
builder.Services.AddScoped<IAuthenticationService, AuthorityAuthenticationService>();
|
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;
|
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.Name = AuthorityDefaults.Scheme.Cookie.CookieName;
|
||||||
options.Cookie.Path = AuthorityDefaults.Paths.Default;
|
options.Cookie.Path = AuthorityDefaults.Paths.Default;
|
||||||
@@ -63,17 +84,12 @@ public static class AuthorityProviderExtensions
|
|||||||
return builder;
|
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;
|
return builder;
|
||||||
}
|
}
|
||||||
|
|
||||||
public static AuthorityBuilder AddAuthorityRepository<TRepository>(this AuthorityBuilder authorityBuilder) where TRepository : class
|
|
||||||
{
|
|
||||||
return authorityBuilder;
|
|
||||||
}
|
|
||||||
|
|
||||||
public static AuthorityBuilder MapAuthorityEndpoints(this AuthorityBuilder builder)
|
public static AuthorityBuilder MapAuthorityEndpoints(this AuthorityBuilder builder)
|
||||||
{
|
{
|
||||||
return builder;
|
return builder;
|
||||||
|
@@ -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;
|
using Microsoft.AspNetCore.Mvc;
|
||||||
|
|
||||||
namespace DotBased.AspNet.Authority.Controllers;
|
namespace DotBased.AspNet.Authority.Controllers;
|
||||||
|
|
||||||
[ApiController]
|
[ApiController]
|
||||||
[Route("[controller]")]
|
[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);
|
||||||
|
}
|
||||||
}
|
}
|
@@ -7,9 +7,7 @@
|
|||||||
</PropertyGroup>
|
</PropertyGroup>
|
||||||
|
|
||||||
<ItemGroup>
|
<ItemGroup>
|
||||||
<Reference Include="Microsoft.Extensions.DependencyInjection.Abstractions">
|
<FrameworkReference Include="Microsoft.AspNetCore.App" />
|
||||||
<HintPath>..\..\..\.nuget\packages\microsoft.extensions.dependencyinjection.abstractions\8.0.2\lib\net8.0\Microsoft.Extensions.DependencyInjection.Abstractions.dll</HintPath>
|
|
||||||
</Reference>
|
|
||||||
</ItemGroup>
|
</ItemGroup>
|
||||||
|
|
||||||
<ItemGroup>
|
<ItemGroup>
|
||||||
@@ -22,10 +20,7 @@
|
|||||||
</ItemGroup>
|
</ItemGroup>
|
||||||
|
|
||||||
<ItemGroup>
|
<ItemGroup>
|
||||||
<PackageReference Include="Microsoft.AspNetCore.Authentication" Version="2.3.0" />
|
<PackageReference Include="Microsoft.Extensions.Options" Version="8.0.2" />
|
||||||
<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" />
|
|
||||||
</ItemGroup>
|
</ItemGroup>
|
||||||
|
|
||||||
</Project>
|
</Project>
|
||||||
|
@@ -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();
|
|
||||||
}
|
|
||||||
}
|
|
@@ -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;
|
||||||
|
}
|
||||||
|
}
|
@@ -36,6 +36,22 @@ public partial class AuthorityManager
|
|||||||
return errors.Count > 0 ? ValidationResult.Fail(errors) : ValidationResult.Success();
|
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)
|
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);
|
var result = await UserRepository.GetUsersAsync(maxResults, offset, query, cancellationToken);
|
||||||
|
@@ -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; } = [];
|
|
||||||
}
|
|
@@ -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; }
|
||||||
|
}
|
@@ -5,4 +5,28 @@ public class AuthorityAuthenticationOptions
|
|||||||
public AuthenticationSecurityOptions Security { get; set; } = new AuthenticationSecurityOptions();
|
public AuthenticationSecurityOptions Security { get; set; } = new AuthenticationSecurityOptions();
|
||||||
public SessionOptions Session { get; set; } = new SessionOptions();
|
public SessionOptions Session { get; set; } = new SessionOptions();
|
||||||
public string DefaultScheme { get; set; } = string.Empty;
|
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
|
||||||
}
|
}
|
@@ -0,0 +1,8 @@
|
|||||||
|
using Microsoft.AspNetCore.Authentication;
|
||||||
|
|
||||||
|
namespace DotBased.AspNet.Authority.Models.Options.Auth;
|
||||||
|
|
||||||
|
public class AuthorityLoginOptions : AuthenticationSchemeOptions
|
||||||
|
{
|
||||||
|
|
||||||
|
}
|
@@ -1,20 +1,56 @@
|
|||||||
using System.Security.Claims;
|
using System.Security.Claims;
|
||||||
|
using DotBased.AspNet.Authority.Models.Options.Auth;
|
||||||
|
using DotBased.Logging;
|
||||||
using Microsoft.AspNetCore.Authentication;
|
using Microsoft.AspNetCore.Authentication;
|
||||||
using Microsoft.AspNetCore.Http;
|
using Microsoft.AspNetCore.Http;
|
||||||
|
using Microsoft.Extensions.Options;
|
||||||
|
|
||||||
namespace DotBased.AspNet.Authority.Services;
|
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);
|
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);
|
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);
|
||||||
|
}
|
||||||
}
|
}
|
@@ -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>
|
|
@@ -22,8 +22,6 @@ Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "AspNet", "AspNet", "{624E7B
|
|||||||
EndProject
|
EndProject
|
||||||
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "DotBased.AspNet.Authority", "DotBased.AspNet.Authority\DotBased.AspNet.Authority.csproj", "{A3ADC9AF-39B7-4EC4-8022-946118A8C322}"
|
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "DotBased.AspNet.Authority", "DotBased.AspNet.Authority\DotBased.AspNet.Authority.csproj", "{A3ADC9AF-39B7-4EC4-8022-946118A8C322}"
|
||||||
EndProject
|
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}"
|
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
|
EndProject
|
||||||
Global
|
Global
|
||||||
@@ -64,10 +62,6 @@ Global
|
|||||||
{A3ADC9AF-39B7-4EC4-8022-946118A8C322}.Debug|Any CPU.Build.0 = Debug|Any CPU
|
{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.ActiveCfg = Release|Any CPU
|
||||||
{A3ADC9AF-39B7-4EC4-8022-946118A8C322}.Release|Any CPU.Build.0 = 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.ActiveCfg = Debug|Any CPU
|
||||||
{F1F3F60B-911F-4036-8A2B-CEC18A8F59DD}.Debug|Any CPU.Build.0 = 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
|
{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}
|
{AC8343A5-7953-4E1D-A926-406BE4D7E819} = {DBDB4538-85D4-45AC-9E0A-A684467AEABA}
|
||||||
{624E7B11-8A18-46E5-AB1F-6AF6097F9D4D} = {2156FB93-C252-4B33-8A0C-73C82FABB163}
|
{624E7B11-8A18-46E5-AB1F-6AF6097F9D4D} = {2156FB93-C252-4B33-8A0C-73C82FABB163}
|
||||||
{A3ADC9AF-39B7-4EC4-8022-946118A8C322} = {624E7B11-8A18-46E5-AB1F-6AF6097F9D4D}
|
{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}
|
{F1F3F60B-911F-4036-8A2B-CEC18A8F59DD} = {624E7B11-8A18-46E5-AB1F-6AF6097F9D4D}
|
||||||
EndGlobalSection
|
EndGlobalSection
|
||||||
EndGlobal
|
EndGlobal
|
||||||
|
@@ -27,4 +27,9 @@ public class WeatherController : ControllerBase
|
|||||||
await Task.Delay(TimeSpan.FromSeconds(1));
|
await Task.Delay(TimeSpan.FromSeconds(1));
|
||||||
return forecast;
|
return forecast;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
public record WeatherForecast(DateOnly Date, int TemperatureC, string? Summary)
|
||||||
|
{
|
||||||
|
public int TemperatureF => 32 + (int)(TemperatureC / 0.5556);
|
||||||
|
}
|
||||||
}
|
}
|
@@ -1,5 +1,6 @@
|
|||||||
using DotBased.AspNet.Authority;
|
using DotBased.AspNet.Authority;
|
||||||
using DotBased.AspNet.Authority.EFCore;
|
using DotBased.AspNet.Authority.EFCore;
|
||||||
|
using DotBased.AspNet.Authority.Models.Options.Auth;
|
||||||
using DotBased.Logging;
|
using DotBased.Logging;
|
||||||
using DotBased.Logging.MEL;
|
using DotBased.Logging.MEL;
|
||||||
using DotBased.Logging.Serilog;
|
using DotBased.Logging.Serilog;
|
||||||
@@ -24,12 +25,52 @@ builder.Logging.AddDotBasedLoggerProvider(LogService.Options);
|
|||||||
|
|
||||||
builder.Services.AddControllers();
|
builder.Services.AddControllers();
|
||||||
|
|
||||||
builder.Services.AddAuthority().AddAuthorityContext(options =>
|
builder.Services.AddAuthority()
|
||||||
|
.AddAuthorityContext(options =>
|
||||||
{
|
{
|
||||||
options.UseSqlite("Data Source=dev-authority.db", c => c.MigrationsAssembly("TestWebApi"));
|
options.UseSqlite("Data Source=dev-authority.db", c => c.MigrationsAssembly("TestWebApi"));
|
||||||
}).AddAuthorityAuth()
|
})
|
||||||
.AddAuthorityCookie()
|
.MapAuthorityEndpoints()
|
||||||
.AddAuthorityToken();
|
.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.
|
// Add services to the container.
|
||||||
// Learn more about configuring Swagger/OpenAPI at https://aka.ms/aspnetcore/swashbuckle
|
// Learn more about configuring Swagger/OpenAPI at https://aka.ms/aspnetcore/swashbuckle
|
||||||
@@ -62,9 +103,4 @@ ILogger SetupSerilog()
|
|||||||
.MinimumLevel.Verbose()
|
.MinimumLevel.Verbose()
|
||||||
.WriteTo.Console(outputTemplate: BasedSerilog.OutputTemplate);
|
.WriteTo.Console(outputTemplate: BasedSerilog.OutputTemplate);
|
||||||
return logConfig.CreateLogger();
|
return logConfig.CreateLogger();
|
||||||
}
|
|
||||||
|
|
||||||
public record WeatherForecast(DateOnly Date, int TemperatureC, string? Summary)
|
|
||||||
{
|
|
||||||
public int TemperatureF => 32 + (int)(TemperatureC / 0.5556);
|
|
||||||
}
|
}
|
@@ -25,4 +25,8 @@
|
|||||||
<ProjectReference Include="..\DotBased\DotBased.csproj" />
|
<ProjectReference Include="..\DotBased\DotBased.csproj" />
|
||||||
</ItemGroup>
|
</ItemGroup>
|
||||||
|
|
||||||
|
<ItemGroup>
|
||||||
|
<Folder Include="Migrations\" />
|
||||||
|
</ItemGroup>
|
||||||
|
|
||||||
</Project>
|
</Project>
|
||||||
|
Reference in New Issue
Block a user