public async Task AppendAuthenticationHeader_ExpiredAccountSession()
        {
            var cachedAccountSession = new AccountSession
            {
                AccessToken = "token",
            };

            this.authenticationProvider.CurrentAccountSession = cachedAccountSession;

            using (var httpRequestMessage = new HttpRequestMessage())
            {
                try
                {
                    await this.authenticationProvider.AppendAuthHeaderAsync(httpRequestMessage);
                }
                catch (OneDriveException oneDriveException)
                {
                    Assert.AreEqual(OneDriveErrorCode.AuthenticationFailure.ToString(), oneDriveException.Error.Code, "Unexpected error code.");
                    Assert.AreEqual(
                        "Failed to retrieve a valid authentication token for the user.",
                        oneDriveException.Error.Message,
                        "Unexpected error message.");

                    throw;
                }
            }
        }
        public void VerifyClassInitialization()
        {
            var responseValues = new Dictionary<string, string>
            {
                { Constants.Authentication.AccessTokenKeyName, "token" },
                { Constants.Authentication.ExpiresInKeyName, "45" },
                { Constants.Authentication.ScopeKeyName, "scope1%20scope2" },
                { Constants.Authentication.UserIdKeyName, "1" },
                { Constants.Authentication.RefreshTokenKeyName, "refresh" },
            };

            var accountSession = new AccountSession(responseValues);

            // Verify the expiration time is after now and somewhere between now and 45 seconds from now.
            // This accounts for delay in initialization until now.
            var dateTimeNow = DateTimeOffset.UtcNow;
            var dateTimeDifference = accountSession.ExpiresOnUtc - DateTimeOffset.UtcNow;
            Assert.IsTrue(accountSession.ExpiresOnUtc > dateTimeNow, "Unexpected expiration returned.");
            Assert.IsTrue(dateTimeDifference.Seconds <= 45, "Unexpected expiration returned.");

            Assert.IsNull(accountSession.ClientId, "Unexpected client ID.");
            Assert.AreEqual(AccountType.None, accountSession.AccountType, "Unexpected account type.");
            Assert.AreEqual("token", accountSession.AccessToken, "Unexpected access token.");
            Assert.AreEqual("1", accountSession.UserId, "Unexpected user ID.");
            Assert.AreEqual("refresh", accountSession.RefreshToken, "Unexpected refresh token.");

            Assert.AreEqual(2, accountSession.Scopes.Length, "Unexpected number of scopes.");
            Assert.AreEqual("scope1", accountSession.Scopes[0], "Unexpected first scope.");
            Assert.AreEqual("scope2", accountSession.Scopes[1], "Unexpected second scope.");
        }
예제 #3
0
 public async Task Setup()
 {
     // onedrive
     var scopes = new string[] { "wl.basic", "wl.signin", "onedrive.readwrite" };
     client = OneDriveClientExtensions.GetUniversalClient(scopes);
     session = await client.AuthenticateAsync();
 }
        public void VerifyClassInitialization_SpecifyOptionalParameters()
        {
            var accountSession = new AccountSession(null, "1", AccountType.MicrosoftAccount);

            Assert.AreEqual("1", accountSession.ClientId, "Unexpected client ID.");
            Assert.AreEqual(AccountType.MicrosoftAccount, accountSession.AccountType, "Unexpected account type.");
        }
        internal async Task<AccountSession> GetAccountSessionAsync()
        {
            try
            {
                var serviceTicketRequest = new OnlineIdServiceTicketRequest(string.Join(" ", this.ServiceInfo.Scopes), "DELEGATION");
                var authenticationResponse = await this.authenticator.AuthenticateUserAsync(serviceTicketRequest);

                var ticket = authenticationResponse.Tickets.FirstOrDefault();

                var accountSession = new AccountSession
                {
                    AccessToken = ticket == null ? null : ticket.Value,
                    AccountType = this.ServiceInfo.AccountType,
                    CanSignOut = this.authenticator.CanSignOut,
                    ClientId = this.authenticator.ApplicationId.ToString(),
                    UserId = authenticationResponse.SafeCustomerId,
                };

                return accountSession;
            }
            catch (Exception exception)
            {
                throw new OneDriveException(new Error { Code = OneDriveErrorCode.AuthenticationFailure.ToString(), Message = exception.Message }, exception);
            }
        }
        public void AddToCache()
        {
            var accountSession = new AccountSession
            {
                AccessToken = "token",
                UserId = "1",
            };

            this.credentialCache.AfterAccess = this.AfterAccess;
            this.credentialCache.BeforeAccess = this.BeforeAccess;
            this.credentialCache.BeforeWrite = this.BeforeWrite;

            Assert.IsNotNull(this.credentialCache.AfterAccess, "AfterAccess delegate not set.");
            Assert.IsNotNull(this.credentialCache.BeforeAccess, "BeforeAccess delegate not set.");
            Assert.IsNotNull(this.credentialCache.BeforeWrite, "BeforeWrite delegate not set.");
            
            this.credentialCache.AddToCache(accountSession);

            // Adding items to the cache is handled by ADAL. Verify the delegates are not called
            // for AddToCache since the method is a no-op for AdalCredentialCache.
            Assert.IsFalse(this.afterAccessCalled, "AfterAccess called.");
            Assert.IsFalse(this.beforeAccessCalled, "BeforeAccess called.");
            Assert.IsFalse(this.beforeWriteCalled, "BeforeWrite called.");

            Assert.IsFalse(this.credentialCache.HasStateChanged, "State changed flag not set.");
        }
        public async Task AuthenticateAsync_ExpiredResultNoRefreshToken()
        {
            var cachedAccountSession = new AccountSession
            {
                AccountType = this.serviceInfo.AccountType,
                AccessToken = "token",
                ClientId = this.serviceInfo.AppId,
                ExpiresOnUtc = DateTimeOffset.UtcNow.AddMinutes(4),
                UserId = this.serviceInfo.UserId,
            };

            var refreshedAccountSession = new AccountSession
            {
                AccountType = AccountType.MicrosoftAccount,
                ClientId = "1",
                AccessToken = "token2",
            };

            this.serviceInfo.CredentialCache.AddToCache(cachedAccountSession);

            this.authenticationProvider.CurrentAccountSession = cachedAccountSession;

            await this.AuthenticateWithCodeFlow(refreshedAccountSession);

            this.credentialCache.Verify(cache => cache.OnGetResultFromCache(), Times.Once);
            this.credentialCache.Verify(cache => cache.OnDeleteFromCache(), Times.Once);
        }
        protected Task AuthenticateWithCodeFlow(AccountSession refreshedAccountSession)
        {
            var tokenResponseDictionary = new Dictionary<string, string> { { "code", "code" } };

            this.webUi.Setup(webUi => webUi.AuthenticateAsync(
                It.Is<Uri>(uri => uri.ToString().Contains("response_type=code")),
                It.Is<Uri>(uri => uri.ToString().Equals(this.serviceInfo.ReturnUrl))))
                .Returns(
                    Task.FromResult<IDictionary<string, string>>(tokenResponseDictionary));

            return this.AuthenticateWithRefreshToken(refreshedAccountSession);
        }
        public async Task AuthenticateAsync_CachedCurrentAccountSession()
        {
            var cachedAccountSession = new AccountSession
            {
                AccessToken = "token",
                ExpiresOnUtc = DateTimeOffset.UtcNow.AddMinutes(10),
            };

            this.authenticationProvider.CurrentAccountSession = cachedAccountSession;

            var accountSession = await this.authenticationProvider.AuthenticateAsync();

            Assert.IsNotNull(accountSession, "No account session returned.");
            Assert.AreEqual(cachedAccountSession.AccessToken, accountSession.AccessToken, "Unexpected access token returned.");
            Assert.AreEqual(cachedAccountSession.ExpiresOnUtc, accountSession.ExpiresOnUtc, "Unexpected expiration returned.");
        }
예제 #10
0
        internal virtual void DeleteFromCache(AccountSession accountSession)
        {
            if (accountSession != null)
            {
                var cacheNotificationArgs = new CredentialCacheNotificationArgs {
                    CredentialCache = this
                };
                this.OnBeforeAccess(cacheNotificationArgs);
                this.OnBeforeWrite(cacheNotificationArgs);

                var credentialCacheKey = this.GetKeyForAuthResult(accountSession);
                this.cacheDictionary.Remove(credentialCacheKey);

                this.HasStateChanged = true;

                this.OnAfterAccess(cacheNotificationArgs);
            }
        }
        public async Task AppendAuthenticationHeader()
        {
            var cachedAccountSession = new AccountSession
            {
                AccessToken = "token",
            };

            this.authenticationProvider.CurrentAccountSession = cachedAccountSession;

            using (var httpRequestMessage = new HttpRequestMessage())
            {
                await this.authenticationProvider.AppendAuthHeaderAsync(httpRequestMessage);
                Assert.AreEqual(
                    string.Format("{0} {1}", Constants.Headers.Bearer, cachedAccountSession.AccessToken),
                    httpRequestMessage.Headers.Authorization.ToString(),
                    "Unexpected authorization header set.");
            }
        }
        internal async Task <AccountSession> GetAccountSessionAsync()
        {
            try
            {
                var serviceTicketRequest = new OnlineIdServiceTicketRequest(string.Join(" ", this.ServiceInfo.Scopes), "DELEGATION");
                var ticketRequests       = new List <OnlineIdServiceTicketRequest>();
                ticketRequests.Add(serviceTicketRequest);
                var authenticationResponse = await this.authenticator.AuthenticateUserAsync(ticketRequests, (Windows.Security.Authentication.OnlineId.CredentialPromptType) this.ServiceInfo.MicrosoftAccountPromptType);

                var ticket = authenticationResponse.Tickets.FirstOrDefault();

                if (ticket == null || string.IsNullOrEmpty(ticket.Value))
                {
                    throw new OneDriveException(
                              new Error
                    {
                        Code    = OneDriveErrorCode.AuthenticationFailure.ToString(),
                        Message = string.Format(
                            "Failed to retrieve a valid authentication token from OnlineIdAuthenticator for user {0}.",
                            authenticationResponse.SignInName)
                    });
                }

                var accountSession = new AccountSession
                {
                    AccessToken  = ticket == null ? null : ticket.Value,
                    AccountType  = this.ServiceInfo.AccountType,
                    CanSignOut   = this.authenticator.CanSignOut,
                    ClientId     = this.authenticator.ApplicationId.ToString(),
                    ExpiresOnUtc = DateTimeOffset.UtcNow.AddMinutes(this.ticketExpirationTimeInMinutes),
                    UserId       = authenticationResponse.SafeCustomerId,
                };

                return(accountSession);
            }
            catch (Exception exception)
            {
                throw new OneDriveException(new Error {
                    Code = OneDriveErrorCode.AuthenticationFailure.ToString(), Message = exception.Message
                }, exception);
            }
        }
        public async Task AppendAuthenticationHeaderDifferentType()
        {
            var cachedAccountSession = new AccountSession
            {
                AccessToken = "token",
                AccessTokenType = "test",
                ExpiresOnUtc = DateTimeOffset.UtcNow.AddHours(1),
            };

            this.authenticationProvider.CurrentAccountSession = cachedAccountSession;

            using (var httpRequestMessage = new HttpRequestMessage())
            {
                await this.authenticationProvider.AppendAuthHeaderAsync(httpRequestMessage);
                Assert.AreEqual(
                    string.Format("{0} {1}", cachedAccountSession.AccessTokenType, cachedAccountSession.AccessToken),
                    httpRequestMessage.Headers.Authorization.ToString(),
                    "Unexpected authorization header set.");
            }
        }
예제 #14
0
        private void Initialize()
        {
            if (Client != null)
                return;

            // Load credential cache
            CredentialCache credentialCache = new CredentialCache();
            if (!string.IsNullOrEmpty(Settings.Default.Credentials))
                credentialCache.InitializeCacheFromBlob(Convert.FromBase64String(Settings.Default.Credentials));

            // Authenticate with OneDrive
            Client = OneDriveClient.GetMicrosoftAccountClient(applicationId, applicationReturnUrl, applicationScopes, applicationSecret, credentialCache, null, new OneDriveInfoProvider());
            Task<AccountSession> oneDriveSessionTask = Client.AuthenticateAsync();
            oneDriveSessionTask.Wait();
            Session = oneDriveSessionTask.Result;

            // Save credentials
            if (Session == null)
            {
                Settings.Default.Credentials = null;
                Settings.Default.Save();
            }
            else if (credentialCache.HasStateChanged)
            {
                Settings.Default.Credentials = Convert.ToBase64String(credentialCache.GetCacheBlob());
                Settings.Default.Save();
            }

            // Find specified root folder
            if (!Path.StartsWith("/") || !IsPathValid(Path))
                throw new Exception("The specified path is not valid");

            Task<Item> task;
            if (Path.Length == 1)
                task = Client.Drive.Root.Request().GetAsync();
            else
                task = Client.Drive.Root.ItemWithPath(Path.Trim('/')).Request().GetAsync();

            task.Wait();
            root = task.Result;
        }
        protected override async Task <AccountSession> GetAuthenticationResultAsync()
        {
            AccountSession authResult = null;

            // Log the user in if we haven't already pulled their credentials from the cache.
            var code = await this.GetAuthorizationCodeAsync();

            if (!string.IsNullOrEmpty(code))
            {
                authResult = await this.RedeemAuthorizationCodeAsync(code);

                authResult.CanSignOut = true;
            }

            if (authResult != null)
            {
                this.CacheAuthResult(authResult);
            }

            return(authResult);
        }
        private AccountSession ProcessAuthenticationResult(IAuthenticationResult authenticationResult)
        {
            if (authenticationResult == null)
            {
                this.CurrentAccountSession = null;
                return(this.CurrentAccountSession);
            }

            this.CurrentAccountSession = new AdalAccountSession
            {
                AccessToken     = authenticationResult.AccessToken,
                AccessTokenType = authenticationResult.AccessTokenType,
                AccountType     = AccountType.ActiveDirectory,
                CanSignOut      = true,
                ClientId        = this.ServiceInfo.AppId,
                ExpiresOnUtc    = authenticationResult.ExpiresOn,
                RefreshToken    = authenticationResult.RefreshToken,
                UserId          = authenticationResult.UserInfo == null ? null : authenticationResult.UserInfo.UniqueId,
            };

            return(this.CurrentAccountSession);
        }
예제 #17
0
        internal virtual AccountSession GetResultFromCache(AccountType accountType, string clientId, string userId)
        {
            var cacheNotificationArgs = new CredentialCacheNotificationArgs {
                CredentialCache = this
            };

            this.OnBeforeAccess(cacheNotificationArgs);

            var credentialCacheKey = new CredentialCacheKey
            {
                AccountType = accountType,
                ClientId    = clientId,
                UserId      = userId,
            };

            AccountSession cacheResult = null;

            this.cacheDictionary.TryGetValue(credentialCacheKey, out cacheResult);

            this.OnAfterAccess(cacheNotificationArgs);

            return(cacheResult);
        }
        public void AddToCache_CacheChangeNotifications()
        {
            var accountSession = new AccountSession
            {
                AccessToken = "token",
                UserId = "1",
            };

            this.credentialCache.AfterAccess = this.AfterAccess;
            this.credentialCache.BeforeAccess = this.BeforeAccess;
            this.credentialCache.BeforeWrite = this.BeforeWrite;

            Assert.IsNotNull(this.credentialCache.AfterAccess, "AfterAccess delegate not set.");
            Assert.IsNotNull(this.credentialCache.BeforeAccess, "BeforeAccess delegate not set.");
            Assert.IsNotNull(this.credentialCache.BeforeWrite, "BeforeWrite delegate not set.");

            this.credentialCache.AddToCache(accountSession);

            Assert.IsTrue(this.afterAccessCalled, "AfterAccess not called.");
            Assert.IsTrue(this.beforeAccessCalled, "BeforeAccess not called.");
            Assert.IsTrue(this.beforeWriteCalled, "BeforeWrite not called.");

            Assert.IsTrue(this.credentialCache.HasStateChanged, "State changed flag not set.");
        }
 /// <summary>
 /// Constructs an <see cref="AdalAuthenticationProvider"/>.
 /// </summary>
 /// <param name="serviceInfo">The information for authenticating against the service.</param>
 /// <param name="currentAccountSession">The current account session, used for initializing an already logged in user.</param>
 public AdalAuthenticationProvider(ServiceInfo serviceInfo, AccountSession currentAccountSession = null)
     : base(serviceInfo, currentAccountSession)
 {
 }
예제 #20
0
 internal override void AddToCache(AccountSession accountSession)
 {
     // Let ADAL handle the caching
 }
        internal virtual void AddToCache(AccountSession accountSession)
        {
            var cacheNotificationArgs = new CredentialCacheNotificationArgs { CredentialCache = this };

            this.OnBeforeAccess(cacheNotificationArgs);
            this.OnBeforeWrite(cacheNotificationArgs);

            var cacheKey = this.GetKeyForAuthResult(accountSession);
            this.cacheDictionary[cacheKey] = accountSession;

            this.HasStateChanged = true;
            this.OnAfterAccess(cacheNotificationArgs);
        }
 /// <summary>
 /// Constructs an <see cref="AdalAuthenticationProviderBase"/>.
 /// </summary>
 /// <param name="serviceInfo">The information for authenticating against the service.</param>
 /// <param name="currentAccountSession">The current account session, used for initializing an already logged in user.</param>
 protected AdalAuthenticationProviderBase(ServiceInfo serviceInfo, AccountSession currentAccountSession = null)
 {
     this.CurrentAccountSession = currentAccountSession;
     this.ServiceInfo           = serviceInfo;
 }
        public async Task AuthenticateAsync_RefreshToken()
        {
            var cachedAccountSession = new AccountSession
            {
                AccountType = AccountType.MicrosoftAccount,
                ClientId = "1",
                AccessToken = "token",
                ExpiresOnUtc = DateTimeOffset.UtcNow.AddMinutes(4),
                RefreshToken = "refresh",
            };

            var refreshedAccountSession = new AccountSession
            {
                AccountType = AccountType.MicrosoftAccount,
                ClientId = "1",
                AccessToken = "token2",
                RefreshToken = "refresh2",
            };

            this.authenticationProvider.CurrentAccountSession = cachedAccountSession;

            await this.AuthenticateWithRefreshToken(refreshedAccountSession);
        }
        /// <summary>
        /// Signs the current user out.
        /// </summary>
        public virtual async Task SignOutAsync()
        {
            if (this.CurrentAccountSession != null && this.CurrentAccountSession.CanSignOut)
            {
                if (this.ServiceInfo.HttpProvider != null)
                {
                    using (var httpRequestMessage = new HttpRequestMessage(HttpMethod.Get, this.ServiceInfo.SignOutUrl))
                    {
                        await this.ServiceInfo.HttpProvider.SendAsync(httpRequestMessage);
                    }
                }

                this.DeleteUserCredentialsFromCache(this.CurrentAccountSession);
                this.CurrentAccountSession = null;
            }
        }
        protected async Task AuthenticateWithRefreshToken(AccountSession refreshedAccountSession)
        {
            using (var httpResponseMessage = new HttpResponseMessage())
            using (var responseStream = new MemoryStream())
            using (var streamContent = new StreamContent(responseStream))
            {
                httpResponseMessage.Content = streamContent;

                this.httpProvider.Setup(
                    provider => provider.SendAsync(
                        It.Is<HttpRequestMessage>(
                            request => request.RequestUri.ToString().Equals(this.serviceInfo.TokenServiceUrl))))
                    .Returns(Task.FromResult<HttpResponseMessage>(httpResponseMessage));

                this.serializer.Setup(
                    serializer => serializer.DeserializeObject<IDictionary<string, string>>(It.IsAny<Stream>()))
                    .Returns(new Dictionary<string, string>
                        {
                            { Constants.Authentication.AccessTokenKeyName, refreshedAccountSession.AccessToken },
                            { Constants.Authentication.RefreshTokenKeyName, refreshedAccountSession.RefreshToken },
                        });

                var accountSession = await this.authenticationProvider.AuthenticateAsync();

                Assert.IsNotNull(accountSession, "No account session returned.");
                Assert.AreEqual(
                    refreshedAccountSession.AccessToken,
                    accountSession.AccessToken,
                    "Unexpected access token returned.");
                Assert.AreEqual(
                    refreshedAccountSession.RefreshToken,
                    accountSession.RefreshToken,
                    "Unexpected refresh token returned.");
                Assert.AreEqual(
                    refreshedAccountSession.AccessToken,
                    this.authenticationProvider.CurrentAccountSession.AccessToken,
                    "Unexpected cached access token.");
                Assert.AreEqual(
                    refreshedAccountSession.RefreshToken,
                    this.authenticationProvider.CurrentAccountSession.RefreshToken,
                    "Unexpected cached refresh token.");
            }
        }
        public async Task SignOutAsync()
        {
            var accountSession = new AccountSession
            {
                AccessToken = "accessToken",
                CanSignOut = true,
                ClientId = "12345",
            };

            this.authenticationProvider.CurrentAccountSession = accountSession;

            await this.authenticationProvider.SignOutAsync();

            this.httpProvider.Verify(
                provider => provider.SendAsync(
                    It.Is<HttpRequestMessage>(message => message.RequestUri.ToString().Equals(this.serviceInfo.SignOutUrl))),
                Times.Once);

            Assert.IsNull(this.authenticationProvider.CurrentAccountSession, "Current account session not cleared.");

            this.credentialCache.Verify(cache => cache.OnDeleteFromCache(), Times.Once);
        }
 /// <summary>
 /// Constructs an <see cref="AdalAuthenticationProviderBase"/>.
 /// </summary>
 /// <param name="serviceInfo">The information for authenticating against the service.</param>
 /// <param name="currentAccountSession">The current account session, used for initializing an already logged in user.</param>
 protected AdalAuthenticationProviderBase(ServiceInfo serviceInfo, AccountSession currentAccountSession = null)
 {
     this.CurrentAccountSession = currentAccountSession;
     this.ServiceInfo = serviceInfo;
 }
 private CredentialCacheKey GetKeyForAuthResult(AccountSession accountSession)
 {
     return new CredentialCacheKey
     {
         AccountType = accountSession.AccountType,
         ClientId = accountSession.ClientId,
         UserId = accountSession.UserId,
     };
 }
 protected void DeleteUserCredentialsFromCache(AccountSession accountSession)
 {
     if (this.ServiceInfo.CredentialCache != null)
     {
         this.ServiceInfo.CredentialCache.DeleteFromCache(accountSession);
     }
 }
        /// <summary>
        /// Retrieves the authentication token.
        /// </summary>
        /// <returns>The authentication token.</returns>
        public async Task<AccountSession> AuthenticateAsync()
        {
            if (this.CurrentAccountSession != null && !this.CurrentAccountSession.IsExpiring())
            {
                return this.CurrentAccountSession;
            }

            if (string.IsNullOrEmpty(this.ServiceInfo.ServiceResource) || string.IsNullOrEmpty(this.ServiceInfo.BaseUrl))
            {
                var discoveryServiceToken = await this.GetAuthenticationTokenForResourceAsync(this.serviceInfo.DiscoveryServiceResource);
                await this.RetrieveMyFilesServiceResourceAsync(discoveryServiceToken);
            }

            var authenticationResult = await this.AuthenticateResourceAsync(this.ServiceInfo.ServiceResource);

            if (authenticationResult == null)
            {
                this.CurrentAccountSession = null;
                return this.CurrentAccountSession;
            }

            this.CurrentAccountSession = new AdalAccountSession
            {
                AccessToken = authenticationResult.AccessToken,
                AccessTokenType = authenticationResult.AccessTokenType,
                AccountType = AccountType.ActiveDirectory,
                CanSignOut = true,
                ClientId = this.ServiceInfo.AppId,
                ExpiresOnUtc = authenticationResult.ExpiresOn,
                UserId = authenticationResult.UserInfo == null ? null : authenticationResult.UserInfo.UniqueId,
            };

            return this.CurrentAccountSession;
        }
 internal override void DeleteFromCache(AccountSession accountSession)
 {
     this.DeleteFromCacheCalled = true;
     base.DeleteFromCache(accountSession);
 }
 /// <summary>
 /// Constructs an <see cref="AdalAuthenticationProvider"/>.
 /// </summary>
 /// <param name="serviceInfo">The information for authenticating against the service.</param>
 /// <param name="currentAccountSession">The current account session, used for initializing an already logged in user.</param>
 public AdalAuthenticationProvider(ServiceInfo serviceInfo, AccountSession currentAccountSession = null)
     : base(serviceInfo, currentAccountSession)
 {
 }
        internal virtual void DeleteFromCache(AccountSession accountSession)
        {
            if (accountSession != null)
            {
                var cacheNotificationArgs = new CredentialCacheNotificationArgs { CredentialCache = this };
                this.OnBeforeAccess(cacheNotificationArgs);
                this.OnBeforeWrite(cacheNotificationArgs);

                var credentialCacheKey = this.GetKeyForAuthResult(accountSession);
                this.cacheDictionary.Remove(credentialCacheKey);

                this.HasStateChanged = true;

                this.OnAfterAccess(cacheNotificationArgs);
            }
        }
        public async Task AuthenticateAsync_CachedCurrentAccountSessionExpiring()
        {
            var cachedAccountSession = new AccountSession
            {
                AccessToken = "expiredToken",
                ExpiresOnUtc = DateTimeOffset.UtcNow,
            };

            this.authenticationProvider.CurrentAccountSession = cachedAccountSession;
            
            var mockAuthenticationResult = new MockAuthenticationResult();
            mockAuthenticationResult.SetupGet(result => result.AccessToken).Returns("token");
            mockAuthenticationResult.SetupGet(result => result.AccessTokenType).Returns("type");
            mockAuthenticationResult.SetupGet(result => result.ExpiresOn).Returns(DateTimeOffset.UtcNow.AddHours(1));

            var mockAuthenticationContextWrapper = new MockAuthenticationContextWrapper();
            mockAuthenticationContextWrapper.Setup(wrapper => wrapper.AcquireTokenSilentAsync(
                It.Is<string>(resource => resource.Equals(serviceResourceId)),
                It.Is<string>(clientId => clientId.Equals(this.serviceInfo.AppId))))
                .Returns(Task.FromResult(mockAuthenticationResult.Object));

            await this.AuthenticateAsync_AuthenticateWithoutDiscoveryService(
                mockAuthenticationContextWrapper.Object,
                mockAuthenticationResult.Object);
        }
        public async Task SignOutAsync()
        {
            var accountSession = new AccountSession
            {
                AccessToken = "accessToken",
                CanSignOut = true,
                ClientId = "12345",
            };

            this.authenticationProvider.CurrentAccountSession = accountSession;
            this.webAuthenticationUi.OnAuthenticateAsync = this.OnAuthenticateAsync_SignOut;

            await this.authenticationProvider.SignOutAsync();

            Assert.IsNull(this.authenticationProvider.CurrentAccountSession, "Current account session not cleared.");
            Assert.IsTrue(this.credentialCache.DeleteFromCacheCalled, "DeleteFromCache not called.");
        }
예제 #36
0
        internal override async Task <AccountSession> ProcessCachedAccountSessionAsync(AccountSession accountSession, IHttpProvider httpProvider)
        {
            if (accountSession != null)
            {
                if (accountSession.ShouldRefresh) // Don't check 'CanRefresh' because this type can always refresh
                {
                    accountSession = await this.GetAccountSessionAsync();

                    if (!string.IsNullOrEmpty(accountSession?.AccessToken))
                    {
                        return(accountSession);
                    }
                }
                else
                {
                    return(accountSession);
                }
            }

            return(null);
        }
        public async Task SignOutAsync()
        {
            this.signOut = true;
            var expectedSignOutUrl = string.Format(
                "{0}?client_id={1}&redirect_uri={2}",
                this.serviceInfo.SignOutUrl,
                this.serviceInfo.AppId,
                this.serviceInfo.ReturnUrl);

            var accountSession = new AccountSession
            {
                AccessToken = "accessToken",
                ClientId = "12345",
            };

            this.authenticationProvider.CurrentAccountSession = accountSession;

            await this.authenticationProvider.SignOutAsync();

            Assert.IsNull(this.authenticationProvider.CurrentAccountSession, "Current account session not cleared.");
            Assert.IsTrue(this.credentialCache.DeleteFromCacheCalled, "DeleteFromCache not called.");
        }
 internal override void AddToCache(AccountSession accountSession)
 {
     this.AddToCacheCalled = true;
     base.AddToCache(accountSession);
 }
        private AccountSession ProcessAuthenticationResult(IAuthenticationResult authenticationResult)
        {
            if (authenticationResult == null)
            {
                this.CurrentAccountSession = null;
                return this.CurrentAccountSession;
            }

            this.CurrentAccountSession = new AdalAccountSession
            {
                AccessToken = authenticationResult.AccessToken,
                AccessTokenType = authenticationResult.AccessTokenType,
                AccountType = AccountType.ActiveDirectory,
                CanSignOut = true,
                ClientId = this.ServiceInfo.AppId,
                ExpiresOnUtc = authenticationResult.ExpiresOn,
                RefreshToken = authenticationResult.RefreshToken,
                UserId = authenticationResult.UserInfo == null ? null : authenticationResult.UserInfo.UniqueId,
            };

            return this.CurrentAccountSession;
        }