简体   繁体   中英

Environment dependent controller with [Authorize]

To mark a controller as requiring authorization you typically decorate it like this:

[Authorize]
public class MyController : Controller

Our auth is through a 3rd party provider and given the way it is setup, we only want this to actually be in effect in our production environment, we don't want it to be active in QA environment for example. It's easy to toggle off environment in the Startup.cs file but is there a way to conditionally decorate the controllers? I started looking at policies and roles and that seem like it might be hacked to work but is there a better way?

If you are using Asp.NET Core, Following the documentation here:

https://docs.microsoft.com/en-us/aspnet/core/security/authorization/policies?view=aspnetcore-2.1 https://docs.microsoft.com/en-us/aspnet/core/security/authorization/dependencyinjection?view=aspnetcore-2.1

You can make your custom policy like so:

public class EnvironmentAuthorize : IAuthorizationRequirement
{
    public string Environment { get; set; }

    public EnvironmentAuthorize(string env)
    {
        Environment = env;
    }
}

public class EnvironmentAuthorizeHandler : AuthorizationHandler<EnvironmentAuthorize>
{
    private readonly IHostingEnvironment envionment;

    public EnvironmentAuthorizeHandler(IHostingEnvironment env)
    {
        envionment = env;
    }

    protected override Task HandleRequirementAsync(AuthorizationHandlerContext context, EnvironmentAuthorize requirement)
    {
        if (requirement.Environment != envionment.EnvironmentName)
        {
            context.Succeed(requirement);
        }

        return Task.CompletedTask;
    }
}

In de Startup.cs:

        services.AddAuthorization(options =>
        {
            options.AddPolicy("ProductionOnly", policy =>
                policy.Requirements.Add(new EnvironmentAuthorize("Production")));
        });

        services.AddSingleton<IAuthorizationHandler, EnvironmentAuthorizeHandler>();

In the Controller:

[Authorize(Policy = "ProductionOnly")]
public class MyController : Controller

Although it's possible, i can not recommend this, having different behaviors in different environments is truly a nightmare.

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