Skip to content
Draft
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 2 additions & 0 deletions CookieAuthenticationExample/App.razor
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,8 @@
@*this gets displayed if the user is not authorized to view the page*@
<NotAuthorized>
<p>Sie sind nicht berechtigt, diese Seite aufzurufen.</p>

<LoginControl></LoginControl>
</NotAuthorized>
</AuthorizeRouteView>
<FocusOnNavigate RouteData="@routeData" Selector="h1" />
Expand Down
11 changes: 11 additions & 0 deletions CookieAuthenticationExample/Models/NavigationPages.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,11 @@
namespace CookieAuthenticationExample.Models
{
public class NavigationPages
{
public const string Home = "/";

public const string Login = "/Login";
public const string WeatherForecast = "/fetchdata";
public const string Counter = "/counter";
}
}
104 changes: 57 additions & 47 deletions CookieAuthenticationExample/Pages/FetchData.razor
Original file line number Diff line number Diff line change
Expand Up @@ -2,8 +2,10 @@
@using CookieAuthenticationExample.Data

@using System.Security.Claims
@using CookieAuthenticationExample.Models
@inject AuthenticationStateProvider AuthenticationStateProvider
@inject WeatherForecastService ForecastService
@inject NavigationManager NavigationManager

@attribute [Authorize]

Expand All @@ -13,65 +15,73 @@

<p>This component demonstrates fetching data from a service.</p>

<button @onclick="Refresh">Refresh</button>

@if (forecasts == null)
{
<p>
<em>Loading...</em>
</p>
<p>
<em>Loading...</em>
</p>
}
else
{
<table class="table">
<thead>
<tr>
<th>Date</th>
<th>Temp. (C)</th>
<th>Temp. (F)</th>
<th>Summary</th>
</tr>
</thead>
<tbody>
@foreach (var forecast in forecasts)
{
<tr>
<td>@forecast.Date.ToShortDateString()</td>
<td>@forecast.TemperatureC</td>
<td>@forecast.TemperatureF</td>
<td>@forecast.Summary</td>
</tr>
}
</tbody>
</table>
<table class="table">
<thead>
<tr>
<th>Date</th>
<th>Temp. (C)</th>
<th>Temp. (F)</th>
<th>Summary</th>
</tr>
</thead>
<tbody>
@foreach (var forecast in forecasts)
{
<tr>
<td>@forecast.Date.ToShortDateString()</td>
<td>@forecast.TemperatureC</td>
<td>@forecast.TemperatureF</td>
<td>@forecast.Summary</td>
</tr>
}
</tbody>
</table>
}

@code {
private WeatherForecast[]? forecasts;
private IEnumerable<Claim> claims = Enumerable.Empty<Claim>();
private IEnumerable<string> userClaimRoles = Enumerable.Empty<string>();
private WeatherForecast[]? forecasts;
private IEnumerable<Claim> claims = Enumerable.Empty<Claim>();
private IEnumerable<string> userClaimRoles = Enumerable.Empty<string>();

private async Task GetClaimsPrincipalData()
{
var authState = await AuthenticationStateProvider.GetAuthenticationStateAsync();
var user = authState.User;
if (user.Identity is not null && user.Identity.IsAuthenticated)
{
claims = user.Claims;
userClaimRoles = user.Claims.Select(a => a.Value).ToList();
}

private async Task GetClaimsPrincipalData()
{
var authState = await AuthenticationStateProvider.GetAuthenticationStateAsync();
var user = authState.User;
if (user.Identity is not null && user.Identity.IsAuthenticated)
{
claims = user.Claims;
userClaimRoles = user.Claims.Select(a => a.Value).ToList();
}
if (userClaimRoles.Contains("Administrator"))
{
//yayyy admin
}
}

if (userClaimRoles.Contains("Administrator"))
{
//yayyy admin
}
}
private Task Refresh()
{
NavigationManager.NavigateTo(NavigationPages.WeatherForecast, true);
return Task.CompletedTask;
}


protected override async Task OnInitializedAsync()
{
//dummy call to simulate claim user role check
GetClaimsPrincipalData();
protected override async Task OnInitializedAsync()
{
//dummy call to simulate claim user role check
await GetClaimsPrincipalData();

forecasts = await ForecastService.GetForecastAsync(DateOnly.FromDateTime(DateTime.Now));
}
forecasts = await ForecastService.GetForecastAsync(DateOnly.FromDateTime(DateTime.Now));
}

}
3 changes: 2 additions & 1 deletion CookieAuthenticationExample/Pages/LogOut.cshtml.cs
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
using CookieAuthenticationExample.Models;
using Microsoft.AspNetCore.Authentication;
using Microsoft.AspNetCore.Authentication.Cookies;
using Microsoft.AspNetCore.Mvc;
Expand All @@ -12,7 +13,7 @@ public async Task<IActionResult> OnGetAsync()
// Clear the existing external cookie
await HttpContext.SignOutAsync(CookieAuthenticationDefaults.AuthenticationScheme);

return LocalRedirect(Url.Content("~/"));
return LocalRedirect(NavigationPages.Home);
}
}
}
8 changes: 4 additions & 4 deletions CookieAuthenticationExample/Pages/Login.cshtml.cs
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.RazorPages;
using System.Security.Claims;
using CookieAuthenticationExample.Models;
using CookieAuthenticationExample.Services;
using Microsoft.AspNetCore.Authorization;

Expand All @@ -21,9 +22,8 @@ public LoginModel(UserService userService)
public async Task<IActionResult> OnGetAsync(string paramUsername, string paramPassword)
{
if (string.IsNullOrEmpty(paramUsername) || string.IsNullOrEmpty(paramPassword))
return LocalRedirect("/");
return LocalRedirect(NavigationPages.Home);

string returnUrl = Url.Content("~/");
try
{
// Clear the existing external cookie
Expand All @@ -35,7 +35,7 @@ public async Task<IActionResult> OnGetAsync(string paramUsername, string paramPa
if (!_userService.CheckDatabaseIfPasswordMatches(paramUsername, paramPassword))
{
//no login possible
return LocalRedirect(returnUrl);
return LocalRedirect(NavigationPages.Home);
}

//todo get user roles from Database via UserService
Expand All @@ -60,7 +60,7 @@ public async Task<IActionResult> OnGetAsync(string paramUsername, string paramPa
string error = ex.Message;

}
return LocalRedirect(returnUrl);
return LocalRedirect(NavigationPages.Home);
}
}

Expand Down
9 changes: 8 additions & 1 deletion CookieAuthenticationExample/Program.cs
Original file line number Diff line number Diff line change
Expand Up @@ -14,11 +14,18 @@
builder.Services.AddAuthentication(CookieAuthenticationDefaults.AuthenticationScheme)
.AddCookie(options =>
{
options.ExpireTimeSpan = TimeSpan.FromSeconds(30);
options.ExpireTimeSpan = TimeSpan.FromSeconds(5);
options.SlidingExpiration = true;
options.AccessDeniedPath = "/Forbidden";
options.LoginPath = "/login";

options.Cookie = new CookieBuilder()
{
SameSite = SameSiteMode.Lax,
SecurePolicy = CookieSecurePolicy.SameAsRequest,
HttpOnly = true,
};

});

builder.Services.AddSingleton<IHttpContextAccessor, HttpContextAccessor>();
Expand Down
16 changes: 12 additions & 4 deletions CookieAuthenticationExample/Shared/NavMenu.razor
Original file line number Diff line number Diff line change
@@ -1,4 +1,7 @@
<div class="top-row ps-3 navbar navbar-dark">
@using CookieAuthenticationExample.Models
@inject NavigationManager NavigationManager

<div class="top-row ps-3 navbar navbar-dark">
<div class="container-fluid">
<a class="navbar-brand" href="">CookieAuthenticationExample</a>
<button title="Navigation menu" class="navbar-toggler" @onclick="ToggleNavMenu">
Expand All @@ -15,12 +18,12 @@
</NavLink>
</div>
<div class="nav-item px-3">
<NavLink class="nav-link" href="counter">
<NavLink class="nav-link" href="counter" @onclick='() => NavigateTo(NavigationPages.Counter)'>
<span class="oi oi-plus" aria-hidden="true"></span> Counter
</NavLink>
</div>
</div>`
<div class="nav-item px-3">
<NavLink class="nav-link" href="fetchdata">
<NavLink class="nav-link" href="fetchdata" @onclick='() => NavigateTo(NavigationPages.WeatherForecast)'>
<span class="oi oi-list-rich" aria-hidden="true"></span> Fetch data
</NavLink>
</div>
Expand All @@ -37,4 +40,9 @@
{
collapseNavMenu = !collapseNavMenu;
}

private void NavigateTo(string url)
{
NavigationManager.NavigateTo(url, true);
}
}