Fallback Policy Log Authorization Events

Viewed 486

Is possible to raise FallbackPolicy authorization events without creating my own AuthorizationHandler or AuthorizationFilter? Ideally I want to raise OnTokenValidated or OnAuthFailure events and log accordingly.

public void ConfigureServices(IServiceCollection services)
{
    services.AddMicrosoftIdentityWebApiAuthentication(Configuration);

    services.AddControllers();

    services.AddAuthorization(options =>
    {
        options.FallbackPolicy = new AuthorizationPolicyBuilder().RequireAuthenticatedUser().Build();

    });

    // ..
}
1 Answers

FallbackPolicy is used when there is no instance of IAuthorizeData (such as from AuthorizeAttribute) associated with any resources and it's used only by AuthorizationMiddleware. I think it's confusing to fire events like OnAuthFailure or OnTokenValidated as you want in that case. But that's your part. Here I just want to show one point at which you can inject your code to raise the events you want. Actually it's just a kind of inline authorization handler, you can specify the code right when building the fallback policy with AuthorizationPolicyBuilder, like this:

options.FallbackPolicy = new AuthorizationPolicyBuilder()
                             .RequireAuthenticatedUser()
                             .RequireAssertion(context => {
                                 //here you can inject your code
                                 //return true/false to make the requirement valid/invalid
                                 //for logging purpose, we can return true here
                                 return true;
                              }).Build();
Related