Search code examples
c#asp.net-web-api2authorizationodata

Odata How to Authorization on $expand functionality of user Roles?


I want to restrict access to $expand operation Based on Roles. My problem need to restrict access to some entity for user Roles.can someone gives some hints on where to start?


Solution

  • you can do AUTHORIZATION using this code snippetI get that from http://www.software-architects.com/devblog/2014/09/12/10-OData-FAQs easy with too much code

    [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();
        }
    
        [...]
    }
    

    or Create Extensions Method IEdmModelBuilder more reference in

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