Search code examples
c#dynamics-crm-2011dynamics-crm

OrganizationService throws authentication exception during RetrieveMultiple request


I've a Post|sync|sandbox|Update Message CRM plugin for CRM online 2015, all works fine except RetrieveMultiple call

I've created IOrganizationService

    public static IOrganizationService GetOrganizationServiceByCurrentUser(this IServiceProvider serviceProvider)
    {
        var serviceFactory = serviceProvider.GetService<IOrganizationServiceFactory>();
        var context = serviceProvider.GetService<IPluginExecutionContext>();
        return serviceFactory.CreateOrganizationService(context.UserId);
    }

after call RetrieveMultiple

        Entity config = organizationService.RetrieveMultiple(new FetchExpression(CrmConstants.Query.AzureCofig))
                                           .Entities.FirstOrDefault();

following error is appeared

The authentication endpoint Username was not found on the configured Secure Token Service!

I've tried to do the same thru unit test and CrmConnection all works fine. Looks like something wrong with plugin execution rights. Any idea?


Solution

  • If you retrieve any config sections you have to create IOrganizationService under the system account, not the user context

       public static IOrganizationService GetOrganizationServiceByCurrentUser(this IServiceProvider serviceProvider)
        {
            var serviceFactory = serviceProvider.GetService<IOrganizationServiceFactory>();
            return serviceFactory.CreateOrganizationService(null);
        }