[英]Authorize Attribute User / Roles
I am new with authorization and security to applications. 我对应用程序的授权和安全性是陌生的。 I'm building upon my angularjs and web api app that uses Owin and AspNet.Identity.EntityFramework. 我正在使用Owin和AspNet.Identity.EntityFramework的angularjs和Web api应用程序为基础。 I've been able to get the authorization working to force a user to either register / log in to the app. 我已经能够获得授权,以强制用户注册/登录该应用程序。 Now I'm looking on how to add more specific access such as a an admin role or specific user to look at more sensitive data. 现在,我正在研究如何添加更特定的访问权限,例如管理员角色或特定用户,以查看更敏感的数据。 I've started with the [Authorize]
attribute. 我从[Authorize]
属性开始。 Which forced the security. 这迫使安全。 Then I added [Authorize(User="tbryant")]
which didnt allow other users and even the user tbryant to log in. There is a user name in the AspNetUsers table of tbryant. 然后,我添加了[Authorize(User="tbryant")]
,它不允许其他用户甚至tbryant用户登录。tbryant的AspNetUsers表中有一个用户名。
Here is my sample data from my api controller: 这是来自我的api控制器的示例数据:
[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;
}
}
Make sure the "user.Identity.Name" in HttpContext is equal to "tbryant". 确保HttpContext中的“ user.Identity.Name”等于“ tbryant”。
Here is how Authorize attribute works. 这是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;
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.