授权属性用户/角色

时间:2016-02-18 04:16:40

标签: asp.net angularjs asp.net-mvc asp.net-web-api owin

我是应用程序的授权和安全新手。我建立在使用Owin和AspNet.Identity.EntityFramework的angularjs和web api应用程序之上。我已经能够获得授权,迫使用户注册/登录应用程序。现在,我正在研究如何添加更具体的访问权限,例如管理员角色或特定用户,以查看更敏感的数据。我已经开始使用[Authorize(User="tbryant")]属性了。这迫使了安全。然后我添加了 [RoutePrefix("api/Orders")] public class OrdersController : ApiController { [Authorize(Users="tbryant")] [Route("")] public IHttpActionResult Get() { return Ok(Order.CreateOrders()); } } public class Order { public int OrderID { get; set; } public string CustomerName { get; set; } public string ShipperCity { get; set; } public Boolean IsShipped { get; set; } public static List<Order> CreateOrders() { List<Order> OrderList = new List<Order> { new Order {OrderID = 10248, CustomerName = "Tee Joudeh", ShipperCity = "Cleveland", IsShipped = true }, new Order {OrderID = 10249, CustomerName = "Ahmad Hasan", ShipperCity = "Columbus", IsShipped = false}, new Order {OrderID = 10250,CustomerName = "Thomas Yaser", ShipperCity = "Detroit", IsShipped = false }, new Order {OrderID = 10251,CustomerName = "Lena Jones", ShipperCity = "Ann Arbor", IsShipped = false}, new Order {OrderID = 10252,CustomerName = "Yasmeen Rami", ShipperCity = "Bamberg", IsShipped = true} }; return OrderList; } } ,它不允许其他用户甚至用户使用tbryant登录。在tbryant的AspNetUsers表中有一个用户名。

这是我的api控制器的示例数据:

{{1}}

1 个答案:

答案 0 :(得分:0)

确保&#34; user.Identity.Name&#34;在HttpContext中等于&#34; tbryant&#34;。

以下是Authorize属性的工作原理。

protected virtual bool AuthorizeCore(HttpContextBase httpContext)
{
if (httpContext == null)
{
    throw new ArgumentNullException("httpContext");
}

IPrincipal user = httpContext.User;
if (!user.Identity.IsAuthenticated)
{
    return false;
}

if (_usersSplit.Length > 0 && !_usersSplit.Contains(user.Identity.Name, StringComparer.OrdinalIgnoreCase))
{
    return false;
}

if (_rolesSplit.Length > 0 && !_rolesSplit.Any(user.IsInRole))
{
    return false;
}

return true;
}