以编程方式将[AllowAnonymous]属性添加到我的所有控制器方法中 [英] Programmatically add [AllowAnonymous] attribute to all my controller methods

查看:167
本文介绍了以编程方式将[AllowAnonymous]属性添加到我的所有控制器方法中的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个带有多个控制器的WebAPI2 REST api.我使用基于角色的身份验证.我在所有控制器和某些方法上都添加了[Authorize]属性.但是,在DEV环境中,我想禁用身份验证.我希望可以将一些代码放入WebApiConfig中,例如:

I have a WebAPI2 REST api with several controllers. I use role based authentication. I put [Authorize] attributes on all my controllers and some methods. However, in the DEV environment I want to disable authentication. I was hoping that I can put some code into the WebApiConfig such as:

public static class WebApiConfig
{
    public static void Register(HttpConfiguration config)
    {
        config.MapHttpAttributeRoutes();
        config.EnableCors(new EnableCorsAttribute("*", "*", "*"));

        //==============================================
        // NOTE: disable all authentication in the DEV_ENVIRONMENT

        if (Environment.GetEnvironmentVariable("DEV_ENVIRONMENT") == "1")
        {
            config.Filters.Add(new AllowAnonymousAttribute());
        }
    }
}

但是,这不会编译,因为

However, this does not compile, because

error CS1503: Argument 1: cannot convert from 
'System.Web.Http.AllowAnonymousAttribute' to 
'System.Web.Http.Filters.IFilter'

在运行时是否可以关闭我的REST api中的所有身份验证?

Is there a way at runtime to turn off all authentication in my REST api?

推荐答案

我不会删除"授权.假设您有一个客户,并且CustomerId是一个声明,那么由于缺少声明,您将无法测试代码.相反,我会选择出于开发目的添加身份.

I wouldn't 'remove' authorization. Suppose you have a customer and CustomerId is a claim, then you can't test the code because claims are missing. Instead I would choose to add an identity for development purposes.

可能是黑客,但我的策略是在设置当前用户的地方添加一个过滤器,其中包括所需的角色:

It's probably a hack, but my strategy would be to add a filter where the current user is set including the required roles(s):

using System.Security.Principal;
using System.Web;
using System.Web.Http.Controllers;
using System.Web.Http.Filters;

public class AddIdentityFilter : AuthorizationFilterAttribute
{
    public override void OnAuthorization(HttpActionContext actionContext)
    {
        HttpContext.Current.User = new GenericPrincipal(new GenericIdentity("John"), new[] { "Admin" });
        base.OnAuthorization(actionContext);
    }
}

在WebApiConfig.cs中添加过滤器:

In WebApiConfig.cs add the filter:

public static class WebApiConfig
{
    public static void Register(HttpConfiguration config)
    {
        config.SuppressDefaultHostAuthentication();

        // Add some logic here to determine the environment
        var isDevelopment = true;

        if (isDevelopment)
            config.Filters.Add(new AddIdentityFilter());

        // ...
    }

这样,您可以在开发时定义多个测试场景.

This way you can define multiple scenarios for testing while developing.

这是 asp.net core 3.0 应用程序的类似方法.在Startup.Configure中:

And here's a similar approach for an asp.net core 3.0 app. In Startup.Configure:

if (env.IsDevelopment())
{
    // Custom authentication
    app.Use(async (context, next) =>
    {
        // Set claims for the test user.
        var claims = new[] { new Claim("role", "Admin"), new Claim("sub", "some guid") };
        var id = new ClaimsIdentity(claims, "DebugAuthorizationMiddleware", "name", "role");
        // Add the test user as Identity.
        context.User.AddIdentity(id);
        // User is now authenticated.
        await next.Invoke();
    });
}
else
{
    // use configured authentication
    app.UseAuthentication();
}
app.UseAuthorization();

这篇关于以编程方式将[AllowAnonymous]属性添加到我的所有控制器方法中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆