This commit is contained in:
parent
325e2f1ee9
commit
08e573d63c
17 changed files with 348 additions and 26 deletions
48
Services/Auth/DefaultAdminAuthenticationHandler.cs
Normal file
48
Services/Auth/DefaultAdminAuthenticationHandler.cs
Normal file
|
|
@ -0,0 +1,48 @@
|
|||
using System.Security.Claims;
|
||||
using System.Text.Encodings.Web;
|
||||
using Microsoft.AspNetCore.Authentication;
|
||||
using Microsoft.Extensions.Options;
|
||||
using WorkTracker.Configuration;
|
||||
|
||||
namespace WorkTracker.Services.Auth;
|
||||
|
||||
public sealed class DefaultAdminAuthenticationHandler : AuthenticationHandler<AuthenticationSchemeOptions>
|
||||
{
|
||||
public const string SchemeName = "DefaultAdmin";
|
||||
|
||||
private readonly IOptions<AppAuthOptions> appAuthOptions;
|
||||
|
||||
public DefaultAdminAuthenticationHandler(
|
||||
IOptionsMonitor<AuthenticationSchemeOptions> options,
|
||||
ILoggerFactory logger,
|
||||
UrlEncoder encoder,
|
||||
IOptions<AppAuthOptions> appAuthOptions)
|
||||
: base(options, logger, encoder)
|
||||
{
|
||||
this.appAuthOptions = appAuthOptions;
|
||||
}
|
||||
|
||||
protected override Task<AuthenticateResult> HandleAuthenticateAsync()
|
||||
{
|
||||
var configuredOptions = appAuthOptions.Value;
|
||||
var username = string.IsNullOrWhiteSpace(configuredOptions.DefaultUsername)
|
||||
? "Admin"
|
||||
: configuredOptions.DefaultUsername.Trim();
|
||||
var userId = string.IsNullOrWhiteSpace(configuredOptions.DefaultUserId)
|
||||
? username.ToUpperInvariant()
|
||||
: configuredOptions.DefaultUserId.Trim();
|
||||
|
||||
var claims = new List<Claim>
|
||||
{
|
||||
new(ClaimTypes.NameIdentifier, userId),
|
||||
new(ClaimTypes.Name, username),
|
||||
new(ClaimTypes.Role, "Admin")
|
||||
};
|
||||
|
||||
var identity = new ClaimsIdentity(claims, SchemeName);
|
||||
var principal = new ClaimsPrincipal(identity);
|
||||
var ticket = new AuthenticationTicket(principal, SchemeName);
|
||||
|
||||
return Task.FromResult(AuthenticateResult.Success(ticket));
|
||||
}
|
||||
}
|
||||
Loading…
Add table
Add a link
Reference in a new issue