Hiding menu element by permission using AngularJS and Web API

别等时光非礼了梦想. 提交于 2020-01-25 20:08:09

问题


I have implemented roles based authorization in my Web API RESTfull service using OWIN.

What would be the best way to hide menu items or buttons based on the role that the user has? I want to hide the items that the user has no access to.

UPDATED

I want to know what the best practice is for my controller.

This is an example of what I want, but I don't think it is the right way to do it. Second, the routing fails because it cannot distinguish between the two actions.

[Authorize(Roles = "SomeRole")]
public class FooController : ApiController
{
    [HttpGet]
    public string HelloWorld()
    {
         return "Hello world - you are authorized";
    }

    [HttpGet]
    [Route("hasaccess")]
    [AllowAnonymous]
    public bool HasAccess()
    {
         return User.IsInRole("SomeRole");
    }
}

http://localhost:8080/api/foo/ --> calls HelloWorld()

http://localhost:8080/api/foo/hasaccess --> calls HasAccess()


回答1:


You could use ng-if directive. It will render this div only if hasRole function returns true.

<div ng-if="hasRole('admin')"> 
                  Admin menu item
</div>

And then in controller have a function

$scope.hasRole = function(role){
    //check if user has needed Role
    //return true or false
}


来源:https://stackoverflow.com/questions/38095870/hiding-menu-element-by-permission-using-angularjs-and-web-api

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!