remember me
This commit is contained in:
parent
dac3acfecf
commit
8629883f88
10 changed files with 278 additions and 96 deletions
|
@ -3,7 +3,8 @@ using System.Text.Encodings.Web;
|
||||||
using Femto.Api.Sessions;
|
using Femto.Api.Sessions;
|
||||||
using Femto.Common;
|
using Femto.Common;
|
||||||
using Femto.Modules.Auth.Application;
|
using Femto.Modules.Auth.Application;
|
||||||
using Femto.Modules.Auth.Application.Services;
|
using Femto.Modules.Auth.Application.Dto;
|
||||||
|
using Femto.Modules.Auth.Models;
|
||||||
using Microsoft.AspNetCore.Authentication;
|
using Microsoft.AspNetCore.Authentication;
|
||||||
using Microsoft.Extensions.Options;
|
using Microsoft.Extensions.Options;
|
||||||
|
|
||||||
|
@ -20,41 +21,14 @@ internal class SessionAuthenticationHandler(
|
||||||
protected override async Task<AuthenticateResult> HandleAuthenticateAsync()
|
protected override async Task<AuthenticateResult> HandleAuthenticateAsync()
|
||||||
{
|
{
|
||||||
Logger.LogDebug("{TraceId} Authenticating session", this.Context.TraceIdentifier);
|
Logger.LogDebug("{TraceId} Authenticating session", this.Context.TraceIdentifier);
|
||||||
|
|
||||||
var sessionId = this.Context.GetSessionId();
|
|
||||||
|
|
||||||
if (sessionId is null)
|
|
||||||
{
|
|
||||||
Logger.LogDebug("{TraceId} SessionId was null ", this.Context.TraceIdentifier);
|
|
||||||
return AuthenticateResult.NoResult();
|
|
||||||
}
|
|
||||||
|
|
||||||
var session = await authService.GetSession(sessionId);
|
|
||||||
|
|
||||||
if (session is null)
|
var user = await this.TryAuthenticateWithSession();
|
||||||
{
|
|
||||||
Logger.LogDebug("{TraceId} Loaded session was null ", this.Context.TraceIdentifier);
|
|
||||||
return await FailAndDeleteSession(sessionId);
|
|
||||||
}
|
|
||||||
|
|
||||||
if (session.IsExpired)
|
if (user is null)
|
||||||
{
|
user = await this.TryAuthenticateWithRememberMeToken();
|
||||||
Logger.LogDebug("{TraceId} Loaded session was expired ", this.Context.TraceIdentifier);
|
|
||||||
return await FailAndDeleteSession(sessionId);
|
|
||||||
}
|
|
||||||
|
|
||||||
var user = await authService.GetUserWithId(session.UserId);
|
|
||||||
|
|
||||||
if (user is null)
|
if (user is null)
|
||||||
{
|
return AuthenticateResult.NoResult();
|
||||||
return await FailAndDeleteSession(sessionId);
|
|
||||||
}
|
|
||||||
|
|
||||||
if (session.ExpiresSoon)
|
|
||||||
{
|
|
||||||
session = await authService.CreateWeakSession(session.UserId);
|
|
||||||
this.Context.SetSession(session, user);
|
|
||||||
}
|
|
||||||
|
|
||||||
var claims = new List<Claim>
|
var claims = new List<Claim>
|
||||||
{
|
{
|
||||||
|
@ -72,10 +46,77 @@ internal class SessionAuthenticationHandler(
|
||||||
return AuthenticateResult.Success(new AuthenticationTicket(principal, this.Scheme.Name));
|
return AuthenticateResult.Success(new AuthenticationTicket(principal, this.Scheme.Name));
|
||||||
}
|
}
|
||||||
|
|
||||||
private async Task<AuthenticateResult> FailAndDeleteSession(string sessionId)
|
private async Task<UserInfo?> TryAuthenticateWithSession()
|
||||||
{
|
{
|
||||||
await authService.DeleteSession(sessionId);
|
var sessionId = this.Context.GetSessionId();
|
||||||
this.Context.DeleteSession();
|
|
||||||
return AuthenticateResult.Fail("invalid session");
|
if (sessionId is null)
|
||||||
|
{
|
||||||
|
Logger.LogDebug("{TraceId} SessionId was null ", this.Context.TraceIdentifier);
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
|
||||||
|
var session = await authService.GetSession(sessionId);
|
||||||
|
|
||||||
|
if (session is null)
|
||||||
|
{
|
||||||
|
Logger.LogDebug("{TraceId} Loaded session was null ", this.Context.TraceIdentifier);
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
|
||||||
|
if (session.IsExpired)
|
||||||
|
{
|
||||||
|
Logger.LogDebug("{TraceId} Loaded session was expired ", this.Context.TraceIdentifier);
|
||||||
|
await authService.DeleteSession(sessionId);
|
||||||
|
this.Context.DeleteSession();
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
|
||||||
|
var user = await authService.GetUserWithId(session.UserId);
|
||||||
|
|
||||||
|
if (user is null)
|
||||||
|
{
|
||||||
|
await authService.DeleteSession(sessionId);
|
||||||
|
this.Context.DeleteSession();
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
|
||||||
|
if (session.ExpiresSoon)
|
||||||
|
{
|
||||||
|
session = await authService.CreateWeakSession(session.UserId);
|
||||||
|
this.Context.SetSession(session, user);
|
||||||
|
}
|
||||||
|
|
||||||
|
return user;
|
||||||
|
}
|
||||||
|
|
||||||
|
private async Task<UserInfo?> TryAuthenticateWithRememberMeToken()
|
||||||
|
{
|
||||||
|
/*
|
||||||
|
* load remember me from token
|
||||||
|
* if it is null, return null
|
||||||
|
* if it exists, validate it
|
||||||
|
* if it is valid, create a new weak session, return the user
|
||||||
|
* if it is almost expired, refresh it
|
||||||
|
*/
|
||||||
|
|
||||||
|
var rememberMeToken = this.Context.GetRememberMeToken();
|
||||||
|
|
||||||
|
if (rememberMeToken is null)
|
||||||
|
return null;
|
||||||
|
|
||||||
|
var (user, newRememberMeToken) = await authService.GetUserWithRememberMeToken(rememberMeToken);
|
||||||
|
|
||||||
|
if (user is null)
|
||||||
|
return null;
|
||||||
|
|
||||||
|
var session = await authService.CreateWeakSession(user.Id);
|
||||||
|
|
||||||
|
this.Context.SetSession(session, user);
|
||||||
|
|
||||||
|
if (newRememberMeToken is not null)
|
||||||
|
this.Context.SetRememberMeToken(newRememberMeToken);
|
||||||
|
|
||||||
|
return user;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
|
@ -1,6 +1,6 @@
|
||||||
using Femto.Api.Sessions;
|
using Femto.Api.Sessions;
|
||||||
using Femto.Common;
|
using Femto.Common;
|
||||||
using Femto.Modules.Auth.Application.Services;
|
using Femto.Modules.Auth.Application;
|
||||||
using Femto.Modules.Auth.Contracts;
|
using Femto.Modules.Auth.Contracts;
|
||||||
using Microsoft.AspNetCore.Authorization;
|
using Microsoft.AspNetCore.Authorization;
|
||||||
using Microsoft.AspNetCore.Mvc;
|
using Microsoft.AspNetCore.Mvc;
|
||||||
|
@ -18,10 +18,9 @@ public class AuthController(ICurrentUserContext currentUserContext, IAuthService
|
||||||
CancellationToken cancellationToken
|
CancellationToken cancellationToken
|
||||||
)
|
)
|
||||||
{
|
{
|
||||||
var result = await authService.GetUserWithCredentials(
|
var result = await authService.AuthenticateUserCredentials(
|
||||||
request.Username,
|
request.Username,
|
||||||
request.Password,
|
request.Password,
|
||||||
request.RememberMe,
|
|
||||||
cancellationToken
|
cancellationToken
|
||||||
);
|
);
|
||||||
|
|
||||||
|
@ -29,23 +28,35 @@ public class AuthController(ICurrentUserContext currentUserContext, IAuthService
|
||||||
return this.BadRequest();
|
return this.BadRequest();
|
||||||
|
|
||||||
var (user, session) = result;
|
var (user, session) = result;
|
||||||
|
|
||||||
HttpContext.SetSession(session, user);
|
HttpContext.SetSession(session, user);
|
||||||
|
|
||||||
|
if (request.RememberMe)
|
||||||
|
{
|
||||||
|
var newRememberMeToken = await authService.CreateRememberMeToken(user.Id);
|
||||||
|
HttpContext.SetRememberMeToken(newRememberMeToken);
|
||||||
|
}
|
||||||
|
|
||||||
return new LoginResponse(user.Id, user.Username, user.Roles.Any(r => r == Role.SuperUser));
|
return new LoginResponse(user.Id, user.Username, user.Roles.Any(r => r == Role.SuperUser));
|
||||||
}
|
}
|
||||||
|
|
||||||
[HttpPost("register")]
|
[HttpPost("register")]
|
||||||
public async Task<ActionResult<RegisterResponse>> Register([FromBody] RegisterRequest request)
|
public async Task<ActionResult<RegisterResponse>> Register([FromBody] RegisterRequest request, CancellationToken cancellationToken)
|
||||||
{
|
{
|
||||||
var (user, session) = await authService.CreateUserWithCredentials(
|
var (user, session) = await authService.CreateUserWithCredentials(
|
||||||
request.Username,
|
request.Username,
|
||||||
request.Password,
|
request.Password,
|
||||||
request.SignupCode,
|
request.SignupCode,
|
||||||
request.RememberMe
|
cancellationToken
|
||||||
);
|
);
|
||||||
|
|
||||||
HttpContext.SetSession(session, user);
|
HttpContext.SetSession(session, user);
|
||||||
|
|
||||||
|
if (request.RememberMe)
|
||||||
|
{
|
||||||
|
var newRememberMeToken = await authService.CreateRememberMeToken(user.Id);
|
||||||
|
HttpContext.SetRememberMeToken(newRememberMeToken);
|
||||||
|
}
|
||||||
|
|
||||||
return new RegisterResponse(
|
return new RegisterResponse(
|
||||||
user.Id,
|
user.Id,
|
||||||
|
@ -65,6 +76,14 @@ public class AuthController(ICurrentUserContext currentUserContext, IAuthService
|
||||||
HttpContext.DeleteSession();
|
HttpContext.DeleteSession();
|
||||||
}
|
}
|
||||||
|
|
||||||
|
var rememberMeToken = HttpContext.GetRememberMeToken();
|
||||||
|
|
||||||
|
if (rememberMeToken is not null)
|
||||||
|
{
|
||||||
|
await authService.DeleteRememberMeToken(rememberMeToken);
|
||||||
|
HttpContext.DeleteRememberMeToken();
|
||||||
|
}
|
||||||
|
|
||||||
return Ok(new { });
|
return Ok(new { });
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
|
@ -15,18 +15,12 @@ internal static class HttpContextSessionExtensions
|
||||||
PropertyNamingPolicy = JsonNamingPolicy.CamelCase,
|
PropertyNamingPolicy = JsonNamingPolicy.CamelCase,
|
||||||
};
|
};
|
||||||
|
|
||||||
public static string? GetSessionId(this HttpContext httpContext)
|
public static string? GetSessionId(this HttpContext httpContext) =>
|
||||||
{
|
httpContext.Request.Cookies["sid"];
|
||||||
var sessionId = httpContext.Request.Cookies["sid"];
|
|
||||||
|
|
||||||
return sessionId;
|
|
||||||
}
|
|
||||||
|
|
||||||
public static void SetSession(this HttpContext context, Session session, UserInfo user)
|
public static void SetSession(this HttpContext context, Session session, UserInfo user)
|
||||||
{
|
{
|
||||||
var cookieSettings = context.RequestServices.GetRequiredService<
|
var cookieSettings = context.RequestServices.GetRequiredService<IOptions<CookieSettings>>();
|
||||||
IOptions<CookieSettings>
|
|
||||||
>();
|
|
||||||
|
|
||||||
context.Response.Cookies.Append(
|
context.Response.Cookies.Append(
|
||||||
"sid",
|
"sid",
|
||||||
|
@ -57,7 +51,7 @@ internal static class HttpContextSessionExtensions
|
||||||
}
|
}
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
public static void DeleteSession(this HttpContext httpContext)
|
public static void DeleteSession(this HttpContext httpContext)
|
||||||
{
|
{
|
||||||
var cookieSettings = httpContext.RequestServices.GetRequiredService<
|
var cookieSettings = httpContext.RequestServices.GetRequiredService<
|
||||||
|
@ -91,4 +85,47 @@ internal static class HttpContextSessionExtensions
|
||||||
}
|
}
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
||||||
|
public static RememberMeToken? GetRememberMeToken(this HttpContext httpContext) =>
|
||||||
|
httpContext.Request.Cookies["rid"] is { } code ? RememberMeToken.FromCode(code) : null;
|
||||||
|
|
||||||
|
public static void SetRememberMeToken(this HttpContext context, NewRememberMeToken token)
|
||||||
|
{
|
||||||
|
var cookieSettings = context.RequestServices.GetRequiredService<IOptions<CookieSettings>>();
|
||||||
|
|
||||||
|
context.Response.Cookies.Append(
|
||||||
|
"rid",
|
||||||
|
token.Code,
|
||||||
|
new CookieOptions
|
||||||
|
{
|
||||||
|
Path = "/",
|
||||||
|
IsEssential = true,
|
||||||
|
Domain = cookieSettings.Value.Domain,
|
||||||
|
HttpOnly = true,
|
||||||
|
Secure = cookieSettings.Value.Secure,
|
||||||
|
SameSite = cookieSettings.Value.SameSite,
|
||||||
|
Expires = token.Expires,
|
||||||
|
}
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
public static void DeleteRememberMeToken(this HttpContext context)
|
||||||
|
{
|
||||||
|
var cookieSettings = context.RequestServices.GetRequiredService<IOptions<CookieSettings>>();
|
||||||
|
|
||||||
|
context.Response.Cookies.Delete(
|
||||||
|
"rid",
|
||||||
|
new CookieOptions
|
||||||
|
{
|
||||||
|
Path = "/",
|
||||||
|
HttpOnly = true,
|
||||||
|
Domain = cookieSettings.Value.Domain,
|
||||||
|
IsEssential = true,
|
||||||
|
Secure = cookieSettings.Value.Secure,
|
||||||
|
SameSite = cookieSettings.Value.SameSite,
|
||||||
|
Expires = DateTimeOffset.UtcNow.AddDays(-1),
|
||||||
|
}
|
||||||
|
);
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
|
@ -7,7 +7,7 @@ using Femto.Modules.Auth.Infrastructure;
|
||||||
using Femto.Modules.Auth.Models;
|
using Femto.Modules.Auth.Models;
|
||||||
using Microsoft.EntityFrameworkCore;
|
using Microsoft.EntityFrameworkCore;
|
||||||
|
|
||||||
namespace Femto.Modules.Auth.Application.Services;
|
namespace Femto.Modules.Auth.Application;
|
||||||
|
|
||||||
internal class AuthService(
|
internal class AuthService(
|
||||||
AuthContext context,
|
AuthContext context,
|
||||||
|
@ -15,10 +15,11 @@ internal class AuthService(
|
||||||
IDbConnectionFactory connectionFactory
|
IDbConnectionFactory connectionFactory
|
||||||
) : IAuthService
|
) : IAuthService
|
||||||
{
|
{
|
||||||
public async Task<UserAndSession?> GetUserWithCredentials(string username,
|
public async Task<UserAndSession?> AuthenticateUserCredentials(
|
||||||
|
string username,
|
||||||
string password,
|
string password,
|
||||||
bool createLongTermSession,
|
CancellationToken cancellationToken = default
|
||||||
CancellationToken cancellationToken = default)
|
)
|
||||||
{
|
{
|
||||||
var user = await context
|
var user = await context
|
||||||
.Users.Where(u => u.Username == username)
|
.Users.Where(u => u.Username == username)
|
||||||
|
@ -48,7 +49,7 @@ internal class AuthService(
|
||||||
.SingleOrDefaultAsync(cancellationToken);
|
.SingleOrDefaultAsync(cancellationToken);
|
||||||
}
|
}
|
||||||
|
|
||||||
public async Task<Session> CreateStrongSession(Guid userId)
|
public async Task<Session> CreateNewSession(Guid userId)
|
||||||
{
|
{
|
||||||
var session = new Session(userId, true);
|
var session = new Session(userId, true);
|
||||||
|
|
||||||
|
@ -76,11 +77,12 @@ internal class AuthService(
|
||||||
await storage.DeleteSession(sessionId);
|
await storage.DeleteSession(sessionId);
|
||||||
}
|
}
|
||||||
|
|
||||||
public async Task<UserAndSession> CreateUserWithCredentials(string username,
|
public async Task<UserAndSession> CreateUserWithCredentials(
|
||||||
|
string username,
|
||||||
string password,
|
string password,
|
||||||
string signupCode,
|
string signupCode,
|
||||||
bool createLongTermSession,
|
CancellationToken cancellationToken = default
|
||||||
CancellationToken cancellationToken = default)
|
)
|
||||||
{
|
{
|
||||||
var now = DateTimeOffset.UtcNow;
|
var now = DateTimeOffset.UtcNow;
|
||||||
|
|
||||||
|
@ -166,24 +168,61 @@ internal class AuthService(
|
||||||
.ToList();
|
.ToList();
|
||||||
}
|
}
|
||||||
|
|
||||||
public async Task<LongTermSession> CreateLongTermSession(Guid userId, bool isStrong)
|
public async Task<NewRememberMeToken> CreateRememberMeToken(Guid userId)
|
||||||
{
|
{
|
||||||
throw new NotImplementedException();
|
var (rememberMeToken, verifier) = LongTermSession.Create(userId);
|
||||||
|
|
||||||
|
await context.AddAsync(rememberMeToken);
|
||||||
|
await context.SaveChangesAsync();
|
||||||
|
|
||||||
|
return new(rememberMeToken.Selector, verifier, rememberMeToken.Expires);
|
||||||
}
|
}
|
||||||
|
|
||||||
public async Task<LongTermSession> DeleteLongTermSession(string sessionId)
|
public async Task<(UserInfo?, NewRememberMeToken?)> GetUserWithRememberMeToken(
|
||||||
|
RememberMeToken rememberMeToken
|
||||||
|
)
|
||||||
{
|
{
|
||||||
throw new NotImplementedException();
|
var token = await context.LongTermSessions.SingleOrDefaultAsync(t =>
|
||||||
|
t.Selector == rememberMeToken.Selector
|
||||||
|
);
|
||||||
|
|
||||||
|
if (token is null)
|
||||||
|
return (null, null);
|
||||||
|
|
||||||
|
if (!token.Validate(rememberMeToken.Verifier))
|
||||||
|
return (null, null);
|
||||||
|
|
||||||
|
var user = await context.Users.SingleOrDefaultAsync(u => u.Id == token.UserId);
|
||||||
|
|
||||||
|
if (user is null)
|
||||||
|
return (null, null);
|
||||||
|
|
||||||
|
if (token.ExpiresSoon)
|
||||||
|
{
|
||||||
|
var (newToken, verifier) = LongTermSession.Create(user.Id);
|
||||||
|
await context.AddAsync(newToken);
|
||||||
|
await context.SaveChangesAsync();
|
||||||
|
|
||||||
|
return (new(user), new(newToken.Selector, verifier, newToken.Expires));
|
||||||
|
}
|
||||||
|
|
||||||
|
return (new(user), null);
|
||||||
}
|
}
|
||||||
|
|
||||||
public async Task<LongTermSession> RefreshLongTermSession(string sessionId)
|
public async Task DeleteRememberMeToken(RememberMeToken rememberMeToken)
|
||||||
{
|
{
|
||||||
throw new NotImplementedException();
|
var session = await context.LongTermSessions.SingleOrDefaultAsync(s =>
|
||||||
}
|
s.Selector == rememberMeToken.Selector
|
||||||
|
);
|
||||||
|
|
||||||
public async Task<ValidateSessionResult> ValidateLongTermSession(string sessionId)
|
if (session is null)
|
||||||
{
|
return;
|
||||||
throw new NotImplementedException();
|
|
||||||
|
if (!session.Validate(rememberMeToken.Verifier))
|
||||||
|
return;
|
||||||
|
|
||||||
|
context.Remove(session);
|
||||||
|
await context.SaveChangesAsync();
|
||||||
}
|
}
|
||||||
|
|
||||||
private class GetSignupCodesQueryResultRow
|
private class GetSignupCodesQueryResultRow
|
|
@ -3,7 +3,6 @@ using Femto.Common.Infrastructure;
|
||||||
using Femto.Common.Infrastructure.DbConnection;
|
using Femto.Common.Infrastructure.DbConnection;
|
||||||
using Femto.Common.Infrastructure.Outbox;
|
using Femto.Common.Infrastructure.Outbox;
|
||||||
using Femto.Common.Integration;
|
using Femto.Common.Integration;
|
||||||
using Femto.Modules.Auth.Application.Services;
|
|
||||||
using Femto.Modules.Auth.Data;
|
using Femto.Modules.Auth.Data;
|
||||||
using Femto.Modules.Auth.Infrastructure;
|
using Femto.Modules.Auth.Infrastructure;
|
||||||
using MediatR;
|
using MediatR;
|
||||||
|
|
18
Femto.Modules.Auth/Application/Dto/RememberMeToken.cs
Normal file
18
Femto.Modules.Auth/Application/Dto/RememberMeToken.cs
Normal file
|
@ -0,0 +1,18 @@
|
||||||
|
using Femto.Modules.Auth.Models;
|
||||||
|
|
||||||
|
namespace Femto.Modules.Auth.Application.Dto;
|
||||||
|
|
||||||
|
public record RememberMeToken(string Selector, string Verifier)
|
||||||
|
{
|
||||||
|
public static RememberMeToken FromCode(string code)
|
||||||
|
{
|
||||||
|
var parts = code.Split('.');
|
||||||
|
return new RememberMeToken(parts[0], parts[1]);
|
||||||
|
}
|
||||||
|
|
||||||
|
};
|
||||||
|
|
||||||
|
public record NewRememberMeToken(string Selector, string Verifier, DateTimeOffset Expires)
|
||||||
|
{
|
||||||
|
public string Code => $"{Selector}.{Verifier}";
|
||||||
|
}
|
|
@ -1,7 +1,7 @@
|
||||||
using Femto.Modules.Auth.Application.Dto;
|
using Femto.Modules.Auth.Application.Dto;
|
||||||
using Femto.Modules.Auth.Models;
|
using Femto.Modules.Auth.Models;
|
||||||
|
|
||||||
namespace Femto.Modules.Auth.Application.Services;
|
namespace Femto.Modules.Auth.Application;
|
||||||
|
|
||||||
/// <summary>
|
/// <summary>
|
||||||
/// I broke off IAuthService from IAuthModule because the CQRS distinction is cumbersome when doing auth handling,
|
/// I broke off IAuthService from IAuthModule because the CQRS distinction is cumbersome when doing auth handling,
|
||||||
|
@ -11,17 +11,16 @@ namespace Femto.Modules.Auth.Application.Services;
|
||||||
/// </summary>
|
/// </summary>
|
||||||
public interface IAuthService
|
public interface IAuthService
|
||||||
{
|
{
|
||||||
public Task<UserAndSession?> GetUserWithCredentials(
|
public Task<UserAndSession?> AuthenticateUserCredentials(
|
||||||
string username,
|
string username,
|
||||||
string password,
|
string password,
|
||||||
bool createLongTermSession,
|
|
||||||
CancellationToken cancellationToken = default
|
CancellationToken cancellationToken = default
|
||||||
);
|
);
|
||||||
public Task<UserInfo?> GetUserWithId(
|
public Task<UserInfo?> GetUserWithId(
|
||||||
Guid? userId,
|
Guid? userId,
|
||||||
CancellationToken cancellationToken = default
|
CancellationToken cancellationToken = default
|
||||||
);
|
);
|
||||||
public Task<Session> CreateStrongSession(Guid userId);
|
public Task<Session> CreateNewSession(Guid userId);
|
||||||
public Task<Session> CreateWeakSession(Guid userId);
|
public Task<Session> CreateWeakSession(Guid userId);
|
||||||
public Task<Session?> GetSession(string sessionId);
|
public Task<Session?> GetSession(string sessionId);
|
||||||
public Task DeleteSession(string sessionId);
|
public Task DeleteSession(string sessionId);
|
||||||
|
@ -29,7 +28,6 @@ public interface IAuthService
|
||||||
public Task<UserAndSession> CreateUserWithCredentials(string username,
|
public Task<UserAndSession> CreateUserWithCredentials(string username,
|
||||||
string password,
|
string password,
|
||||||
string signupCode,
|
string signupCode,
|
||||||
bool createLongTermSession,
|
|
||||||
CancellationToken cancellationToken = default);
|
CancellationToken cancellationToken = default);
|
||||||
|
|
||||||
public Task AddSignupCode(
|
public Task AddSignupCode(
|
||||||
|
@ -41,6 +39,10 @@ public interface IAuthService
|
||||||
public Task<ICollection<SignupCodeDto>> GetSignupCodes(
|
public Task<ICollection<SignupCodeDto>> GetSignupCodes(
|
||||||
CancellationToken cancellationToken = default
|
CancellationToken cancellationToken = default
|
||||||
);
|
);
|
||||||
|
|
||||||
|
Task<NewRememberMeToken> CreateRememberMeToken(Guid userId);
|
||||||
|
Task<(UserInfo?, NewRememberMeToken?)> GetUserWithRememberMeToken(RememberMeToken rememberMeToken);
|
||||||
|
Task DeleteRememberMeToken(RememberMeToken rememberMeToken);
|
||||||
}
|
}
|
||||||
|
|
||||||
public record UserAndSession(UserInfo User, Session Session);
|
public record UserAndSession(UserInfo User, Session Session);
|
|
@ -0,0 +1,13 @@
|
||||||
|
using Femto.Modules.Auth.Models;
|
||||||
|
using Microsoft.EntityFrameworkCore;
|
||||||
|
using Microsoft.EntityFrameworkCore.Metadata.Builders;
|
||||||
|
|
||||||
|
namespace Femto.Modules.Auth.Data.Configurations;
|
||||||
|
|
||||||
|
public class LongTermSessionConfiguration : IEntityTypeConfiguration<LongTermSession>
|
||||||
|
{
|
||||||
|
public void Configure(EntityTypeBuilder<LongTermSession> builder)
|
||||||
|
{
|
||||||
|
builder.ToTable("long_term_session");
|
||||||
|
}
|
||||||
|
}
|
|
@ -1,3 +1,4 @@
|
||||||
|
using System.ComponentModel.DataAnnotations.Schema;
|
||||||
using System.Text;
|
using System.Text;
|
||||||
using static System.Security.Cryptography.RandomNumberGenerator;
|
using static System.Security.Cryptography.RandomNumberGenerator;
|
||||||
|
|
||||||
|
@ -6,22 +7,30 @@ namespace Femto.Modules.Auth.Models;
|
||||||
public class LongTermSession
|
public class LongTermSession
|
||||||
{
|
{
|
||||||
private static TimeSpan TokenTimeout { get; } = TimeSpan.FromDays(90);
|
private static TimeSpan TokenTimeout { get; } = TimeSpan.FromDays(90);
|
||||||
|
private static TimeSpan RefreshBuffer { get; } = TimeSpan.FromDays(5);
|
||||||
|
|
||||||
public int Id { get; private set; }
|
public int Id { get; private set; }
|
||||||
|
|
||||||
public string Selector { get; private set; }
|
public string Selector { get; private set; }
|
||||||
|
|
||||||
public byte[] HashedVerifier { get; private set; }
|
public byte[] HashedVerifier { get; private set; }
|
||||||
|
|
||||||
public DateTimeOffset Expires { get; private set; }
|
public DateTimeOffset Expires { get; private set; }
|
||||||
|
|
||||||
public Guid UserId { get; private set; }
|
public Guid UserId { get; private set; }
|
||||||
|
|
||||||
private LongTermSession() {}
|
[NotMapped]
|
||||||
|
public bool ExpiresSoon => this.Expires < DateTimeOffset.UtcNow + RefreshBuffer;
|
||||||
|
|
||||||
|
private LongTermSession() { }
|
||||||
|
|
||||||
public static (LongTermSession, string) Create(Guid userId)
|
public static (LongTermSession, string) Create(Guid userId)
|
||||||
{
|
{
|
||||||
var selector = GetString("abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789", 12);
|
var selector = GetString(
|
||||||
|
"abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789",
|
||||||
|
12
|
||||||
|
);
|
||||||
|
|
||||||
var verifier = GetString("abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789", 32);
|
var verifier = GetString("abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789", 32);
|
||||||
|
|
||||||
using var sha256 = System.Security.Cryptography.SHA256.Create();
|
using var sha256 = System.Security.Cryptography.SHA256.Create();
|
||||||
|
@ -29,23 +38,26 @@ public class LongTermSession
|
||||||
var longTermSession = new LongTermSession
|
var longTermSession = new LongTermSession
|
||||||
{
|
{
|
||||||
Selector = selector,
|
Selector = selector,
|
||||||
HashedVerifier = sha256.ComputeHash(Encoding.UTF8.GetBytes(verifier)),
|
HashedVerifier = ComputeHash(verifier),
|
||||||
UserId = userId,
|
UserId = userId,
|
||||||
Expires = DateTimeOffset.UtcNow + TokenTimeout
|
Expires = DateTimeOffset.UtcNow + TokenTimeout,
|
||||||
};
|
};
|
||||||
|
|
||||||
var rememberMeToken = $"{selector}.{verifier}";
|
|
||||||
|
|
||||||
return (longTermSession, rememberMeToken);
|
return (longTermSession, verifier);
|
||||||
}
|
}
|
||||||
|
|
||||||
public bool Validate(string verifier)
|
public bool Validate(string verifier)
|
||||||
{
|
{
|
||||||
if (this.Expires < DateTimeOffset.UtcNow)
|
if (this.Expires < DateTimeOffset.UtcNow)
|
||||||
return false;
|
return false;
|
||||||
|
|
||||||
|
return ComputeHash(verifier).SequenceEqual(this.HashedVerifier);
|
||||||
|
}
|
||||||
|
|
||||||
|
private static byte[] ComputeHash(string verifier)
|
||||||
|
{
|
||||||
using var sha256 = System.Security.Cryptography.SHA256.Create();
|
using var sha256 = System.Security.Cryptography.SHA256.Create();
|
||||||
var hashedVerifier = sha256.ComputeHash(Encoding.UTF8.GetBytes(verifier));
|
var hashedVerifier = sha256.ComputeHash(Encoding.UTF8.GetBytes(verifier));
|
||||||
return hashedVerifier.SequenceEqual(this.HashedVerifier);
|
return hashedVerifier;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
|
@ -4,11 +4,13 @@ namespace Femto.Modules.Auth.Models;
|
||||||
|
|
||||||
public class Session(Guid userId, bool isStrong)
|
public class Session(Guid userId, bool isStrong)
|
||||||
{
|
{
|
||||||
|
private static readonly TimeSpan ValidityPeriod = TimeSpan.FromSeconds(5);
|
||||||
|
private static readonly TimeSpan RefreshBuffer = TimeSpan.FromMinutes(0);
|
||||||
public string Id { get; } = Convert.ToBase64String(GetBytes(32));
|
public string Id { get; } = Convert.ToBase64String(GetBytes(32));
|
||||||
public Guid UserId { get; } = userId;
|
public Guid UserId { get; } = userId;
|
||||||
public DateTimeOffset Expires { get; } = DateTimeOffset.UtcNow + TimeSpan.FromMinutes(15);
|
public DateTimeOffset Expires { get; } = DateTimeOffset.UtcNow + ValidityPeriod;
|
||||||
|
|
||||||
public bool ExpiresSoon => this.Expires < DateTimeOffset.UtcNow + TimeSpan.FromMinutes(5);
|
public bool ExpiresSoon => this.Expires < DateTimeOffset.UtcNow + RefreshBuffer;
|
||||||
public bool IsStronglyAuthenticated { get; } = isStrong;
|
public bool IsStronglyAuthenticated { get; } = isStrong;
|
||||||
public bool IsExpired => this.Expires < DateTimeOffset.UtcNow;
|
public bool IsExpired => this.Expires < DateTimeOffset.UtcNow;
|
||||||
}
|
}
|
||||||
|
|
Loading…
Add table
Add a link
Reference in a new issue