HandleRequirementAsync not being called in Auth handler in Blazor app

Viewed 856

Im trying to come to grips with using a custom auth handler in a serverside Blazor app. I have a breakpoint in my handler, but its not getting hit. Whats missing?

Requirement

public class ValidUserRequirement : IAuthorizationRequirement
{
    public bool MustBeValid { get; }

    public ValidUserRequirement(bool IsValid)
    {
        MustBeValid = IsValid;
    }
}

Policies

public static class Policies
{

    public const string IsValidUser = "IsValidUser";


    public static AuthorizationPolicy IsValidUserPolicy()
    {
        return new AuthorizationPolicyBuilder().RequireAuthenticatedUser()                                                  
                                               .Build();
    }
}

Handler

public class MyAuthHandler : AuthorizationHandler<ValidUserRequirement>
{

    protected override Task HandleRequirementAsync(AuthorizationHandlerContext context, ValidUserRequirement requirement)
    {    
        // will do checks against Db here
        return Task.CompletedTask;
    }
}

Excerpt from startup.cs

// Our services
services.AddAuthorization(config =>
{
    config.AddPolicy("IsValidUser", policy => policy.AddRequirements(new ValidUserRequirement(true)));
});
services.AddSingleton<IAuthorizationHandler, MyAuthHandler>();
services.AddScoped<AuthenticationStateProvider, ServerAuthenticationStateProvider>();   

auth attribute on blazor page

@attribute [Authorize(Policy = Policies.IsValidUser)]   

app.razor

<Router AppAssembly="@typeof(Program).Assembly">
    <Found Context="routeData">
        <RouteView RouteData="@routeData" DefaultLayout="@typeof(MainLayout)" />
    </Found>
    <NotFound>
        <LayoutView Layout="@typeof(MainLayout)">
            <p>Sorry, there's nothing at this address.</p>
        </LayoutView>
    </NotFound>
</Router>

[ update ]
Ok, I created a new project, server-side blazor, using windows auth and pulled in this same code. I could successfully hit a breakpoint in the auth handler, so something is off in the project im working on.

0 Answers
Related