如何实现这个mvc过滤器属性?

时间:2018-05-25 19:29:00

标签: c# .net asp.net-web-api asp.net-web-api2

我需要将新的Security API集成到我的组织中的几个现有应用程序中。某些应用程序使用ASP.NET MVC并使用.NET AuthorizeAttribute类来安装具有安全性的类。

例如:

[Authorize(Roles="MY_CORP\Group1,MY_CORP\Group2")]
public class MyClass
{
    //
}

上面的代码基于Windows身份验证配置。我需要更新此实现以使用新的安全API。新的Security API将检索这样的用户:

var user = new SecurityApi().GetUser(userId);
var groups = user.Groups;

理想情况下,更新的装饰器看起来像这样,其中GroupX和GroupY作为user.Groups从Security API返回:

[Authorize(Roles="GroupX, GroupY")]
public class MyClass
{
    //
}

我知道如何实现这个目标吗?

1 个答案:

答案 0 :(得分:0)

我使用了以下内容:

public class RequireAuthAttribute : TypeFilterAttribute
{
    public RequireAuthAttribute(params Roles[] rolesRequirement) 
        : base(typeof(RequireAuthFilter))
    {
        Arguments = new object[] { rolesRequirement };
    }

    public enum Roles: ushort
    {
        CompanyOnly,
        AuthenticatedCustomer,
        AuthorizedCustomer,
        AuthorizedOwnerManager
    }
}

使用:

public class RequireAuthFilter : IAsyncActionFilter
{
    private readonly Roles[] _rolesToAllow;

    public RequireAuthFilter(Roles[] rolesRequirement = default(Roles[]))
    {
        _rolesToAllow = rolesRequirement;
    }

    public async Task OnActionExecutionAsync(
    ActionExecutingContext context, 
    ActionExecutionDelegate next ) 
    {
        // Verify is Authenticated
        if (context.HttpContext.User.Identity.IsAuthenticated != true)
        {
            context.HttpContext.SetResponse(401, "User is not Authenticated");
            return;
        }

        var isCompanyAdmin = context.HttpContext.IsCompanyAdmin(); 
        // ^ HttpContext Extension method that looks at our JWT Token 
        // and determines if has required Cliams/Roles.

        if (isCompanyAdmin == true)
        {
            await next();
            return;
        } else {
            context.HttpContext.SetResponse(401, "Restricted to Company");
            return;
        }

        // Other custom logic for each role.
        // You will want to decide if comma represents AND or an OR 
        // when specifying roles.
    }
}

并像这样使用:

[RequireAuth(Roles.CompanyOnly, Roles.AuthorizedOwnerManager)]
public class MyClass
{
    //
}