Added automatic token refresh feature and login page
This commit is contained in:
@@ -6,11 +6,9 @@
|
||||
|
||||
<h1>Counter</h1>
|
||||
|
||||
<AuthorizedView Permissions="@permissions">
|
||||
<p role="status">Current count: @currentCount</p>
|
||||
<p role="status">Current count: @currentCount</p>
|
||||
|
||||
<button class="btn btn-primary" @onclick="IncrementCount">Click me</button>
|
||||
</AuthorizedView>
|
||||
<button class="btn btn-primary" @onclick="IncrementCount">Click me</button>
|
||||
|
||||
@code {
|
||||
private int currentCount = 0;
|
||||
|
||||
@@ -1,5 +1,8 @@
|
||||
@page "/"
|
||||
@using HopFrame.Security.Claims
|
||||
@using HopFrame.Web.Components
|
||||
|
||||
<AuthorizedView RedirectIfUnauthorized="login"/>
|
||||
|
||||
<PageTitle>Home</PageTitle>
|
||||
|
||||
|
||||
@@ -1,12 +1,10 @@
|
||||
using FrontendTest;
|
||||
using FrontendTest.Components;
|
||||
using HopFrame.Security.Authentication;
|
||||
using HopFrame.Web;
|
||||
|
||||
var builder = WebApplication.CreateBuilder(args);
|
||||
|
||||
builder.Services.AddDbContext<DatabaseContext>();
|
||||
builder.Services.AddHopFrameAuthentication<DatabaseContext>();
|
||||
builder.Services.AddHopFrameServices<DatabaseContext>();
|
||||
|
||||
// Add services to the container.
|
||||
@@ -27,6 +25,8 @@ app.UseHttpsRedirection();
|
||||
app.UseStaticFiles();
|
||||
app.UseAntiforgery();
|
||||
app.UseAuthorization();
|
||||
app.UseAuthentication();
|
||||
app.UseMiddleware<AuthMiddleware>();
|
||||
|
||||
app.MapRazorComponents<App>()
|
||||
.AddHopFramePages()
|
||||
|
||||
@@ -15,7 +15,7 @@ public class AuthorizedFilter : IAuthorizationFilter {
|
||||
public void OnAuthorization(AuthorizationFilterContext context) {
|
||||
if (context.Filters.Any(item => item is IAllowAnonymousFilter)) return;
|
||||
|
||||
if (context.HttpContext.User.Identity?.IsAuthenticated == false) {
|
||||
if (string.IsNullOrEmpty(context.HttpContext.User.GetAccessTokenId())) {
|
||||
context.Result = new UnauthorizedResult();
|
||||
return;
|
||||
}
|
||||
|
||||
@@ -5,11 +5,11 @@ using Microsoft.AspNetCore.Http;
|
||||
namespace HopFrame.Security.Claims;
|
||||
|
||||
internal class TokenContextImplementor<TDbContext>(IHttpContextAccessor accessor, TDbContext context) : ITokenContext where TDbContext : HopDbContextBase {
|
||||
public bool IsAuthenticated => accessor.HttpContext?.User.Identity?.IsAuthenticated == true;
|
||||
public bool IsAuthenticated => !string.IsNullOrEmpty(accessor.HttpContext?.User.GetAccessTokenId());
|
||||
|
||||
public User User => context.Users
|
||||
.SingleOrDefault(user => user.Id == accessor.HttpContext.User.GetUserId())?
|
||||
.ToUserModel(context);
|
||||
|
||||
public Guid AccessToken => Guid.Parse(accessor.HttpContext?.User.GetAccessTokenId() ?? string.Empty);
|
||||
public Guid AccessToken => Guid.Parse(accessor.HttpContext?.User.GetAccessTokenId() ?? Guid.Empty.ToString());
|
||||
}
|
||||
@@ -1,6 +1,6 @@
|
||||
namespace HopFrame.Security.Models;
|
||||
|
||||
public struct UserLogin {
|
||||
public class UserLogin {
|
||||
public string Email { get; set; }
|
||||
public string Password { get; set; }
|
||||
}
|
||||
@@ -26,6 +26,6 @@ public interface IPermissionService {
|
||||
|
||||
Task DeletePermission(Permission permission);
|
||||
|
||||
internal Task<string[]> GetFullPermissions(string user);
|
||||
Task<string[]> GetFullPermissions(string user);
|
||||
|
||||
}
|
||||
35
HopFrame.Web/AuthMiddleware.cs
Normal file
35
HopFrame.Web/AuthMiddleware.cs
Normal file
@@ -0,0 +1,35 @@
|
||||
using System.Security.Claims;
|
||||
using HopFrame.Database;
|
||||
using HopFrame.Security.Authentication;
|
||||
using HopFrame.Security.Claims;
|
||||
using HopFrame.Security.Services;
|
||||
using HopFrame.Web.Services;
|
||||
using Microsoft.AspNetCore.Http;
|
||||
|
||||
namespace HopFrame.Web;
|
||||
|
||||
public class AuthMiddleware(IAuthService auth, IPermissionService perms) : IMiddleware {
|
||||
public async Task InvokeAsync(HttpContext context, RequestDelegate next) {
|
||||
var loggedIn = await auth.IsLoggedIn();
|
||||
|
||||
if (!loggedIn) {
|
||||
var token = await auth.RefreshLogin();
|
||||
if (token is null) {
|
||||
await next.Invoke(context);
|
||||
return;
|
||||
}
|
||||
|
||||
var claims = new List<Claim> {
|
||||
new(HopFrameClaimTypes.AccessTokenId, token.Token),
|
||||
new(HopFrameClaimTypes.UserId, token.UserId)
|
||||
};
|
||||
|
||||
var permissions = await perms.GetFullPermissions(token.UserId);
|
||||
claims.AddRange(permissions.Select(perm => new Claim(HopFrameClaimTypes.Permission, perm)));
|
||||
|
||||
context.User.AddIdentity(new ClaimsIdentity(claims, HopFrameAuthentication<HopDbContextBase>.SchemeName));
|
||||
}
|
||||
|
||||
await next.Invoke(context);
|
||||
}
|
||||
}
|
||||
@@ -2,12 +2,13 @@
|
||||
@using HopFrame.Security.Claims
|
||||
@using Microsoft.AspNetCore.Http
|
||||
|
||||
@if (IsAuthorized()) {
|
||||
@if (HandleComponent()) {
|
||||
@ChildContent
|
||||
}
|
||||
|
||||
@inject ITokenContext Auth
|
||||
@inject IHttpContextAccessor HttpAccessor
|
||||
@inject NavigationManager Navigator
|
||||
|
||||
@code {
|
||||
[Parameter]
|
||||
@@ -16,14 +17,17 @@
|
||||
[Parameter]
|
||||
public string Permission { get; set; }
|
||||
|
||||
[Parameter]
|
||||
public string RedirectIfUnauthorized { get; set; }
|
||||
|
||||
[Parameter]
|
||||
public RenderFragment ChildContent { get; set; }
|
||||
|
||||
private bool IsAuthorized() {
|
||||
if (!Auth.IsAuthenticated) return false;
|
||||
if (Permissions.Length == 0 && string.IsNullOrEmpty(Permission)) return true;
|
||||
if ((Permissions == null || Permissions.Length == 0) && string.IsNullOrEmpty(Permission)) return true;
|
||||
|
||||
var perms = new List<string>(Permissions);
|
||||
var perms = new List<string>(Permissions!);
|
||||
if (!string.IsNullOrEmpty(Permission)) perms.Add(Permission);
|
||||
|
||||
var permissions = HttpAccessor.HttpContext?.User.GetPermissions();
|
||||
@@ -31,4 +35,14 @@
|
||||
|
||||
return true;
|
||||
}
|
||||
|
||||
private bool HandleComponent() {
|
||||
var authorized = IsAuthorized();
|
||||
|
||||
if (authorized == false && !string.IsNullOrEmpty(RedirectIfUnauthorized)) {
|
||||
Navigator.NavigateTo(RedirectIfUnauthorized, true);
|
||||
}
|
||||
|
||||
return authorized;
|
||||
}
|
||||
}
|
||||
61
HopFrame.Web/Pages/Login.razor
Normal file
61
HopFrame.Web/Pages/Login.razor
Normal file
@@ -0,0 +1,61 @@
|
||||
@page "/login"
|
||||
@using HopFrame.Security.Models
|
||||
@using HopFrame.Web.Services
|
||||
@using Microsoft.AspNetCore.Components.Forms
|
||||
@using Microsoft.AspNetCore.Components.Routing
|
||||
@using Microsoft.AspNetCore.Components.Web
|
||||
|
||||
<PageTitle>Login</PageTitle>
|
||||
|
||||
<div class="login-wrapper">
|
||||
<EditForm Model="LoginData" FormName="login-form" OnSubmit="OnLogin">
|
||||
<div class="field-wrapper">
|
||||
<h2>Login</h2>
|
||||
<div class="mb-3">
|
||||
<label for="email" class="form-label">Email address</label>
|
||||
<InputText type="email" class="form-control" id="email" required @bind-Value="LoginData.Email"/>
|
||||
@*<ValidationMessage For="() => RegisterData.Email"/>*@
|
||||
</div>
|
||||
<div class="mb-3">
|
||||
<label for="password" class="form-label">Password</label>
|
||||
<InputText type="password" class="form-control" id="password" aria-describedby="passwordHelp" required @bind-Value="LoginData.Password"/>
|
||||
@*<ValidationMessage For="() => RegisterData.Password"/>*@
|
||||
</div>
|
||||
<div class="mb-3">
|
||||
<span>Don't have an account? <NavLink href="register">Register</NavLink></span>
|
||||
</div>
|
||||
<button type="submit" class="btn btn-primary">Login</button>
|
||||
|
||||
@if (_loginError) {
|
||||
<div class="alert alert-danger" role="alert" style="margin-top: 16px; margin-bottom: 0px">
|
||||
Email or password does not match any account!
|
||||
</div>
|
||||
}
|
||||
</div>
|
||||
</EditForm>
|
||||
</div>
|
||||
|
||||
@inject IAuthService Auth
|
||||
@inject NavigationManager Navigator
|
||||
|
||||
@code {
|
||||
[SupplyParameterFromForm]
|
||||
private UserLogin LoginData { get; set; }
|
||||
|
||||
private bool _loginError;
|
||||
|
||||
protected override void OnInitialized() {
|
||||
LoginData ??= new();
|
||||
}
|
||||
|
||||
private async Task OnLogin() {
|
||||
var result = await Auth.Login(LoginData);
|
||||
|
||||
if (!result) {
|
||||
_loginError = true;
|
||||
return;
|
||||
}
|
||||
|
||||
Navigator.NavigateTo(Register.RedirectAfterRegister, true);
|
||||
}
|
||||
}
|
||||
15
HopFrame.Web/Pages/Login.razor.css
Normal file
15
HopFrame.Web/Pages/Login.razor.css
Normal file
@@ -0,0 +1,15 @@
|
||||
.login-wrapper {
|
||||
display: flex;
|
||||
justify-content: center;
|
||||
align-items: center;
|
||||
}
|
||||
|
||||
.field-wrapper {
|
||||
margin-top: 25vh;
|
||||
min-width: 30vw;
|
||||
|
||||
padding: 30px;
|
||||
border: 2px solid #ced4da;
|
||||
border-radius: 10px;
|
||||
position: relative;
|
||||
}
|
||||
@@ -3,13 +3,18 @@
|
||||
@using HopFrame.Web.Model
|
||||
@using HopFrame.Web.Services
|
||||
@using Microsoft.AspNetCore.Components.Forms
|
||||
@using Microsoft.AspNetCore.Components.Routing
|
||||
@using Microsoft.AspNetCore.Components.Web
|
||||
|
||||
@implements IDisposable
|
||||
|
||||
<PageTitle>Register</PageTitle>
|
||||
|
||||
<div class="register-wrapper">
|
||||
<EditForm EditContext="_context" OnValidSubmit="OnRegister" FormName="register-form">
|
||||
@*<AntiforgeryToken/>*@
|
||||
<div class="field-wrapper">
|
||||
<h2>Register</h2>
|
||||
<div class="mb-3">
|
||||
<label for="email" class="form-label">Email address</label>
|
||||
<InputText type="email" class="form-control" id="email" required @bind-Value="RegisterData.Email"/>
|
||||
@@ -31,18 +36,20 @@
|
||||
<InputText type="password" class="form-control" id="passwordRepeat" aria-describedby="passwordHelp" required @bind-Value="RegisterData.RepeatedPassword"/>
|
||||
<ValidationMessage For="() => RegisterData.RepeatedPassword"/>
|
||||
</div>
|
||||
<div class="mb-3">
|
||||
<span>Already have an account? <NavLink href="login">Login</NavLink></span>
|
||||
</div>
|
||||
<button type="submit" class="btn btn-primary">Register</button>
|
||||
</div>
|
||||
</EditForm>
|
||||
</div>
|
||||
|
||||
@inject NavigationManager Navigation
|
||||
@inject NavigationManager Navigator
|
||||
@inject IUserService Users
|
||||
@inject IAuthService Auth
|
||||
|
||||
@code {
|
||||
public static string RedirectAfterRegister { get; set; } = "/";
|
||||
private const string RefreshTokenType = "HopFrame.Security.RefreshToken";
|
||||
|
||||
[SupplyParameterFromForm]
|
||||
private RegisterData RegisterData { get; set; }
|
||||
@@ -74,7 +81,7 @@
|
||||
if (hasConflict) return;
|
||||
|
||||
await Auth.Register(RegisterData);
|
||||
Navigation.NavigateTo(RedirectAfterRegister, true);
|
||||
Navigator.NavigateTo(RedirectAfterRegister, true);
|
||||
}
|
||||
|
||||
private void ValidateForm(object sender, ValidationRequestedEventArgs e) {
|
||||
|
||||
@@ -11,4 +11,5 @@
|
||||
padding: 30px;
|
||||
border: 2px solid #ced4da;
|
||||
border-radius: 10px;
|
||||
position: relative;
|
||||
}
|
||||
|
||||
@@ -1,4 +1,5 @@
|
||||
using HopFrame.Database;
|
||||
using HopFrame.Security.Authentication;
|
||||
using HopFrame.Web.Services;
|
||||
using HopFrame.Web.Services.Implementation;
|
||||
using Microsoft.AspNetCore.Builder;
|
||||
@@ -10,6 +11,9 @@ public static class ServiceCollectionExtensions {
|
||||
public static IServiceCollection AddHopFrameServices<TDbContext>(this IServiceCollection services) where TDbContext : HopDbContextBase {
|
||||
services.AddHttpClient();
|
||||
services.AddScoped<IAuthService, AuthService<TDbContext>>();
|
||||
services.AddTransient<AuthMiddleware>();
|
||||
|
||||
services.AddHopFrameAuthentication<TDbContext>();
|
||||
|
||||
return services;
|
||||
}
|
||||
|
||||
@@ -1,3 +1,4 @@
|
||||
using HopFrame.Database.Models.Entries;
|
||||
using HopFrame.Security.Models;
|
||||
|
||||
namespace HopFrame.Web.Services;
|
||||
@@ -7,6 +8,6 @@ public interface IAuthService {
|
||||
Task<bool> Login(UserLogin login);
|
||||
Task Logout();
|
||||
|
||||
Task<bool> RefreshLogin();
|
||||
Task<TokenEntry> RefreshLogin();
|
||||
Task<bool> IsLoggedIn();
|
||||
}
|
||||
@@ -51,7 +51,7 @@ public class AuthService<TDbContext>(
|
||||
var user = await userService.GetUserByEmail(login.Email);
|
||||
|
||||
if (user == null) return false;
|
||||
if (await userService.CheckUserPassword(user, login.Password)) return false;
|
||||
if (await userService.CheckUserPassword(user, login.Password) == false) return false;
|
||||
|
||||
var refreshToken = new TokenEntry {
|
||||
CreatedAt = DateTime.Now,
|
||||
@@ -100,7 +100,7 @@ public class AuthService<TDbContext>(
|
||||
httpAccessor.HttpContext?.Response.Cookies.Delete(ITokenContext.AccessTokenType);
|
||||
}
|
||||
|
||||
public async Task<bool> RefreshLogin() {
|
||||
public async Task<TokenEntry> RefreshLogin() {
|
||||
if (await IsLoggedIn()) {
|
||||
var oldToken = httpAccessor.HttpContext?.Request.Cookies[ITokenContext.AccessTokenType];
|
||||
var entry = await context.Tokens.SingleOrDefaultAsync(token => token.Token == oldToken);
|
||||
@@ -110,14 +110,14 @@ public class AuthService<TDbContext>(
|
||||
}
|
||||
}
|
||||
|
||||
var refreshToken = httpAccessor.HttpContext?.Request.Cookies[ITokenContext.AccessTokenType];
|
||||
var refreshToken = httpAccessor.HttpContext?.Request.Cookies[ITokenContext.RefreshTokenType];
|
||||
|
||||
if (string.IsNullOrWhiteSpace(refreshToken)) return false;
|
||||
if (string.IsNullOrWhiteSpace(refreshToken)) return null;
|
||||
|
||||
var token = await context.Tokens.SingleOrDefaultAsync(token => token.Token == refreshToken && token.Type == TokenEntry.RefreshTokenType);
|
||||
|
||||
if (token is null) return false;
|
||||
if (token.CreatedAt + HopFrameAuthentication<TDbContext>.RefreshTokenTime < DateTime.Now) return false;
|
||||
if (token is null) return null;
|
||||
if (token.CreatedAt + HopFrameAuthentication<TDbContext>.RefreshTokenTime < DateTime.Now) return null;
|
||||
|
||||
var accessToken = new TokenEntry {
|
||||
CreatedAt = DateTime.Now,
|
||||
@@ -135,7 +135,7 @@ public class AuthService<TDbContext>(
|
||||
Secure = true
|
||||
});
|
||||
|
||||
return true;
|
||||
return accessToken;
|
||||
}
|
||||
|
||||
public async Task<bool> IsLoggedIn() {
|
||||
|
||||
Reference in New Issue
Block a user