Custom Authorization attribute asp.net core

user911

I am trying to figure out what is the best way to create custom authorization attribute for my asp.net core application. I have seen this post and I am aware of the 2 approaches discussed here. How do you create a custom AuthorizeAttribute in ASP.NET Core?

1) Using IAuthorizationFilter

2) Using Policies

I saw that the official document suggests that we should be using policies and not IAuthorizationFilter but I felt that using policies for my scenario is an overkill. I personally liked IAuthorizationFilter approach more.

I have a very basic requirement. I want to create an authorize attribute for my web api and need to throw 403 if the current user is not whitelisted to use this API. I really don't care about the scopes(canRead, canWrite, can readWrite etc). If I go ahead with policy approach, I may be using the same policy for all my APIs. What is the best way to achieve this?

nlawalker

Using policies for something like this isn't overkill. You need a requirement:

public class WhitelistRequirement: IAuthorizationRequirement
{
}

A handler:

public class WhitelistHandler : AuthorizationHandler<WhitelistRequirement>
{

    // Implement a constructor to inject dependencies, such as your whitelist

    protected override Task HandleRequirementAsync(AuthorizationHandlerContext context,
                                                   WhitelistRequirement requirement)
    {
        if (isInWhitelist) // Your implementation here
        {
            context.Succeed(requirement);
        }

        return Task.CompletedTask;
    }
}

Register both in ConfigureServices:

services.AddAuthorization(options =>
            options.AddPolicy("WhitelistPolicy",
            b => b.AddRequirements(new WhitelistRequirement())));

services.AddSingleton<IAuthorizationHandler, WhitelistHandler>();

Then use your policy:

[Authorize(Policy = "WhitelistPolicy")]

You can apply the policy globally with a global filter:

services.AddMvc(config =>
{
    var policy = new AuthorizationPolicyBuilder()
                     .AddRequirements(new WhitelistRequirement())
                     .Build();
    config.Filters.Add(new AuthorizeFilter(policy));
})

The resulting behavior for unauthenticated or forbidden users depends on the implementation of the "challenge" and "forbid" behaviors in your app's authentication handler.

See here.

Collected from the Internet

Please contact [email protected] to delete if infringement.

edited at
0

Comments

0 comments
Login to comment

Related

Asp Net Core 3.1 Authorization by Custom Roles

custom authorization in asp.net core mvc

How create custom authorization attribute for checking a role and url path in Asp.Net Core?

Custom Authorization attribute doesn't allow authorize in asp.net core 3

Custom Authorize attribute - ASP .NET Core 2.2

ASP.NET Core Custom Authorization & Memory Cache

Custom authorization filter not working in ASP.NET Core 3

Custom authorization in ASP.NET Core with enum roles

Asp.Net Core custom authorization always ends with 401 Unauthorized

Authorization failing for custom authentication handler for ASP.NET Core 3.1?

ASP.NET Core Custom Policy Based Authorization - unclear

Custom Bearer Token Authorization for ASP.Net Core

Custom Authorization in Asp.net core 2.1 web api

Using the Authorize Attribute with Custom Cookie Authentication in ASP.NET Core

ASP.NET Core custom validation attribute localization

ASP.NET Core Custom Validation Attribute Not Firing

How to get custom attribute name for action in asp.net core?

Asp.net core web api Localization DataAnnotation custom attribute

.net core 3 middleware or authorization attribute ? and how to?

ASP.NET Core Custom Role Based Authorization (Custom User.IsInRole)?

IsAuthenticated is always false in Custom Authorization Attribute (.NET Core 2.2 and Jason Web Token)

Authorization in ASP.NET Core. Always 401 Unauthorized for [Authorize] attribute

Custom Authorization Filter in .NET Core API

Custom Attribute settings in .net Core

Need advice of where to put custom user authorization in ASP.NET Core

How to access current HttpContext in ASP.NET Core 2 Custom Policy-Based Authorization with AuthorizationHandlerContext

Intercept asp.net core Authorize action to perform custom action upon successful authorization

ASP.Net Core 3.0 Windows Authentication with Custom Role Based Authorization

ASP.NET Core 3.1 MVC Access Denied role based authorization - Conflict with custom UserClaimsPrincipalFactory