简体   繁体   中英

Azure API management choose policy for restricting particular group

I am trying to restrict a group from accessing an operation. but having some error:

One or more fields contain incorrect values: Error in element 'choose' on line 15, column 6: Cannot convert lambda expression to type 'IGroup' because it is not a delegate type

Please find below code

 <policies>
        <inbound>
        <choose>
        <when condition="@(context.User.Groups.Contains(g => g.name == "audit"))">
             <return-response>
                  <set-status code="403" reason="Unauthorized" />
                  <set-body>Users in group audit do not have access to this method. </set-body>
             </return-response>
        </when>
    </choose>
            <base />
        </inbound>
        <backend>
            <base />
        </backend>
        <outbound>
            <base />
        </outbound>
        <on-error>
            <base />
        </on-error>
    </policies>

Looks like there's two different issues with the current policy.

  1. The property name is Name , not name (see IGroup )
  2. You can't use Contains() , while Any() works

The context.User.Groups property is of type IEnumerable<IGroup> . API Management policy expressions only allow/support a selected list of types and members.
The Contains() implementation in the supported System.Linq.Enumerable class doesn't have an overload accepting a Func . It only has Contains<TSource>(IEnumerable<TSource>, TSource) and Contains<TSource>(IEnumerable<TSource>, TSource, IEqualityComparer<TSource>) .

The Any() implementation does have an overload that accepts a Func ( Any(IEnumerable, Func<TSource,Boolean>) ).

So you might need to use Any() , checking the Name property like this:

<when condition="@(context.User.Groups.Any(g => g.Name == "audit"))">

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM