如何使用自定义授权属性多次授权用户

本文关键字:授权 用户 属性 自定义 何使用 | 更新日期: 2023-09-27 17:56:20

我有一个自定义授权属性类来检查isAuthorize两次。

我想要什么 :

1)它将首先检查用户是否super admin。如果他是,那么他将authorized

2)如果he is not,那么它将检查他是否有一个名为"Deal User"的角色。如果he is not那么他将unauthorized.

3)现在如果用户is in"Deal User"角色,我想检查用户是否拥有交易。所以我检查数据库是否用户拥有该交易.如果he owns,那么他将authorized。否则他会被Unauthorized.

public class DealManageCustomAuthorizeAttribute : AuthorizeAttribute
{
    private static ApplicationDbContext Context = new ApplicationDbContext();
    private static UserStore<ApplicationUser> userStore = new UserStore<ApplicationUser>(Context);
    private UserManager<ApplicationUser> userManager = new UserManager<ApplicationUser>(userStore);
    private enum Result
    {
        Authorize,
        Unauthorize,
        InternalServerError
    }
    public override void OnAuthorization(HttpActionContext actionContext)
    {
        var result = AuthorizeRequest(actionContext);
        if (result == Result.Authorize)
        {
            return;
        }
        else
        {
            HandleUnauthorizedRequest(actionContext);
        }
    }
    protected override void HandleUnauthorizedRequest(System.Web.Http.Controllers.HttpActionContext actionContext)
    {
        //Code to handle unauthorized request
        base.HandleUnauthorizedRequest(actionContext);
    }
    private Result AuthorizeRequest(System.Web.Http.Controllers.HttpActionContext actionContext)
    {
        base.Roles = "Super Admin";
        bool authorized = base.IsAuthorized(actionContext);
        if (!authorized)
        {
            try
            {
                base.Roles = "Deal User";
                bool auth = base.IsAuthorized(actionContext);
                if (!auth)
                {
                    return Result.Unauthorize;
                }
                Uri uri = actionContext.Request.RequestUri;
                Guid dealId = new Guid(HttpUtility.ParseQueryString(uri.Query).Get("dealId"));
                string userId = HttpContext.Current.User.Identity.GetUserId();
                var retval = new Deal(Common.Common.TableSureConnectionString).CheckDealByIdAndUserId(dealId, userId);
                if (retval)
                {
                    return Result.Authorize;
                }
                return Result.Unauthorize;
            }
            catch (Exception)
            {
                return Result.InternalServerError;
            }
        }
        return Result.Authorize;
    }
}

我编写了代码,它正在工作。但我想知道它是否是授权用户的正确方法?

如何使用自定义授权属性多次授权用户

目前尚不清楚您的自定义授权属性不起作用的确切原因,但很明显它的实现过于复杂。

AuthorizeAttribute具有简单的布尔函数IsAuthorized,您可以(并且应该)覆盖该函数以返回用户是否获得授权。基本实现已经检查

  1. 用户是否已登录。
  2. 用户是否属于提供的角色之一。

因此,您需要做的就是在用户处于交易用户角色时添加其他逻辑。

永远不要访问 Web API/MVC 中的静态HttpContext.Current成员。在这种特殊情况下,actionContext作为参数传入,您可以(并且应该)使用该参数。

using Microsoft.AspNet.Identity;
using System;
using System.Linq;
using System.Net.Http;
using System.Security.Principal;
using System.Web.Http;
using System.Web.Http.Controllers;
[AttributeUsage(AttributeTargets.Method | AttributeTargets.Class, AllowMultiple = true)]
public class DealManageCustomAuthorizeAttribute : AuthorizeAttribute
{
    public DealManageCustomAuthorizeAttribute()
    {
        // Set the Super Admin and Deal User roles
        this.Roles = "Super Admin,Deal User";
    }
    protected override bool IsAuthorized(HttpActionContext actionContext)
    {
        // This checks whether the user is logged in, and whether
        // they are in the Super Admin or Deal User role.
        var isAuthorized = base.IsAuthorized(actionContext);
        IPrincipal user = actionContext.ControllerContext.RequestContext.Principal;
        // Special case - user is in the Deal User role
        if (isAuthorized && user.IsInRole("Deal User"))
        {
            var queryString = actionContext.Request.GetQueryNameValuePairs()
                .ToDictionary(kv => kv.Key, kv => kv.Value, StringComparer.OrdinalIgnoreCase);
            // Ensure the query string contains the key "dealId"
            if (!queryString.ContainsKey("dealId"))
            {
                return false;
            }
            Guid dealId;
            if (!Guid.TryParse(queryString["dealId"], out dealId))
            {
                // If the Guid cannot be parsed, return unauthorized
                return false;
            }
            // Now check whether the deal is authorized.
            var userId = user.Identity.GetUserId();
            return new Deal(Common.Common.TableSureConnectionString)
                .CheckDealByIdAndUserId(dealId, userId);
        }
        return isAuthorized;
    }
}