Quantcast
Channel: Active questions tagged blazor - Stack Overflow
Viewing all articles
Browse latest Browse all 4839

@attribute [Authorized] not recognizing authenticated user?

$
0
0

I have a Blazor Web App and I'm am trying to add authentication. I can verify that my user is logged in by calling the following code on one of my unsecured pages:

 private async Task CheckAuth()    {        var state = await AuthStateProvider.GetAuthenticationStateAsync();        var user = state.User;        if (user.Identity.IsAuthenticated)        {            Console.WriteLine("User is authenticated!");        }        else        {            Console.WriteLine("User is NOT authenticated.");        }    }

But, as soon as I try to visit the following page with @attribute [Authorized], to shows that my user is NOT logged in:

@using Aelios.Client.Layout@using Microsoft.AspNetCore.Authorization@using Microsoft.AspNetCore.Components.Authorization@page "/secure/dashboard"@attribute [Authorize]@layout AdminLayout<PageTitle>Dashboard</PageTitle>INSIDE SECURE DASHBOARD@code {}

If I however REMOVE the attribute and try the following, it shows that the user indeed IS authenticated:

@using Aelios.Client.Layout@using Microsoft.AspNetCore.Authorization@using Microsoft.AspNetCore.Components.Authorization@page "/secure/dashboard"@layout AdminLayout<PageTitle>Dashboard</PageTitle>INSIDE SECURE DASHBOARD<CascadingAuthenticationState><AuthorizeView><Authorized><p>✅ You are authorized!</p><p>👤 User: @context.User.Identity.Name</p><p>🔹 Claims:</p><ul>                @foreach (var claim in context.User.Claims)                {<li>@claim.Type: @claim.Value</li>                }</ul></Authorized><NotAuthorized>❌ You are NOT authorized!</NotAuthorized></AuthorizeView></CascadingAuthenticationState>@code {}

This is my Routes.razor file:

<CascadingAuthenticationState><Router AppAssembly="typeof(Program).Assembly"><Found Context="routeData">            @if (routeData.PageType.GetCustomAttributes(typeof(AuthorizeAttribute), true).Any())            {<AuthorizeRouteView RouteData="routeData" DefaultLayout="typeof(Layout.AdminLayout)"><NotAuthorized><LayoutView Layout="typeof(Layout.MainLayout)"><p>You are not authorized to view this page. Please <a href="/login">log in</a>.</p></LayoutView></NotAuthorized></AuthorizeRouteView>            }            else            {<RouteView RouteData="routeData" DefaultLayout="typeof(Layout.MainLayout)"/>            }</Found><NotFound><LayoutView Layout="typeof(Layout.MainLayout)"><p>Sorry, the page was not found.</p></LayoutView></NotFound></Router></CascadingAuthenticationState>

This is making no sense to me at all, hopefully someone can see something I don't?


Viewing all articles
Browse latest Browse all 4839

Trending Articles



<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>