prasad sivvala
prasad sivvala

Reputation: 11

GetAuthenticationStateAsync() is not hitting with Authorize attribute

I have created a .NET Aspire project and implemented JWT authentication. In .NET Aspire, it creates 4 projects Api, Apphost, Service defaults, Blazor Server App.

When I am refreshing page in my Blazor server app without [Authorize] attribute, GetAuthenticationStateAsync() is hit and it is working fine.

When I am refreshing the page with [Authorize] attribute, the GetAuthenticationStateAsync() method is not hit. I am not getting any errors - just a blank screen.

I have tried several ways like registering order of the services.

Can anyone help me to resolve this?

Upvotes: 1

Views: 58

Answers (1)

Qiang Fu
Qiang Fu

Reputation: 8335

You could create a CustomAuthorizationHandler and bypass the authorization when HttpContext is not null.

    public class CustomAuthorizationHandler : AuthorizationHandler<IAuthorizationRequirement>
    {
        protected override Task HandleRequirementAsync(AuthorizationHandlerContext context, IAuthorizationRequirement requirement)
        {
            if (context.Resource != null)
            {
                // Bypass authorization
                context.Succeed(requirement);
            }
            return Task.CompletedTask;
        }
    }

Register it to program.cs

builder.Services.AddSingleton<IAuthorizationHandler, CustomAuthorizationHandler>();

Upvotes: 0

Related Questions