protected BaseRequest(AuthenticationRequestParameters authenticationRequestParameters)
        {
            this.Authenticator = authenticationRequestParameters.Authenticator;
            this.CallState = CreateCallState(this.Authenticator.CorrelationId);

            PlatformPlugin.Logger.Information(this.CallState,
                string.Format(CultureInfo.InvariantCulture,"=== Token Acquisition started:\n\tAuthority: {0}\n\tScope: {1}\n\tClientId: {2}\n\tCacheType: {3}",
                Authenticator.Authority, authenticationRequestParameters.Scope.AsSingleString(), authenticationRequestParameters.ClientKey.ClientId,
                (tokenCache != null) ? tokenCache.GetType().FullName + string.Format(CultureInfo.InvariantCulture," ({0} items)", tokenCache.Count) : "null"));

            this.tokenCache = authenticationRequestParameters.TokenCache;
            this.ClientKey = authenticationRequestParameters.ClientKey;
            this.Policy = authenticationRequestParameters.Policy;
            this.restrictToSingleUser = authenticationRequestParameters.RestrictToSingleUser;

            if (MsalStringHelper.IsNullOrEmpty(authenticationRequestParameters.Scope))
            {
                throw new ArgumentNullException("scope");
            }
            
            this.Scope = authenticationRequestParameters.Scope.CreateSetFromArray();
            ValidateScopeInput(this.Scope);


            this.LoadFromCache = (tokenCache != null);
            this.StoreToCache = (tokenCache != null);
            this.SupportADFS = false;
            
            if (this.tokenCache != null && (restrictToSingleUser && this.tokenCache.GetUniqueIdsFromCache(this.ClientKey.ClientId).Count() > 1))
            {
                throw new ArgumentException(
                    "Cache cannot have entries for more than 1 unique id when RestrictToSingleUser is set to TRUE.");
            }
        }
Esempio n. 2
0
        /// <summary>
        /// 获取access_token。会缓存,过期后自动重新获取新的token。
        /// </summary>
        public static string GetAccessToken(WeChatParam param)
        {
            var appId = GetConfig.GetAppid(param);
            var secret = GetConfig.GetSecret(param);
            if (!AccessTokensCache.ContainsKey(appId) || AccessTokensCache[appId] == null
                    || AccessTokensCache[appId].ExpireTime < DateTime.Now)
            {
                var result = HttpHelper.Get<TokenResult>(ApiList.GetTokenUrl, new HttpParam
                    {
                        {"grant_type", "client_credential"},
                        {"appid", appId},
                        {"secret", secret}
                    });
                if (!result.IsSuccess)
                    throw new WxException(result.errcode, result.errmsg);
                AccessTokensCache[appId] = new TokenCache
                {
                    AccessToken = result.access_token,
                    ExpireTime = DateTime.Now.AddSeconds(result.expires_in - 60)
                };
            }
            return AccessTokensCache[appId].AccessToken;

        }
Esempio n. 3
0
        /// <summary>
        /// Returns a SharePoint ClientContext using Azure Active Directory authentication. This requires that you have a Azure AD Native Application registered. The user will be prompted for authentication.
        /// </summary>
        /// <param name="siteUrl">Site for which the ClientContext object will be instantiated</param>
        /// <param name="clientId">The Azure AD Native Application Client ID</param>
        /// <param name="redirectUri">The Azure AD Native Application Redirect Uri</param>
        /// <param name="tokenCache">Optional token cache. If not specified an in-memory token cache will be used</param>
        /// <returns></returns>
        public ClientContext GetAzureADNativeApplicationAuthenticatedContext(string siteUrl, string clientId, Uri redirectUri, TokenCache tokenCache = null)
        {
            var clientContext = new ClientContext(siteUrl);

            _contextUrl  = siteUrl;
            _tokenCache  = tokenCache;
            _clientId    = clientId;
            _redirectUri = redirectUri;
            clientContext.ExecutingWebRequest += clientContext_NativeApplicationExecutingWebRequest;

            return(clientContext);
        }
 public CustomProvider(OpenIdConfig config, TokenCache tokenCache) : base(config, tokenCache)
 {
 }
        private AuthenticationRequestParameters CreateAuthenticationParametersAndSetupMocks(
            MockHttpAndServiceBundle harness,
            int numAuthorizationPendingResults,
            out HashSet <string> expectedScopes,
            bool isAdfs = false)
        {
            var cache      = new TokenCache(harness.ServiceBundle, false);
            var parameters = harness.CreateAuthenticationRequestParameters(
                isAdfs ? TestConstants.OnPremiseAuthority : TestConstants.AuthorityHomeTenant,
                null,
                cache,
                null,
                extraQueryParameters: TestConstants.ExtraQueryParameters,
                claims: TestConstants.Claims);

            if (!isAdfs)
            {
                harness.HttpManager.AddInstanceDiscoveryMockHandler();
            }

            expectedScopes = new HashSet <string>();
            expectedScopes.UnionWith(TestConstants.s_scope);
            expectedScopes.Add(OAuth2Value.ScopeOfflineAccess);
            expectedScopes.Add(OAuth2Value.ScopeProfile);
            expectedScopes.Add(OAuth2Value.ScopeOpenId);

            // Mock Handler for device code request
            harness.HttpManager.AddMockHandler(
                new MockHttpMessageHandler
            {
                ExpectedMethod   = HttpMethod.Post,
                ExpectedPostData = new Dictionary <string, string>()
                {
                    { OAuth2Parameter.ClientId, TestConstants.ClientId },
                    { OAuth2Parameter.Scope, expectedScopes.AsSingleString() },
                    { OAuth2Parameter.Claims, TestConstants.Claims }
                },
                ResponseMessage     = isAdfs ? CreateAdfsDeviceCodeResponseSuccessMessage() : CreateDeviceCodeResponseSuccessMessage(),
                ExpectedQueryParams = TestConstants.ExtraQueryParameters,
            });

            for (int i = 0; i < numAuthorizationPendingResults; i++)
            {
                harness.HttpManager.AddMockHandler(
                    new MockHttpMessageHandler
                {
                    ExpectedMethod  = HttpMethod.Post,
                    ExpectedUrl     = isAdfs ? "https://fs.contoso.com/adfs/oauth2/token" : "https://login.microsoftonline.com/home/oauth2/v2.0/token",
                    ResponseMessage = MockHelpers.CreateFailureMessage(
                        HttpStatusCode.Forbidden,
                        "{\"error\":\"authorization_pending\"," +
                        "\"error_description\":\"AADSTS70016: Pending end-user authorization." +
                        "\\r\\nTrace ID: f6c2c73f-a21d-474e-a71f-d8b121a58205\\r\\nCorrelation ID: " +
                        "36fe3e82-442f-4418-b9f4-9f4b9295831d\\r\\nTimestamp: 2015-09-24 19:51:51Z\"," +
                        "\"error_codes\":[70016],\"timestamp\":\"2015-09-24 19:51:51Z\",\"trace_id\":" +
                        "\"f6c2c73f-a21d-474e-a71f-d8b121a58205\",\"correlation_id\":" +
                        "\"36fe3e82-442f-4418-b9f4-9f4b9295831d\"}")
                });
            }

            if (numAuthorizationPendingResults > 0)
            {
                // Mock Handler for devicecode->token exchange request
                harness.HttpManager.AddMockHandler(
                    new MockHttpMessageHandler
                {
                    ExpectedMethod   = HttpMethod.Post,
                    ExpectedPostData = new Dictionary <string, string>()
                    {
                        { OAuth2Parameter.ClientId, TestConstants.ClientId },
                        { OAuth2Parameter.Scope, expectedScopes.AsSingleString() }
                    },
                    ResponseMessage = isAdfs ? MockHelpers.CreateAdfsSuccessTokenResponseMessage() : MockHelpers.CreateSuccessTokenResponseMessage()
                });
            }

            return(parameters);
        }
        /// <summary>
        /// For testing purposes only: allows testing token expiration.
        /// </summary>
        /// <param name="domain">The active directory domain or tenantId to authenticate with.</param>
        /// <param name="clientId">The active directory clientId for the application.</param>
        /// <param name="authenticationProvider">A source for the secure secret for this application.</param>
        /// <param name="settings">The active directory service side settings, including authority and token audience.</param>
        /// <param name="cache">The token cache to target during authentication.</param>
        /// <param name="expiration">The token expiration.</param>
        /// <returns>A ServiceClientCredentials object that can authenticate http requests as the given application.</returns>
        internal static async Task <ServiceClientCredentials> LoginSilentAsync(string domain, string clientId,
                                                                               IApplicationAuthenticationProvider authenticationProvider, ActiveDirectoryServiceSettings settings, TokenCache cache, DateTimeOffset expiration)
        {
            var audience   = settings.TokenAudience.OriginalString;
            var context    = GetAuthenticationContext(domain, settings, cache);
            var authResult = await authenticationProvider.AuthenticateAsync(clientId, audience, context).ConfigureAwait(false);

            return(new TokenCredentials(
                       new ApplicationTokenProvider(context, audience, clientId, authenticationProvider, authResult, expiration),
                       authResult.TenantId,
                       authResult.UserInfo == null ? null : authResult.UserInfo.DisplayableId));
        }
 /// <summary>
 /// Creates ServiceClientCredentials for authenticating requests as an active directory application using a certificate credential. Uses the default service settings
 /// for azure resource manager (authority, token audience) during authentication.
 /// See <see href="https://azure.microsoft.com/en-us/documentation/articles/active-directory-devquickstarts-dotnet/">Active Directory Quickstart for .Net</see>
 /// for detailed instructions on creating an Azure Active Directory application.
 /// </summary>
 /// <param name="domain">The active directory domain or tenantId to authenticate with.</param>
 /// <param name="certificate">The certificate associated with Active Directory application.</param>
 /// <param name="cache">The token cache to target during authentication.</param>
 /// <returns>A ServiceClientCredentials object that can authenticate http requests as the given application.</returns>
 public static async Task <ServiceClientCredentials> LoginSilentWithCertificateAsync(string domain, ClientAssertionCertificate certificate, TokenCache cache)
 {
     return(await LoginSilentAsync(domain, certificate, ActiveDirectoryServiceSettings.Azure, cache).ConfigureAwait(false));
 }
Esempio n. 8
0
        public SubscriptionCloudCredentials GetSubscriptionCloudCredentials(AzureContext context, AzureEnvironment.Endpoint targetEndpoint)
        {
            if (context.Subscription == null)
            {
                var exceptionMessage = targetEndpoint == AzureEnvironment.Endpoint.ServiceManagement
                    ? Resources.InvalidDefaultSubscription
                    : Resources.NoSubscriptionInContext;
                throw new ApplicationException(exceptionMessage);
            }

            if (context.Account == null)
            {
                var exceptionMessage = targetEndpoint == AzureEnvironment.Endpoint.ServiceManagement
                    ? Resources.AccountNotFound
                    : Resources.ArmAccountNotFound;
                throw new ArgumentException(exceptionMessage);
            }

            if (context.Account.Type == AzureAccount.AccountType.Certificate)
            {
                var certificate = AzureSession.DataStore.GetCertificate(context.Account.Id);
                return(new CertificateCloudCredentials(context.Subscription.Id.ToString(), certificate));
            }

            if (context.Account.Type == AzureAccount.AccountType.AccessToken)
            {
                return(new TokenCloudCredentials(context.Subscription.Id.ToString(), context.Account.GetProperty(AzureAccount.Property.AccessToken)));
            }

            string tenant = null;

            if (context.Subscription != null && context.Account != null)
            {
                tenant = context.Subscription.GetPropertyAsArray(AzureSubscription.Property.Tenants)
                         .Intersect(context.Account.GetPropertyAsArray(AzureAccount.Property.Tenants))
                         .FirstOrDefault();
            }

            if (tenant == null && context.Tenant != null && context.Tenant.Id != Guid.Empty)
            {
                tenant = context.Tenant.Id.ToString();
            }

            if (tenant == null)
            {
                var exceptionMessage = targetEndpoint == AzureEnvironment.Endpoint.ServiceManagement
                    ? Resources.TenantNotFound
                    : Resources.NoTenantInContext;
                throw new ArgumentException(exceptionMessage);
            }

            try
            {
                var tokenCache = AzureSession.TokenCache;
                TracingAdapter.Information(
                    Resources.UPNAuthenticationTrace,
                    context.Account.Id,
                    context.Environment.Name,
                    tenant);
                if (context.TokenCache != null && context.TokenCache.Length > 0)
                {
                    tokenCache = new TokenCache(context.TokenCache);
                }

                var token = Authenticate(
                    context.Account,
                    context.Environment,
                    tenant,
                    null,
                    ShowDialog.Never,
                    tokenCache,
                    context.Environment.GetTokenAudience(targetEndpoint));

                if (context.TokenCache != null && context.TokenCache.Length > 0)
                {
                    context.TokenCache = tokenCache.Serialize();
                }

                TracingAdapter.Information(
                    Resources.UPNAuthenticationTokenTrace,
                    token.LoginType,
                    token.TenantId,
                    token.UserId);

                return(new AccessTokenCredential(context.Subscription.Id, token));
            }
            catch (Exception ex)
            {
                TracingAdapter.Information(Resources.AdalAuthException, ex.Message);
                var exceptionMessage = targetEndpoint == AzureEnvironment.Endpoint.ServiceManagement
                    ? Resources.InvalidSubscriptionState
                    : Resources.InvalidArmContext;
                throw new ArgumentException(exceptionMessage, ex);
            }
        }
Esempio n. 9
0
 public FormTokenViewer(TokenCache tokenCache)
 {
     InitializeComponent();
     _tokenCache = tokenCache;
     ShowTokens();
 }
Esempio n. 10
0
        public void SliceParametersTest()
        {
            Authority authority = Authority.CreateAuthority(TestConstants.AuthorityHomeTenant, false);

            cache = new TokenCache()
            {
                ClientId = TestConstants.ClientId
            };

            MockWebUI ui = new MockWebUI()
            {
                MockResult = new AuthorizationResult(AuthorizationStatus.Success,
                                                     TestConstants.AuthorityHomeTenant + "?code=some-code"),
                QueryParamsToValidate = new Dictionary <string, string>()
                {
                    { "key1", "value1%20with%20encoded%20space" },
                    { "key2", "value2" }
                }
            };

            //add mock response for tenant endpoint discovery
            HttpMessageHandlerFactory.AddMockHandler(new MockHttpMessageHandler
            {
                Method          = HttpMethod.Get,
                ResponseMessage = MockHelpers.CreateOpenIdConfigurationResponse(TestConstants.AuthorityHomeTenant)
            });

            MockHttpMessageHandler mockHandler = new MockHttpMessageHandler();

            mockHandler.Method      = HttpMethod.Post;
            mockHandler.QueryParams = new Dictionary <string, string>()
            {
                { "key1", "value1%20with%20encoded%20space" },
                { "key2", "value2" }
            };
            mockHandler.ResponseMessage = MockHelpers.CreateSuccessTokenResponseMessage();
            HttpMessageHandlerFactory.AddMockHandler(mockHandler);

            AuthenticationRequestParameters parameters = new AuthenticationRequestParameters()
            {
                Authority       = authority,
                SliceParameters = "key1=value1%20with%20encoded%20space&key2=value2",
                ClientId        = TestConstants.ClientId,
                Scope           = TestConstants.Scope,
                TokenCache      = cache,
                RequestContext  = new RequestContext(Guid.Empty, null)
            };

            parameters.RedirectUri          = new Uri("some://uri");
            parameters.ExtraQueryParameters = "extra=qp";

            InteractiveRequest request = new InteractiveRequest(parameters,
                                                                TestConstants.ScopeForAnotherResource.ToArray(),
                                                                TestConstants.DisplayableId,
                                                                UIBehavior.SelectAccount, ui);
            Task <AuthenticationResult> task = request.RunAsync();

            task.Wait();
            AuthenticationResult result = task.Result;

            Assert.IsNotNull(result);
            Assert.AreEqual(1, cache.TokenCacheAccessor.RefreshTokenCacheDictionary.Count);
            Assert.AreEqual(1, cache.TokenCacheAccessor.AccessTokenCacheDictionary.Count);
            Assert.AreEqual(result.AccessToken, "some-access-token");

            Assert.IsTrue(HttpMessageHandlerFactory.IsMocksQueueEmpty, "All mocks should have been consumed");
        }
Esempio n. 11
0
        public void NoCacheLookup()
        {
            Authority authority = Authority.CreateAuthority(TestConstants.AuthorityHomeTenant, false);

            cache = new TokenCache()
            {
                ClientId = TestConstants.ClientId
            };

            AccessTokenCacheItem atItem = new AccessTokenCacheItem()
            {
                Authority              = TestConstants.AuthorityHomeTenant,
                ClientId               = TestConstants.ClientId,
                RawIdToken             = MockHelpers.CreateIdToken(TestConstants.UniqueId, TestConstants.DisplayableId),
                RawClientInfo          = MockHelpers.CreateClientInfo(),
                TokenType              = "Bearer",
                ExpiresOnUnixTimestamp = MsalHelpers.DateTimeToUnixTimestamp(DateTime.UtcNow + TimeSpan.FromSeconds(3599)),
                ScopeSet               = TestConstants.Scope
            };

            atItem.IdToken    = IdToken.Parse(atItem.RawIdToken);
            atItem.ClientInfo = ClientInfo.CreateFromJson(atItem.RawClientInfo);
            AccessTokenCacheKey atKey = atItem.GetAccessTokenItemKey();

            atItem.AccessToken = atKey.ToString();
            cache.TokenCacheAccessor.AccessTokenCacheDictionary[atKey.ToString()] = JsonHelper.SerializeToJson(atItem);

            MockWebUI ui = new MockWebUI()
            {
                MockResult = new AuthorizationResult(AuthorizationStatus.Success,
                                                     TestConstants.AuthorityHomeTenant + "?code=some-code")
            };

            //add mock response for tenant endpoint discovery
            HttpMessageHandlerFactory.AddMockHandler(new MockHttpMessageHandler
            {
                Method          = HttpMethod.Get,
                ResponseMessage = MockHelpers.CreateOpenIdConfigurationResponse(TestConstants.AuthorityHomeTenant)
            });

            MockHttpMessageHandler mockHandler = new MockHttpMessageHandler();

            mockHandler.Method = HttpMethod.Post;

            mockHandler.ResponseMessage = MockHelpers.CreateSuccessTokenResponseMessage();
            HttpMessageHandlerFactory.AddMockHandler(mockHandler);

            AuthenticationRequestParameters parameters = new AuthenticationRequestParameters()
            {
                Authority      = authority,
                ClientId       = TestConstants.ClientId,
                Scope          = TestConstants.Scope,
                TokenCache     = cache,
                RequestContext = new RequestContext(Guid.Empty, null)
            };

            parameters.RedirectUri          = new Uri("some://uri");
            parameters.ExtraQueryParameters = "extra=qp";

            InteractiveRequest request = new InteractiveRequest(parameters,
                                                                TestConstants.ScopeForAnotherResource.ToArray(),
                                                                TestConstants.DisplayableId,
                                                                UIBehavior.SelectAccount, ui);
            Task <AuthenticationResult> task = request.RunAsync();

            task.Wait();
            AuthenticationResult result = task.Result;

            Assert.IsNotNull(result);
            Assert.AreEqual(1, cache.TokenCacheAccessor.RefreshTokenCacheDictionary.Count);
            Assert.AreEqual(2, cache.TokenCacheAccessor.AccessTokenCacheDictionary.Count);
            Assert.AreEqual(result.AccessToken, "some-access-token");

            Assert.IsTrue(HttpMessageHandlerFactory.IsMocksQueueEmpty, "All mocks should have been consumed");

            Assert.IsNotNull(_myReceiver.EventsReceived.Find(anEvent =>  // Expect finding such an event
                                                             anEvent[EventBase.EventNameKey].EndsWith("ui_event") && anEvent[UiEvent.UserCancelledKey] == "false"));
            Assert.IsNotNull(_myReceiver.EventsReceived.Find(anEvent =>  // Expect finding such an event
                                                             anEvent[EventBase.EventNameKey].EndsWith("api_event") && anEvent[ApiEvent.UiBehaviorKey] == "select_account"));
        }
Esempio n. 12
0
        /// <summary>
        /// Returns a SharePoint ClientContext using Azure Active Directory authentication. This requires that you have a Azure AD Native Application registered. The user will be prompted for authentication.
        /// </summary>
        /// <param name="siteUrl">Site for which the ClientContext object will be instantiated</param>
        /// <param name="clientId">The Azure AD Native Application Client ID</param>
        /// <param name="redirectUri">The Azure AD Native Application Redirect Uri</param>
        /// <param name="tokenCache">Optional token cache. If not specified an in-memory token cache will be used</param>
        /// <param name="environment">SharePoint environment being used</param>
        /// <returns>Client context object</returns>
        public ClientContext GetAzureADNativeApplicationAuthenticatedContext(string siteUrl, string clientId, Uri redirectUri, TokenCache tokenCache = null, AzureEnvironment environment = AzureEnvironment.Production)
        {
            var clientContext = new ClientContext(siteUrl);

            _contextUrl      = siteUrl;
            _tokenCache      = tokenCache;
            _clientId        = clientId;
            _redirectUri     = redirectUri;
            _commonAuthority = String.Format("{0}/common", GetAzureADLoginEndPoint(environment));

            clientContext.ExecutingWebRequest += clientContext_NativeApplicationExecutingWebRequest;

            return(clientContext);
        }
Esempio n. 13
0
 /// <summary>
 /// Returns a SharePoint ClientContext using Azure Active Directory authentication. This requires that you have a Azure AD Native Application registered. The user will be prompted for authentication.
 /// </summary>
 /// <param name="siteUrl">Site for which the ClientContext object will be instantiated</param>
 /// <param name="clientId">The Azure AD Native Application Client ID</param>
 /// <param name="redirectUrl">The Azure AD Native Application Redirect Uri as a string</param>
 /// <param name="tokenCache">Optional token cache. If not specified an in-memory token cache will be used</param>
 /// <param name="environment">SharePoint environment being used</param>
 /// <returns>Client context object</returns>
 public ClientContext GetAzureADNativeApplicationAuthenticatedContext(string siteUrl, string clientId, string redirectUrl, TokenCache tokenCache = null, AzureEnvironment environment = AzureEnvironment.Production)
 {
     return(GetAzureADNativeApplicationAuthenticatedContext(siteUrl, clientId, new Uri(redirectUrl), tokenCache, environment));
 }
Esempio n. 14
0
 public MockHttpTestHarness(string authorityUri)
 {
     _mockHttpAndServiceBundle = new MockHttpAndServiceBundle();
     Authority = Authority.CreateAuthority(ServiceBundle, authorityUri);
     Cache     = new TokenCache(ServiceBundle);
 }
Esempio n. 15
0
        public static AuthResult FromMSALAuthenticationResult(this AuthenticationResult authResult, TokenCache tokenCache)
        {
            var result = new AuthResult
            {
                AccessToken       = authResult.AccessToken,
                UserName          = $"{authResult.User.Name}",
                UserUniqueId      = authResult.User.Identifier,
                ExpiresOnUtcTicks = authResult.ExpiresOn.UtcTicks,
                TokenCache        = tokenCache.Serialize()
            };

            return(result);
        }
 private static void PersistCacheToSession(ISession session, string cacheId,
                                           TokenCache cache)
 {
     session.Set(cacheId, cache.Serialize());
 }
 public AcquireTokenForClientHandler(Authenticator authenticator, TokenCache tokenCache, string resource, ClientKey clientKey)
     : base(authenticator, tokenCache, resource, clientKey, TokenSubjectType.Client)
 {
     this.SupportADFS = true;
 }
 private static void LoadCacheFromSession(ISession session, string cacheId, TokenCache cache)
 {
     cache.Deserialize(session.Get(cacheId));
 }
 /// <summary>
 /// Creates ServiceClientCredentials for authenticating requests as an active directory application using a certificate credential.
 /// See <see href="https://azure.microsoft.com/en-us/documentation/articles/active-directory-devquickstarts-dotnet/">Active Directory Quickstart for .Net</see>
 /// for detailed instructions on creating an Azure Active Directory application.
 /// </summary>
 /// <param name="domain">The active directory domain or tenantId to authenticate with.</param>
 /// <param name="certificate">The certificate associated with Active Directory application.</param>
 /// <param name="settings">The active directory service side settings, including authority and token audience.</param>
 /// <param name="cache">The token cache to target during authentication.</param>
 /// <returns>A ServiceClientCredentials object that can authenticate http requests as the given application.</returns>
 public static async Task <ServiceClientCredentials> LoginSilentAsync(string domain, ClientAssertionCertificate certificate,
                                                                      ActiveDirectoryServiceSettings settings, TokenCache cache)
 {
     return(await LoginSilentAsync(domain, certificate.ClientId,
                                   new CertificateAuthenticationProvider((clientId) => Task.FromResult(certificate)), settings, cache).ConfigureAwait(false));
 }
Esempio n. 20
0
 internal NoLockTokenCacheProxy(TokenCache tokenCache)
 {
     _tokenCache = tokenCache;
 }
 /// <summary>
 /// Creates ServiceClientCredentials for authenticating requests as an active directory application. Uses the default service settings
 /// (authority and token audience) for authenticating with azure resource manager.
 /// See <see href="https://azure.microsoft.com/en-us/documentation/articles/active-directory-devquickstarts-dotnet/">Active Directory Quickstart for .Net</see>
 /// for detailed instructions on creating an Azure Active Directory application.
 /// </summary>
 /// <param name="domain">The active directory domain or tenantId to authenticate with.</param>
 /// <param name="clientId">The active directory clientId for the application.</param>
 /// <param name="authenticationProvider">A source for the secure secret for this application.</param>
 /// <param name="cache">The token cache to target during authentication.</param>
 /// <returns>A ServiceClientCredentials object that can authenticate http requests as the given application.</returns>
 public static async Task <ServiceClientCredentials> LoginSilentAsync(string domain, string clientId,
                                                                      IApplicationAuthenticationProvider authenticationProvider, TokenCache cache)
 {
     return(await LoginSilentAsync(domain, clientId, authenticationProvider, ActiveDirectoryServiceSettings.Azure, cache).ConfigureAwait(false));
 }
Esempio n. 22
0
        internal AdalTokenProvider(string authority, string resource, string clientId, TokenCache tokenCache)
        {
            this.authority  = authority;
            this.resource   = resource;
            this.clientId   = clientId;
            this.tokenCache = tokenCache;

            // authenticationContext is re-created on each call since the authority can be unexpectedly mutated by another call.
            // e.g. AcquireTokenWithWindowsIntegratedAuth could set it to a specific AAD authority preventing a future AcquireTokenWithDeviceFlowAsync from working for a MSA account.
        }
 private static AuthenticationContext GetAuthenticationContext(string domain, ActiveDirectoryServiceSettings serviceSettings, TokenCache cache)
 {
     return((cache == null)
             ? new AuthenticationContext(serviceSettings.AuthenticationEndpoint + domain,
                                         serviceSettings.ValidateAuthority)
             : new AuthenticationContext(serviceSettings.AuthenticationEndpoint + domain,
                                         serviceSettings.ValidateAuthority,
                                         cache));
 }
Esempio n. 24
0
        public void NoCacheLookup()
        {
            MyReceiver myReceiver = new MyReceiver();

            using (MockHttpAndServiceBundle harness = CreateTestHarness(telemetryCallback: myReceiver.HandleTelemetryEvents))
            {
                TokenCache cache = new TokenCache(harness.ServiceBundle, false);

                MsalAccessTokenCacheItem atItem = new MsalAccessTokenCacheItem(
                    TestConstants.ProductionPrefNetworkEnvironment,
                    TestConstants.ClientId,
                    TestConstants.s_scope.AsSingleString(),
                    TestConstants.Utid,
                    null,
                    new DateTimeOffset(DateTime.UtcNow + TimeSpan.FromSeconds(3599)),
                    new DateTimeOffset(DateTime.UtcNow + TimeSpan.FromSeconds(7200)),
                    MockHelpers.CreateClientInfo());

                string atKey = atItem.GetKey().ToString();
                atItem.Secret = atKey;
                ((ITokenCacheInternal)cache).Accessor.SaveAccessToken(atItem);

                MockWebUI ui = new MockWebUI()
                {
                    MockResult = AuthorizationResult.FromUri(TestConstants.AuthorityHomeTenant + "?code=some-code")
                };

                MockInstanceDiscoveryAndOpenIdRequest(harness.HttpManager);

                harness.HttpManager.AddSuccessTokenResponseMockHandlerForPost(TestConstants.AuthorityHomeTenant);

                AuthenticationRequestParameters parameters = harness.CreateAuthenticationRequestParameters(
                    TestConstants.AuthorityHomeTenant,
                    TestConstants.s_scope,
                    cache,
                    extraQueryParameters: new Dictionary <string, string>
                {
                    { "extra", "qp" }
                });
                parameters.RedirectUri = new Uri("some://uri");
                parameters.LoginHint   = TestConstants.DisplayableId;
                AcquireTokenInteractiveParameters interactiveParameters = new AcquireTokenInteractiveParameters
                {
                    Prompt = Prompt.SelectAccount,
                    ExtraScopesToConsent = TestConstants.s_scopeForAnotherResource.ToArray(),
                };

                InteractiveRequest request = new InteractiveRequest(
                    harness.ServiceBundle,
                    parameters,
                    interactiveParameters,
                    ui);

                Task <AuthenticationResult> task = request.RunAsync(CancellationToken.None);
                task.Wait();
                AuthenticationResult result = task.Result;
                Assert.IsNotNull(result);
                Assert.AreEqual(1, ((ITokenCacheInternal)cache).Accessor.GetAllRefreshTokens().Count());
                Assert.AreEqual(2, ((ITokenCacheInternal)cache).Accessor.GetAllAccessTokens().Count());
                Assert.AreEqual(result.AccessToken, "some-access-token");

                Assert.IsNotNull(
                    myReceiver.EventsReceived.Find(
                        anEvent => // Expect finding such an event
                        anEvent[EventBase.EventNameKey].EndsWith("ui_event") &&
                        anEvent[UiEvent.UserCancelledKey] == "false"));
                Assert.IsNotNull(
                    myReceiver.EventsReceived.Find(
                        anEvent => // Expect finding such an event
                        anEvent[EventBase.EventNameKey].EndsWith("api_event") &&
                        anEvent[ApiEvent.PromptKey] == "select_account"));
                Assert.IsNotNull(
                    myReceiver.EventsReceived.Find(
                        anEvent => // Expect finding such an event
                        anEvent[EventBase.EventNameKey].EndsWith("ui_event") &&
                        anEvent[UiEvent.AccessDeniedKey] == "false"));
            }
        }
Esempio n. 25
0
        public void TestCacheDeserializeWithoutServiceBundle()
        {
            var tokenCache = new TokenCache();

            ((ITokenCacheSerializer)tokenCache).DeserializeMsalV3(new byte[0]);
        }
Esempio n. 26
0
        static async Task runSample(string tenantId, string clientId, string subscriptionId, string userName, string password, string location, string armEndpoint)
        {
            var resourceGroup1Name = SdkContext.RandomResourceName("rgDotnetSdk", 24);
            var resourceGroup2Name = SdkContext.RandomResourceName("rgDotnetSdk", 24);

            Console.WriteLine("Get credential token");
            var adSettings = getActiveDirectoryServiceSettings(armEndpoint);

            // Authenticate with ADAL directly. Fluent packages don't support UserPass auth
            var tokenCache = new TokenCache();
            var context    = new AuthenticationContext(authority: adSettings.AuthenticationEndpoint.ToString(), validateAuthority: false, tokenCache: tokenCache);
            var cred       = new UserPasswordCredential(userName, password);
            var token      = await AuthenticationContextIntegratedAuthExtensions.AcquireTokenAsync(ctx : context, resource : adSettings.TokenAudience.ToString(), clientId : clientId, userCredential : cred).ConfigureAwait(continueOnCapturedContext: false);

            var credentials = await UserTokenProvider.CreateCredentialsFromCache(clientId : clientId, domain : tenantId, username : userName, cache : tokenCache, serviceSettings : adSettings).ConfigureAwait(continueOnCapturedContext: false);

            Console.WriteLine("Instantiate resource management client");
            var rmClient = GetResourceManagementClient(new Uri(armEndpoint), credentials, subscriptionId);

            // Create resource group.
            try
            {
                Console.WriteLine(String.Format("Creating a resource group with name:{0}", resourceGroup1Name));
                var rmCreateTask = rmClient.ResourceGroups.CreateOrUpdateWithHttpMessagesAsync(
                    resourceGroup1Name,
                    new Profile2018ResourceManager.Models.ResourceGroup
                {
                    Location = location
                });
                rmCreateTask.Wait();
            }
            catch (Exception ex)
            {
                Console.WriteLine(String.Format("Could not create resource group {0}. Exception: {1}", resourceGroup1Name, ex.Message));
            }

            // Update the resource group.
            try
            {
                Console.WriteLine(String.Format("Updating the resource group with name:{0}", resourceGroup1Name));
                var rmTagTask = rmClient.ResourceGroups.PatchWithHttpMessagesAsync(resourceGroup1Name, new Profile2018ResourceManager.Models.ResourceGroup
                {
                    Tags = new Dictionary <string, string> {
                        { "DotNetTag", "DotNetValue" }
                    }
                });

                rmTagTask.Wait();
            }
            catch (Exception ex)
            {
                Console.WriteLine(String.Format("Could not tag resource group {0}. Exception: {1}", resourceGroup1Name, ex.Message));
            }

            // Create another resource group.
            try
            {
                Console.WriteLine(String.Format("Creating a resource group with name:{0}", resourceGroup2Name));
                var rmCreateTask = rmClient.ResourceGroups.CreateOrUpdateWithHttpMessagesAsync(
                    resourceGroup2Name,
                    new Profile2018ResourceManager.Models.ResourceGroup
                {
                    Location = location
                });
                rmCreateTask.Wait();
            }
            catch (Exception ex)
            {
                Console.WriteLine(String.Format("Could not create resource group {0}. Exception: {1}", resourceGroup2Name, ex.Message));
            }

            // List resource groups.
            try
            {
                Console.WriteLine("Listing all resource groups.");
                var rmListTask = rmClient.ResourceGroups.ListWithHttpMessagesAsync();
                rmListTask.Wait();

                var resourceGroupResults = rmListTask.Result.Body;
                foreach (var result in resourceGroupResults)
                {
                    Console.WriteLine(String.Format("Resource group name:{0}", result.Name));
                }
            }
            catch (Exception ex)
            {
                Console.WriteLine(string.Format("Could not list resource groups. Exception: {0}", ex.Message));
            }

            // Delete a resource group.
            try
            {
                Console.WriteLine(String.Format("Deleting resource group with name:{0}", resourceGroup2Name));
                var rmDeleteTask = rmClient.ResourceGroups.DeleteWithHttpMessagesAsync(resourceGroup2Name);
                rmDeleteTask.Wait();
            }
            catch (Exception ex)
            {
                Console.WriteLine(String.Format("Could not delete resource group {0}. Exception: {1}", resourceGroup2Name, ex.Message));
            }
        }
Esempio n. 27
0
 /// <summary>
 /// Returns a SharePoint ClientContext using Azure Active Directory authentication. This requires that you have a Azure AD Native Application registered. The user will be prompted for authentication.
 /// </summary>
 /// <param name="siteUrl">Site for which the ClientContext object will be instantiated</param>
 /// <param name="clientId">The Azure AD Native Application Client ID</param>
 /// <param name="redirectUrl">The Azure AD Native Application Redirect Uri as a string</param>
 /// <param name="tokenCache">Optional token cache. If not specified an in-memory token cache will be used</param>
 /// <returns></returns>
 public ClientContext GetAzureADNativeApplicationAuthenticatedContext(string siteUrl, string clientId, string redirectUrl, TokenCache tokenCache = null)
 {
     return(GetAzureADNativeApplicationAuthenticatedContext(siteUrl, clientId, new Uri(redirectUrl), tokenCache));
 }
 /// <summary>
 /// Creates ServiceClientCredentials for authenticating requests as an active directory application using client credentials.
 /// See <see href="https://azure.microsoft.com/en-us/documentation/articles/active-directory-devquickstarts-dotnet/">Active Directory Quickstart for .Net</see>
 /// for detailed instructions on creating an Azure Active Directory application.
 /// </summary>
 /// <param name="domain">The active directory domain or tenantId to authenticate with.</param>
 /// <param name="clientId">The active directory clientId for the application.</param>
 /// <param name="secret">The secret for this active directory application.</param>
 /// <param name="settings">The active directory service side settings, including authority and token audience.</param>
 /// <param name="cache">The token cache to target during authentication.</param>
 /// <returns>A ServiceClientCredentials object that can authenticate http requests as the given application.</returns>
 public static async Task <ServiceClientCredentials> LoginSilentAsync(string domain, string clientId, string secret,
                                                                      ActiveDirectoryServiceSettings settings, TokenCache cache)
 {
     return(await LoginSilentAsync(domain, new ClientCredential(clientId, secret), settings, cache).ConfigureAwait(false));
 }
Esempio n. 29
0
        /*
         *  Interactive: User popup
         *  (using a token cache to reuse/save session state)
         */
        private static ServiceClientCredentials GetCredsInteractivePopup(string domain, Uri tokenAudience, TokenCache tokenCache, PromptBehavior promptBehavior = PromptBehavior.Auto)
        {
            SynchronizationContext.SetSynchronizationContext(new SynchronizationContext());

            var clientSettings = new ActiveDirectoryClientSettings
            {
                ClientId          = azure_powershell_clientid,
                ClientRedirectUri = new Uri("urn:ietf:wg:oauth:2.0:oob"),
                PromptBehavior    = promptBehavior
            };

            var serviceSettings = ActiveDirectoryServiceSettings.Azure;

            serviceSettings.TokenAudience = tokenAudience;

            var creds = UserTokenProvider.LoginWithPromptAsync(domain, clientSettings, serviceSettings, tokenCache).GetAwaiter().GetResult();

            return(creds);
        }
 /// <summary>
 /// Creates ServiceClientCredentials for authenticating requests as an active directory application using a client credential.
 /// See <see href="https://azure.microsoft.com/en-us/documentation/articles/active-directory-devquickstarts-dotnet/">Active Directory Quickstart for .Net</see>
 /// for detailed instructions on creating an Azure Active Directory application.
 /// </summary>
 /// <param name="domain">The active directory domain or tenantId to authenticate with.</param>
 /// <param name="credential">The client credential (client id and secret) for this active directory application.</param>
 /// <param name="settings">The active directory service side settings, including authority and token audience.</param>
 /// <param name="cache">The token cache to target during authentication.</param>
 /// <returns>A ServiceClientCredentials object that can authenticate http requests as the given application.</returns>
 public static async Task <ServiceClientCredentials> LoginSilentAsync(string domain, ClientCredential credential,
                                                                      ActiveDirectoryServiceSettings settings, TokenCache cache)
 {
     return(await LoginSilentAsync(domain, credential.ClientId, new MemoryApplicationAuthenticationProvider(credential),
                                   settings, cache).ConfigureAwait(false));
 }
 public AcquireTokenForClientHandler(Authenticator authenticator, TokenCache tokenCache, string[] scope, ClientKey clientKey)
     : base(authenticator, tokenCache, scope, clientKey, TokenSubjectType.Client)
 {
     this.SupportADFS = false;
 }
 /// <summary>
 /// Creates ServiceClientCredentials for authenticating requests as an active directory application using certificate credentials. Uses the default service settings
 /// (authority, token audience) for log in to azure resource manager during authentication.
 /// See <see href="https://azure.microsoft.com/en-us/documentation/articles/active-directory-devquickstarts-dotnet/">Active Directory Quickstart for .Net</see>
 /// for detailed instructions on creating an Azure Active Directory application.
 /// </summary>
 /// <param name="domain">The active directory domain or tenantId to authenticate with.</param>
 /// <param name="clientId">The active directory clientId for the application.</param>
 /// <param name="certificate">The certificate associated with Active Directory application.</param>
 /// <param name="password">The certificate password.</param>
 /// <param name="cache">The token cache to target during authentication.</param>
 /// <returns>A ServiceClientCredentials object that can authenticate http requests as the given application.</returns>
 public static async Task <ServiceClientCredentials> LoginSilentAsync(string domain, string clientId, byte[] certificate, string password, TokenCache cache)
 {
     return(await LoginSilentAsync(domain, clientId, certificate, password, ActiveDirectoryServiceSettings.Azure, cache).ConfigureAwait(false));
 }
Esempio n. 33
0
        /// <summary>
        /// 
        /// </summary>
        public static string GetJsapiTicket(WeChatParam param)
        {
            var appId = GetConfig.GetAppid(param);
            if (!AccessTicketsCache.ContainsKey(appId) || AccessTicketsCache[appId] == null
                || AccessTicketsCache[appId].ExpireTime < DateTime.Now)
            {
                var result = HttpHelper.Get<TokenResult>(ApiList.GetticketUrl, new HttpParam
                    {
                        {"access_token", GetAccessToken(param)},
                        {"type", "jsapi"}
                    });
                if (result.errmsg != "ok")
                    throw new WxException(result.errcode, result.errmsg);

                AccessTicketsCache[appId] = new TokenCache
                {
                    JsapiTicket = result.ticket,
                    ExpireTime = DateTime.Now.AddSeconds(result.expires_in - 3)
                };
            }
            return AccessTicketsCache[appId].JsapiTicket;
        }
        /// <summary>
        /// Creates ServiceClientCredentials for authenticating requests as an active directory application using certificate credential.
        /// See <see href="https://azure.microsoft.com/en-us/documentation/articles/active-directory-devquickstarts-dotnet/">Active Directory Quickstart for .Net</see>
        /// for detailed instructions on creating an Azure Active Directory application.
        /// </summary>
        /// <param name="domain">The active directory domain or tenantId to authenticate with.</param>
        /// <param name="clientId">The active directory clientId for the application.</param>
        /// <param name="certificate">The certificate associated with Active Directory application.</param>
        /// <param name="password">The certificate password.</param>
        /// <param name="settings">The active directory service side settings, including authority and token audience.</param>
        /// <param name="cache">The token cache to target during authentication.</param>
        /// <returns>A ServiceClientCredentials object that can authenticate http requests as the given application.</returns>
        public static async Task <ServiceClientCredentials> LoginSilentAsync(string domain, string clientId, byte[] certificate, string password,
                                                                             ActiveDirectoryServiceSettings settings, TokenCache cache)
        {
#if !net452
            return(await LoginSilentAsync(domain, new ClientAssertionCertificate(clientId, certificate, password),
                                          settings, cache).ConfigureAwait(false));
#else
            return(await LoginSilentAsync(domain, new ClientAssertionCertificate(clientId,
                                                                                 new System.Security.Cryptography.X509Certificates.X509Certificate2(certificate)),
                                          settings, cache).ConfigureAwait(false));
#endif
        }
        /// <summary>
        /// Gets the token.
        /// </summary>
        /// <param name="url">The URL.</param>
        /// <param name="username">The username.</param>
        /// <param name="password">The password.</param>
        /// <returns></returns>
        private static string GetToken(string url, string username, string password)
        {
            string token = String.Empty;
            try
            {

                string tokenUrl = String.Format("{0}?username={1}&password={2}&format=pox", url, username, password);

                //Try and get token from the cache
                if (LocatorManager.CachedTokens != null && LocatorManager.CachedTokens.ContainsKey(tokenUrl))
                {
                    if (LocatorManager.CachedTokens[tokenUrl].IsValid())
                    {
                        token = LocatorManager.CachedTokens[tokenUrl].Token;
                    }
                    else
                    {
                        LocatorManager.CachedTokens.Remove(tokenUrl);
                    }
                }

                if (String.IsNullOrEmpty(token))
                {
                    WebRequest webRequest = WebRequest.Create(tokenUrl);
                    using (WebResponse webResponse = webRequest.GetResponse())
                    {
                        using (Stream byteStream = webResponse.GetResponseStream())
                        {
                            using (XmlTextReader xmlReader = new XmlTextReader(byteStream))
                            {
                                xmlReader.Read();
                                xmlReader.Read();
                                token = xmlReader.Value;
                                int duration = 0;
                                int.TryParse(token.Substring(0, 3), out duration);
                                TokenCache tokenCache = new TokenCache(token, DateTime.Now.AddMinutes(duration - 1).ToUniversalTime());
                                LocatorManager.CachedTokens.Add(tokenUrl, tokenCache);

                            }
                        }
                    }
                }
            }
            catch (Exception)
            {

            }

            return token;
        }
Esempio n. 36
0
        private AdalConfiguration GetAdalConfiguration(AzureEnvironment environment, string tenantId,
                                                       AzureEnvironment.Endpoint resourceId, TokenCache tokenCache)
        {
            if (environment == null)
            {
                throw new ArgumentNullException("environment");
            }

            var adEndpoint = environment.Endpoints[AzureEnvironment.Endpoint.ActiveDirectory];

            if (string.IsNullOrWhiteSpace(adEndpoint))
            {
                throw new ArgumentOutOfRangeException(
                          "environment",
                          string.Format("No Active Directory endpoint specified for environment '{0}'", environment.Name));
            }

            var audience = environment.Endpoints[resourceId];

            if (string.IsNullOrWhiteSpace(audience))
            {
                string message = Resources.InvalidManagementTokenAudience;
                if (resourceId == AzureEnvironment.Endpoint.GraphEndpointResourceId)
                {
                    message = Resources.InvalidGraphTokenAudience;
                }

                throw new ArgumentOutOfRangeException("environment", string.Format(message, environment.Name));
            }

            return(new AdalConfiguration
            {
                AdEndpoint = adEndpoint,
                ResourceClientUri = environment.Endpoints[resourceId],
                AdDomain = tenantId,
                ValidateAuthority = !environment.OnPremise,
                TokenCache = tokenCache
            });
        }