简体   繁体   中英

Custom Authorization attribute asp.net core

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?

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 .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM