示例#1
0
 /// <inheritdoc />
 /// <summary>
 /// 构造
 /// </summary>
 /// <param name="cacheManager"></param>
 /// <param name="dynamics365Options"></param>
 /// <param name="oAuthService"></param>
 /// <param name="asyncLocker"></param>
 public OAuthMessageHandler(
     Dynamics365Option dynamics365Options,
     ICacheManager cacheManager,
     IOAuthService oAuthService,
     IAsyncLocker asyncLocker)
 {
     _dynamics365Options = dynamics365Options;
     _cacheManager       = cacheManager;
     _oAuthService       = oAuthService;
     _asyncLocker        = asyncLocker;
 }
        /// <summary>
        /// 构建请求Token参数
        /// </summary>
        /// <param name="dynamics365Option"></param>
        /// <returns></returns>
        private static List <KeyValuePair <string, string> > BuildTokenParams(Dynamics365Option dynamics365Option)
        {
            var content = new List <KeyValuePair <string, string> >()
            {
                new KeyValuePair <string, string>("client_id", dynamics365Option.ClientId),
                new KeyValuePair <string, string>("client_secret", dynamics365Option.ClientSecret),
                new KeyValuePair <string, string>("resource", dynamics365Option.Resource),
                new KeyValuePair <string, string>("username", $"{dynamics365Option.DomainName}\\{dynamics365Option.UserName}"),
                new KeyValuePair <string, string>("password", dynamics365Option.Password),
                new KeyValuePair <string, string>("grant_type", "password"),
            };

            return(content);
        }
        /// <summary>
        /// 验证参数
        /// </summary>
        private static void VerifyParams(Dynamics365Option dynamics365Option)
        {
            if (dynamics365Option == null)
            {
                throw new ArgumentNullException(nameof(dynamics365Option));
            }

            if (string.IsNullOrWhiteSpace(dynamics365Option.ADFSUri))
            {
                throw new ArgumentNullException(nameof(dynamics365Option.ADFSUri));
            }

            if (string.IsNullOrWhiteSpace(nameof(dynamics365Option.Resource)))
            {
                throw new ArgumentNullException(nameof(dynamics365Option.Resource));
            }

            if (string.IsNullOrWhiteSpace(dynamics365Option.ClientId))
            {
                throw new ArgumentNullException(nameof(dynamics365Option.ClientId));
            }

            if (string.IsNullOrWhiteSpace(dynamics365Option.ClientSecret))
            {
                throw new ArgumentNullException(nameof(dynamics365Option.ClientSecret));
            }

            if (string.IsNullOrWhiteSpace(dynamics365Option.DomainName))
            {
                throw new ArgumentNullException(nameof(dynamics365Option.DomainName));
            }

            if (string.IsNullOrWhiteSpace(dynamics365Option.UserName))
            {
                throw new ArgumentNullException(nameof(dynamics365Option.UserName));
            }

            if (string.IsNullOrWhiteSpace(dynamics365Option.Password))
            {
                throw new ArgumentNullException(nameof(dynamics365Option.Password));
            }
        }
 public Adfs4OAuthService(HttpClient httpClient, Dynamics365Option dynamics365Option)
 {
     _httpClient        = httpClient;
     _dynamics365Option = dynamics365Option;
 }
        /// <summary>
        /// Adds services to the specified <see cref="T:Microsoft.Extensions.DependencyInjection.IServiceCollection"/>.
        /// </summary>
        /// <typeparam name="TCacheManager">缓存管理</typeparam>
        /// <param name="services">
        /// The <see cref="T:Microsoft.Extensions.DependencyInjection.IServiceCollection"/> to add
        /// services to.
        /// </param>
        /// <param name="setupAction">An <see cref="T:System.Action`1"/> to configure the provided</param>
        /// <returns>
        /// The <see cref="T:Microsoft.Extensions.DependencyInjection.IServiceCollection"/> so that
        /// additional calls can be chained.
        /// </returns>
        public static IServiceCollection AddD365WebApiClientService <TCacheManager>(this IServiceCollection services, Action <Dynamics365Option> setupAction)
        {
            if (services == null)
            {
                throw new ArgumentNullException(nameof(services));
            }

            if (setupAction == null)
            {
                throw new ArgumentNullException(nameof(setupAction));
            }

            var options = new Dynamics365Option();

            setupAction(options);
            services.TryAddSingleton(options);
            services.TryAddTransient <OAuthMessageHandler>();
            services.AddHttpClient <IApiClientService, ApiClientService>(httpClient =>
            {
                httpClient.BaseAddress = new Uri(options.WebApiAddress);
                httpClient.Timeout     = new TimeSpan(0, 2, 0);
                httpClient.DefaultRequestHeaders.Add("OData-MaxVersion", "4.0");
                httpClient.DefaultRequestHeaders.Add("OData-Version", "4.0");
                httpClient.DefaultRequestHeaders.Add("Accept", "application/json");
            }).ConfigurePrimaryHttpMessageHandler((serviceProvider) =>
            {
                var httpClientHandler = new HttpClientHandler()
                {
                    AllowAutoRedirect     = true,
                    UseDefaultCredentials = true
                };
                var dynamic365Option = serviceProvider.GetRequiredService <Dynamics365Option>();
                if ((dynamic365Option.Dynamics365Type == Dynamics365Type.OnPremises))
                {
                    httpClientHandler.Credentials = new NetworkCredential(dynamic365Option.UserName, dynamic365Option.Password, dynamic365Option.DomainName);
                }
                return(httpClientHandler);
            }).AddHttpMessageHandler <OAuthMessageHandler>();
            switch (options.Dynamics365Type)
            {
            case Dynamics365Type.IFD_ADFS_V3:
                services.AddHttpClient <Adfs3OAuthService>(httpClient =>
                {
                    httpClient.BaseAddress = new Uri(options.ADFSUri);
                    httpClient.Timeout     = new TimeSpan(0, 2, 0);
                }).ConfigurePrimaryHttpMessageHandler((serviceProvider) =>
                {
                    var httpClientHandler = new HttpClientHandler()
                    {
                        AllowAutoRedirect     = false,
                        UseDefaultCredentials = true
                    };
                    httpClientHandler.ServerCertificateCustomValidationCallback +=
                        (message, certificate2, arg3, arg4) => true;
                    return(httpClientHandler);
                });
                services.TryAddTransient <IOAuthService>(serviceProvider => serviceProvider.GetRequiredService <Adfs3OAuthService>());
                break;

            case Dynamics365Type.Online:
                //todo online resource
                throw new ArgumentOutOfRangeException();

            case Dynamics365Type.IFD_ADFS_V4:
                services.AddHttpClient <Adfs4OAuthService>(httpClient =>
                {
                    httpClient.BaseAddress = new Uri(options.ADFSUri);
                    httpClient.Timeout     = new TimeSpan(0, 2, 0);
                }).ConfigurePrimaryHttpMessageHandler((serviceProvider) =>
                {
                    var httpClientHandler = new HttpClientHandler()
                    {
                        AllowAutoRedirect     = false,
                        UseDefaultCredentials = true
                    };
                    httpClientHandler.ServerCertificateCustomValidationCallback +=
                        (message, certificate2, arg3, arg4) => true;
                    return(httpClientHandler);
                });
                services.TryAddTransient <IOAuthService>(serviceProvider => serviceProvider.GetRequiredService <Adfs4OAuthService>());
                break;

            case Dynamics365Type.OnPremises:
                break;

            default:
                throw new ArgumentOutOfRangeException();
            }
            services.TryAddScoped(typeof(ICacheManager), typeof(TCacheManager));
            services.TryAddScoped <IAsyncLocker, AsyncLocker>();
            services.TryAddScoped <IApiClientService, ApiClientService>();
            return(services);
        }