liveBook · Manning

Fail

As explained in ASP.NET Core in Action, 3e

Fail is an authorization context operation that records explicit failure of an authorization requirement and its containing policy.

Fail explicitly marks an authorization requirement as failed. When a handler calls context.Fail(), the requirement fails even if another handler previously called Succeed(), so the containing policy cannot authorize. section 24.7

Rejecting a banned lounge visitor

A BannedFromLoungeHandler checks for the IsBannedFromLounge claim. When the claim exists, it calls context.Fail(); otherwise it leaves the context unchanged so other handlers can still satisfy the requirement. section 24.4.2

Listing 24.10 Calling context.Fail() in a handler to fail the requirement
public class BannedFromLoungeHandler :
    AuthorizationHandler<AllowedInLoungeRequirement>                    #1
{
    protected override Task HandleRequirementAsync(                     #2
        AuthorizationHandlerContext context,                            #2
        AllowedInLoungeRequirement requirement)                         #2
    {
        if(context.User.HasClaim(c => c.Type == "IsBannedFromLounge"))  #3
        {
            context.Fail();                                             #4
        }
 
        return Task.CompletedTask;                                      #5
    }
}

See the complete handler that explicitly fails the lounge requirement when a banned-user claim is present. section 24.4.2

Use Fail deliberately:

  • Leave the context untouched when the handler cannot decide; another handler may call Succeed(). section 24.7
  • Call Fail() only when the handler must override successful results from other handlers. section 24.7
  • Register the handler with the dependency-injection container so authorization can execute it. section 24.4.2

How ASP.NET Core in Action, 3e covers it

How deep it goes
Explains explicit failure, handler interaction, and registration, but does not detail Fail overloads or internal middleware implementation.
Examples
Uses a banned-lounge claim and a BannedFromLoungeHandler to demonstrate explicit authorization failure.
What it assumes
Assumes authorization policies, requirements, handlers, claims, and Succeed are understood.
What you can do after
Apply it via ASP.NET Core authorization handlers to ensure disqualifying claims reject a policy despite other successful handlers.
How it connects
Connects authorization handlers, authorization requirements, authorization policies, Succeed, and claims-based authorization.

Also explained in

Compare how 2 books explain Fail →

Related concepts

This explainer was generated by Manning's knowledge graph from the text of ASP.NET Core in Action, 3e. The section links point to the parts of the book it draws on.