【问题标题】:how to implement this mvc filter attribute?如何实现这个 mvc 过滤器属性?
【发布时间】:2018-11-05 05:44:32
【问题描述】:

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

例如:

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

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

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

因此,理想情况下,更新后的装饰器应如下所示,其中 GroupX 和 GroupY 作为从安全 API 返回的 user.Groups 存在:

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

知道我将如何实现这一点吗?

【问题讨论】:

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


【解决方案1】:

我使用了一些类似的东西:

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
{
    //
}

【讨论】:

  • 看起来 TypeFilterAttribute 属于 Microsoft.AspNetCore.Mvc 包。我需要在目标框架为 4.5.2 的应用程序中实现该解决方案。 TypeFilterAttribute 解决方案可以与 4.5.2 解决方案一起使用吗?或者您能推荐 4.5.2 的替代方法吗?
  • 我需要几个小时才能得到代码。但它可以通过谷歌搜索实现。大约 6 个月前,我将此解决方案移植到 .Net Core。今晚下班后将发布解决方案。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2017-03-08
  • 2021-01-26
  • 1970-01-01
  • 2014-01-21
  • 1970-01-01
  • 2021-08-31
  • 1970-01-01
相关资源
最近更新 更多