gpt4 book ai didi

c# - Odata如何授权用户角色的$expand功能?

转载 作者:行者123 更新时间:2023-11-30 21:34:33 31 4
gpt4 key购买 nike

我想根据角色限制对 $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更多引用

ODataAuthorizationQueryValidatorSample on git hub

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"});

关于c# - Odata如何授权用户角色的$expand功能?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50024122/

31 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com