对Angular2 / 4和Web API 2中具有特定ID的资源进行Auth0授权

时间:2017-08-19 08:51:37

标签: angular asp.net-web-api2 auth0

我有一个内容管理系统,可以编辑3D地图。我想基于每个用户进行授权,这样用户只能在以下情况下PUT / DELETE / GET某个MapId:

  • 用户拥有地图
  • 用户是管理员

我查看了范围,但这些方法感觉错误,因为“编辑:地图”的范围不能与MapIds不同,只有用户可以编辑任何地图。

另一种方法是使用auth0规则,如下所示:

function (user, context, callback) {    

    var allAuthorizedMapIdsForUser = someExternalDbCall();

    context.idToken['https://authorizedMapids.com'] = allAuthorizedMapIdsForUser;

    callback(null, user, context);
}

但我不确定如何在ASP NET Web API 2中实现和使用它。

第三种也许是最冗余的方法是在每种API方法中实施手动授权:

    [HttpGet]
    public async Task<IHttpActionResult> GetMap(int mapId)
    {
        var userId = //somehow get userId

                            // Checks some DB-table if user has MapId or is admin
        bool isAuthorized = this.IsUserAuthorizedForMapId(mapId, userId);

        if (!isAuthorized)
            return Unauthorized();

        // ..perform GET
    }

有什么想法吗?

1 个答案:

答案 0 :(得分:0)

我可以建议你为AspNetIdentiy创建一个自定义[授权]装饰,它不是基于角色的,而是User-Based ......

例如

(假设你像这样使用AspNET Identity for Webapi:http://bitoftech.net/2015/01/21/asp-net-identity-2-with-asp-net-web-api-2-accounts-management/ ......或任何其他教程)

[AttributeUsage(AttributeTargets.Class | AttributeTargets.Method, Inherited = true, AllowMultiple = true)] 
public class CustomAuthorizeAttribute : AuthorizeAttribute
{
    /// <summary>
    /// aallowed ids you opass external or if you prefer you can deo a query in the AuthorizeCore method
    /// </summary>
   public  string IDS { get; set; }

    /// <summary>
    /// Checks to see if the user is authenticated and has the
    /// correct role to access a particular view.
    /// </summary>
    /// <param name="httpContext"></param>
    /// <returns></returns>
    protected override bool AuthorizeCore(HttpContextBase httpContext)
    {
        if (httpContext == null)
            throw new ArgumentNullException("httpContext");

        if (!httpContext.User.Identity.IsAuthenticated)
            return false;

           var userId = User.Identity.GetUserId();//get current userid
            ApplicationUserManager UserManager = HttpContext.GetOwinContext().GetUserManager<ApplicationUserManager>();//get usermanage

            var IDSAllowed = IDS.Split(",").ToList();

            bool isAuthorized = IDSAllowed.Any()?  IDSAllowed.Contains(userId) : false; //if you prefer you can deo a query on DB to retrive allowed IDS

        if (!isAuthorized)
            return Unauthorized();

        return true;
    }

    protected override void HandleUnauthorizedRequest(AuthorizationContext filterContext)
    {
        if (filterContext == null)
            throw new ArgumentNullException("filterContext");

        filterContext.Result = new ViewResult { ViewName = "NotAuthorized" };
    } 
}

然后您可以在控制器中将其用作

[CustomAuthorize(IDS = "1,2,9")]
     [HttpGet]
    public async Task<IHttpActionResult> GetMap(int mapId)
    {

    }

这样的东西..希望它对你有帮助!