c# - Odata 如何对用户角色的 $expand 功能进行授权?
问题描述
我想根据角色限制对 $expand 操作的访问。我的问题需要限制用户角色对某些实体的访问。有人可以给出一些关于从哪里开始的提示吗?
解决方案
您可以使用此代码片段进行授权我从http://www.software-architects.com/devblog/2014/09/12/10-OData-FAQs得到, 代码太多
[Authorize]
[ODataRoutePrefix("Customer")]
public class CustomerController : ODataController
{
[...]
[EnableQuery]
public IHttpActionResult Get()
{
if (!string.IsNullOrWhiteSpace(((ClaimsPrincipal)Thread.CurrentPrincipal).Claims.FirstOrDefault(c => c.Type == "IsAdmin").Value))
{
return Ok(context.Customers);
}
return Unauthorized();
}
[...]
}
或创建扩展方法 IEdmModelBuilder 更多参考
git hub 上的ODataAuthorizationQueryValidatorSample
using System;
using System.Linq;
using System.Reflection;
using System.Web.OData;
using Microsoft.OData.Edm;
namespace MHS.Assessments.WebAPI.Utilities
{
public static class IEdmModelBuilderExtensions
{
public static void AddAuthorizedRolesAnnotations(this IEdmModel edmModel)
{
var typeAnnotationsMapping = edmModel.SchemaElementsAcrossModels()
.OfType<IEdmEntityType>()
.Where(t => edmModel.GetAnnotationValue<ClrTypeAnnotation>(t) != null)
.Select(t => edmModel.GetAnnotationValue<ClrTypeAnnotation>(t).ClrType)
.ToDictionary(clrType => clrType,
clrType => clrType.GetCustomAttributes<CanExpandAttribute>(inherit: false));
foreach (var kvp in typeAnnotationsMapping)
{
foreach (var attribute in kvp.Value)
{
attribute.SetRoles(edmModel, kvp.Key);
}
}
}
public static void SetAuthorizedRolesOnType(this IEdmModel model,string typeName,string[] roles)
{
IEdmEntityType type = model.FindType(typeName) as IEdmEntityType;
if (type == null)
{
throw new InvalidOperationException("The authorized element must be an entity type");
}
model.SetAnnotationValue<AuthorizedRoles>(type, new AuthorizedRoles(roles));
}
}
}
WebApiConfig.ca
edmModel.SetAuthorizedRolesOnType("Customers", new string[] { "Support"});
推荐阅读
- javascript - javascript 用鼠标自动完成
- r - 如果字符串的一部分存在于另一列中,则删除一列中的部分字符串
- vim - Terraform fmt 因缩进错误而失败
- flutter - 在颤振插件 image_picker 示例中从图库中选择图像时内存增加
- java - 即使数学正确,矩形也不跟随鼠标
- apache-spark - 如何修复无法连接到 spark-shell 中的 hdfs?
- swift - Xcode - 无法单击标签栏上方的插入标签栏项目
- reactjs - React:如何在内容大小未知时为展开和折叠 Div 设置动画
- python-3.x - 我正在尝试打开一个文件,查找“r”或“R”作为每个单词的第一个字母,然后打印这些单词
- php - PHP MySQL 使用 INSERT SELECT 后将插入的值设置为 PHP 变量