Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

130 activity based auto logout #135

Merged
merged 9 commits into from
May 11, 2022
2 changes: 1 addition & 1 deletion src/Application/Users/UserService.cs
Original file line number Diff line number Diff line change
Expand Up @@ -95,7 +95,7 @@ private string GenerateJwtToken(User user)
Subject = new ClaimsIdentity(CreateClaims(user)),
Audience = _config[ConfigurationKeys.JwtIssuer],
Issuer = _config[ConfigurationKeys.JwtIssuer],
Expires = DateTime.UtcNow.AddHours(1),
Expires = DateTime.Now.AddMonths(1),
SigningCredentials =
new SigningCredentials(new SymmetricSecurityKey(key), SecurityAlgorithms.HmacSha256Signature),
};
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -77,6 +77,7 @@ private void Authenticate(AuthenticateResponse authentication)
{
// Store token on http client so all future requests use the token.
_http.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("bearer", authentication.Token);
Console.WriteLine($"setting bearer to {_http.DefaultRequestHeaders.Authorization}");
IsAuthenticated = true;
Username = authentication.Username;
AuthenticationStateChanged?.Invoke(this, new AuthenticationEventArgs { State = authentication, });
Expand Down
1 change: 1 addition & 0 deletions src/Client/Shared/FetchData.razor
Original file line number Diff line number Diff line change
Expand Up @@ -63,6 +63,7 @@ else
/// </summary>
public async Task Fetch(string url)
{
Console.WriteLine($"fetching with {_http.DefaultRequestHeaders.Authorization}");
HttpResponseMessage response = await _http.GetAsync(url);

if (!response.IsSuccessStatusCode)
Expand Down
37 changes: 32 additions & 5 deletions src/Client/Shared/MainLayout.razor
Original file line number Diff line number Diff line change
@@ -1,9 +1,11 @@
@using Application.Users
@using Client.Services.Authentication
@using System.Timers
@inherits LayoutComponentBase
@inject ISessionService _session
@inject IJSRuntime Js
@inject HttpClient Http
@inject ISessionService Session
@inject NavigationManager NavigationManager

<CascadingValue Value="@_session" Name="Session">
<CascadingValue Value="@Session" Name="Session">
<ThemeProvider Theme="@_theme">
<div class="page">
<main>
Expand Down Expand Up @@ -35,9 +37,34 @@
IsRounded = true,
};

private const int InactivityLogoutMilliseconds = 1000 * 60 * 15; // 15 minutes

private readonly Timer _timer = new(InactivityLogoutMilliseconds);

/// <inheritdoc />
protected override async Task OnInitializedAsync()
{
await _session.TryResumeAsync();
await Session.TryResumeAsync();

_timer.Elapsed += LogOut;
_timer.AutoReset = false;

// Register JS-callbacks on the document that call ResetTimer when triggered.
await Js.InvokeVoidAsync("registerActivityCallback", DotNetObjectReference.Create(this));
}

/// <summary>
/// Resets the inactivity timer. Call when user has shown signs of activity.
/// </summary>
[JSInvokable]
public void ResetTimer()
{
_timer.Stop();
_timer.Start();
}

private void LogOut(object? sender, ElapsedEventArgs elapsedEventArgs)
{
InvokeAsync(async () => await Session.EndAsync());
}
}
9 changes: 9 additions & 0 deletions src/Client/wwwroot/js/interop.js
Original file line number Diff line number Diff line change
Expand Up @@ -8,3 +8,12 @@ function focusElement(selector) {
const element = document.querySelector(selector);
element.focus();
}

function registerActivityCallback(dotNetHelper) {
document.onmousemove = resetTimeDelay;
document.onkeydown = resetTimeDelay;

function resetTimeDelay() {
dotNetHelper.invokeMethodAsync("ResetTimer");
}
}
6 changes: 6 additions & 0 deletions src/Server/Program.cs
Original file line number Diff line number Diff line change
Expand Up @@ -60,6 +60,12 @@
builder.Services.AddControllers()
.AddNewtonsoftJson();

builder.Services.AddHttpLogging(logging =>
{
logging.RequestHeaders.Add("authorization");
logging.ResponseHeaders.Add("WWW-Authenticate");
});

WebApplication app = builder.Build();

// Configure the HTTP request pipeline.
Expand Down