private async Task <IAuthenticationResult> PromptUserForAuthenticationWithClientCertificateAsync( string serviceResourceId, string userId) { IAuthenticationResult authenticationResult = null; var clientAssertionCertificate = new ClientAssertionCertificate(this.clientId, this.clientCertificate); var userIdentifier = this.GetUserIdentifierForAuthentication(userId); var redirectUri = new Uri(this.returnUrl); var requestUri = new Uri(this.oAuthHelper.GetAuthorizationCodeRequestUrl( this.clientId, this.returnUrl, null, userId)); var authenticationResponseValues = await webAuthenticationUi.AuthenticateAsync( requestUri, redirectUri).ConfigureAwait(false); OAuthErrorHandler.ThrowIfError(authenticationResponseValues); string code; if (authenticationResponseValues != null && authenticationResponseValues.TryGetValue("code", out code)) { authenticationResult = await this.authenticationContextWrapper.AcquireTokenByAuthorizationCodeAsync( code, redirectUri, clientAssertionCertificate, serviceResourceId).ConfigureAwait(false); } return(authenticationResult); }
/// <summary> /// Retrieves an authentication result for the specified resource. /// </summary> /// <param name="resource">The resource to authenticate.</param> /// <returns>The <see cref="IAuthenticationResult"/> returned for the resource.</returns> protected override async Task <IAuthenticationResult> AuthenticateResourceAsync(string resource) { IAuthenticationResult authenticationResult = null; try { var adalServiceInfo = this.ServiceInfo as AdalServiceInfo; // If we have a client certificate authenticate using it. Use client secret authentication if not. if (adalServiceInfo != null && adalServiceInfo.ClientCertificate != null) { authenticationResult = await this.AuthenticateUsingCertificate(adalServiceInfo, resource); } else { authenticationResult = await this.AuthenticateUsingClientSecret(resource); } } catch (Exception exception) { AuthenticationExceptionHelper.HandleAuthenticationException(exception); } if (authenticationResult == null) { AuthenticationExceptionHelper.HandleAuthenticationException(null); } return(authenticationResult); }
public Task <IAuthenticationResult> AuthenticateAsync(IEnumerable <Type> authenticators, bool saveResult) { return(Task.Run <IAuthenticationResult>(() => { HttpContext httpContext = httpContextAccessor.HttpContext; AuthenticationInternalResult result = null; foreach (Type authenticator in authenticators) { if (AuthenticationHelper.IsValidAuthenticator(httpContext.RequestServices.GetRequiredService <IAuthenticatorMethodCache>(), authenticator, out AuthenticatorMetadata authenticateMethod)) { result = AuthenticationHelper.ExecuteAuthenticator(httpContext, authenticateMethod); if (result != null && result.KeepUnauthenticated == false && result.User != null) { IAuthenticationResult authentication = AuthenticationResult.CAS(result.User); if (saveResult) { accessor.Result = authentication; } return authentication; } } } return AuthenticationResult.Unauthenticated(); })); }
private async Task <IAuthenticationResult> SilentlyAuthenticateUserWithClientCertificateAsync( string serviceResourceId, string userId, bool throwOnError) { IAuthenticationResult authenticationResult = null; var clientAssertionCertificate = new ClientAssertionCertificate(this.clientId, this.clientCertificate); var userIdentifier = this.GetUserIdentifierForAuthentication(userId); try { authenticationResult = await this.authenticationContextWrapper.AcquireTokenSilentAsync( serviceResourceId, clientAssertionCertificate, userIdentifier).ConfigureAwait(false); } catch (Exception) { if (throwOnError) { throw; } } return(authenticationResult); }
public async Task AuthenticateAsync_AuthenticateWithoutDiscoveryService( IAuthenticationResult authenticationResult, MockAuthenticationContextWrapper.AuthenticationResultCallback authenticationResultCallback, MockAuthenticationContextWrapper.AuthenticationResultSilentCallback authenticationResultSilentCallback, MockAuthenticationContextWrapper.AuthenticationResultByRefreshTokenCallback authenticationResultByRefreshTokenCallback) { this.serviceInfo.BaseUrl = "https://localhost"; this.serviceInfo.ServiceResource = "https://resource/"; this.authenticationProvider.authenticationContextWrapper = new MockAuthenticationContextWrapper { AcquireTokenAsyncCallback = authenticationResultCallback, AcquireTokenSilentAsyncCallback = authenticationResultSilentCallback, AcquireTokenByRefreshTokenAsyncCallback = authenticationResultByRefreshTokenCallback, }; var accountSession = await this.authenticationProvider.AuthenticateAsync(); Assert.AreEqual(authenticationResult.AccessToken, accountSession.AccessToken, "Unexpected access token set."); Assert.AreEqual(authenticationResult.AccessTokenType, accountSession.AccessTokenType, "Unexpected access token type set."); Assert.AreEqual(AccountType.ActiveDirectory, accountSession.AccountType, "Unexpected account type set."); Assert.IsTrue(accountSession.CanSignOut, "CanSignOut set to false."); Assert.AreEqual(this.serviceInfo.AppId, accountSession.ClientId, "Unexpected client ID set."); Assert.AreEqual(authenticationResult.ExpiresOn, accountSession.ExpiresOnUtc, "Unexpected expiration set."); Assert.IsNull(accountSession.UserId, "Unexpected user ID set."); }
/// <summary> /// Redeems the refresh token for the provided service info to retrieve an authentication result. /// </summary> /// <param name="refreshToken">The code for retrieving the authentication token.</param> /// <returns>The <see cref="IAuthenticationResult"/> returned for the resource.</returns> public async Task <IAuthenticationResult> RedeemRefreshToken(string refreshToken) { IAuthenticationResult authenticationResult = null; try { authenticationResult = await this.authenticationContextWrapper.AcquireTokenByRefreshTokenAsync( refreshToken, this.serviceInfo.AppId, this.serviceInfo.ServiceResource); } catch (Exception exception) { AuthenticationExceptionHelper.HandleAuthenticationException(exception); } if (authenticationResult.Status != AuthenticationStatus.Success) { throw new OneDriveException( new Error { Code = OneDriveErrorCode.AuthenticationFailure.ToString(), Message = authenticationResult == null ? "An error occurred during Azure Active Directory authentication." : string.Format("An error occurred during Azure Active Directory authentication. Error: {0}. Description: {1}", authenticationResult.Error, authenticationResult.ErrorDescription), }); } return(authenticationResult); }
public async Task AuthenticateRequestAsync(HttpRequestMessage request) { if (this.CurrentAccountSession == null) { throw new ServiceException( new Error { Code = OAuthConstants.ErrorCodes.AuthenticationFailure, Message = "Please call one of the AuthenticateUserAsync...() methods to authenticate the user before trying to authenticate a request.", }); } if (this.CurrentAccountSession.IsExpiring) { if (!string.IsNullOrEmpty(this.CurrentAccountSession.RefreshToken)) { await this.AuthenticateUserWithRefreshTokenAsync( this.CurrentAccountSession.RefreshToken, this.currentServiceResourceId).ConfigureAwait(false); } else { IAuthenticationResult silentAuthenticationResult = null; var authenticationFailedErrorMessage = "Failed to retrieve a cached account session or silently retrieve a new access token. Please call AuthenticateUserAsync...() again to re-authenticate."; try { silentAuthenticationResult = await this.AuthenticateUserSilently( this.currentServiceResourceId, this.CurrentAccountSession.UserId, true).ConfigureAwait(false); } catch (Exception exception) { throw new ServiceException( new Error { Code = OAuthConstants.ErrorCodes.AuthenticationFailure, Message = authenticationFailedErrorMessage }, exception); } this.ValidateAuthenticationResult(silentAuthenticationResult, authenticationFailedErrorMessage); this.CurrentAccountSession = this.ConvertAuthenticationResultToAccountSession(silentAuthenticationResult); } } var accessTokenType = string.IsNullOrEmpty(this.CurrentAccountSession.AccessTokenType) ? OAuthConstants.Headers.Bearer : this.CurrentAccountSession.AccessTokenType; request.Headers.Authorization = new AuthenticationHeaderValue( accessTokenType, this.CurrentAccountSession.AccessToken); }
public async Task AuthenticateUserAsync(string serviceResourceId, string userId = null) { if (string.IsNullOrEmpty(serviceResourceId)) { throw new ServiceException( new Error { Code = OAuthConstants.ErrorCodes.AuthenticationFailure, Message = "Service resource ID is required to authenticate a user with AuthenticateUserAsync." }); } this.currentServiceResourceId = serviceResourceId; IAuthenticationResult authenticationResult = null; try { authenticationResult = await this.AuthenticateUserSilently(serviceResourceId, userId, false).ConfigureAwait(false); this.ValidateAuthenticationResult(authenticationResult); } catch (Exception) { // If silent authentication fails swallow the exception and try prompting the user. // Reset authenticationResult to null in case we have a failed result object. authenticationResult = null; } if (authenticationResult == null) { if (string.IsNullOrEmpty(returnUrl)) { throw new ServiceException( new Error { Code = OAuthConstants.ErrorCodes.AuthenticationFailure, Message = "The user could not be silently authenticated and return URL is required to prompt the user for authentication." }); } try { authenticationResult = await this.AuthenticateUser(serviceResourceId, userId).ConfigureAwait(false); } catch (Exception exception) { BusinessAuthenticationExceptionHelper.HandleAuthenticationException(exception); } if (authenticationResult == null) { BusinessAuthenticationExceptionHelper.HandleAuthenticationException(null); } } this.CurrentAccountSession = this.ConvertAuthenticationResultToAccountSession(authenticationResult); }
public void AttemptLogin(string username, string password, IStoredCredentialsRepository repo) { var credentials = new UsernameAndPassword { Username = username, Password = password }; var authenticationService = GetAuthenticationService(repo); authenticationResult = authenticationService.Authenticate(credentials); }
public override async Task AuthenticateUserWithRefreshTokenAsync(string refreshToken, string serviceResourceId) { if (string.IsNullOrEmpty(refreshToken)) { throw new ServiceException( new Error { Code = OAuthConstants.ErrorCodes.AuthenticationFailure, Message = "Refresh token is required to authenticate a user with a refresh token." }); } this.currentServiceResourceId = serviceResourceId; IAuthenticationResult authenticationResult = null; try { if (this.clientCertificate != null) { var clientAssertionCertificate = new ClientAssertionCertificate(this.clientId, this.clientCertificate); authenticationResult = await this.authenticationContextWrapper.AcquireTokenByRefreshTokenAsync( refreshToken, clientAssertionCertificate, serviceResourceId).ConfigureAwait(false); } else if (!string.IsNullOrEmpty(this.clientSecret)) { var clientCredential = this.GetClientCredentialForAuthentication(this.clientId, this.clientSecret); authenticationResult = await this.authenticationContextWrapper.AcquireTokenByRefreshTokenAsync( refreshToken, clientCredential, serviceResourceId).ConfigureAwait(false); } else { authenticationResult = await this.authenticationContextWrapper.AcquireTokenByRefreshTokenAsync( refreshToken, this.clientId, serviceResourceId).ConfigureAwait(false); } } catch (Exception exception) { BusinessAuthenticationExceptionHelper.HandleAuthenticationException(exception); } if (authenticationResult == null) { BusinessAuthenticationExceptionHelper.HandleAuthenticationException(null); } this.CurrentAccountSession = this.ConvertAuthenticationResultToAccountSession(authenticationResult); }
public string Index([FromServices] IAuthenticationResult result) { if (result.IsAuthenticated) { return($"hello, {result.User.Name} from index"); } else { return("hello, index"); } }
public ClaimsIdentity GetIdentity(IAuthenticationResult result, string authenticationType) { if (result == null) { throw new ArgumentNullException(nameof(result)); } if (!result.Success) { throw new ArgumentException("Authentication result must indicate success.", nameof(result)); } return(GetIdentity(result.Username, result.UserIdentity, authenticationType)); }
internal async Task <HttpResponseMessage> InvokeActionWithAuthenticationFiltersAsync( HttpActionContext actionContext, CancellationToken cancellationToken, IEnumerable <IAuthenticationFilter> filters, Func <Task <HttpResponseMessage> > innerAction) { Contract.Assert(actionContext != null); Contract.Assert(filters != null); Contract.Assert(innerAction != null); IHttpActionResult innerResult = new ContinuationResult(innerAction); HttpAuthenticationContext authenticationContext = new HttpAuthenticationContext(actionContext); authenticationContext.Principal = _principalService.CurrentPrincipal; foreach (IAuthenticationFilter filter in filters) { cancellationToken.ThrowIfCancellationRequested(); IAuthenticationResult result = await filter.AuthenticateAsync(authenticationContext, cancellationToken); if (result != null) { IHttpActionResult error = result.ErrorResult; // Short-circuit on the first authentication filter to provide an error result. if (error != null) { innerResult = error; break; } IPrincipal principal = result.Principal; if (principal != null) { authenticationContext.Principal = principal; _principalService.CurrentPrincipal = principal; } } } foreach (IAuthenticationFilter filter in filters) { cancellationToken.ThrowIfCancellationRequested(); innerResult = await filter.ChallengeAsync(actionContext, innerResult, cancellationToken) ?? innerResult; } cancellationToken.ThrowIfCancellationRequested(); return(await innerResult.ExecuteAsync(cancellationToken)); }
internal static IAuthenticationResult ReadAuthenticationResult(HttpContext httpContext) { if (httpContext.Items.TryGetValue(AUTHENTICATION_RESULT_KEY, out object value)) { if (value is IAuthenticationResult result) { return(result); } } IAuthenticationResult tempresult = AuthenticationResult.Unauthenticated(); SaveAuthenticationResult(httpContext, tempresult); return(tempresult); }
public RegisterViewModel GetUserFromARToken(IAuthenticationResult ar) { JObject user = ParseIdToken(ar.IdToken); var name = user["name"]?.ToString(); var oID = user["oid"]?.ToString(); return(new RegisterViewModel() { FirstName = name, LastName = "Edit", OID = oID, TokenID = ar.IdToken }); }
public MockAccessTokenCache( string initialCertData = DefaultCertificateData, string certData = DefaultCertificateData, IAuthenticationResult initialValue = null, bool throwOnAcquireToken = false, params IAuthenticationResult[] mockTokens) { InitialValue = (initialValue == null) ? null : new AccessTokenCacheValue(initialCertData, initialValue); ThrowOnAcquireToken = throwOnAcquireToken; MockValues = mockTokens.Select(t => new AccessTokenCacheValue(certData, t)).ToArray(); }
protected override async Task <IAuthenticationResult> AuthenticateResourceAsync(string resource) { IAuthenticationResult authenticationResult = null; var clientCredential = string.IsNullOrEmpty(this.serviceInfo.ClientSecret) ? null : new ClientCredential(this.serviceInfo.AppId, this.serviceInfo.ClientSecret); var userIdentifier = this.GetUserIdentifierForAuthentication(); try { authenticationResult = clientCredential == null ? await this.authenticationContextWrapper.AcquireTokenSilentAsync(resource, this.serviceInfo.AppId) : await this.authenticationContextWrapper.AcquireTokenSilentAsync(resource, clientCredential, userIdentifier); } catch (Exception) { // If an exception happens during silent authentication try interactive authentication. } if (authenticationResult != null) { return(authenticationResult); } try { authenticationResult = clientCredential == null ? this.authenticationContextWrapper.AcquireToken( resource, this.ServiceInfo.AppId, new Uri(this.ServiceInfo.ReturnUrl), PromptBehavior.Auto, userIdentifier) : await this.authenticationContextWrapper.AcquireTokenAsync(resource, clientCredential); } catch (AdalException adalException) { throw this.GetAuthenticationException(string.Equals(adalException.ErrorCode, Constants.Authentication.AuthenticationCancelled), adalException); } catch (Exception exception) { throw this.GetAuthenticationException(false, exception); } if (authenticationResult == null) { throw this.GetAuthenticationException(); } return(authenticationResult); }
public async Task <IActionResult> No([FromServices] IAuthenticationService service) { IAuthenticationResult result = await service.CASAsync(); if (result.IsAuthenticated) { ContentResult content = new ContentResult(); content.Content = "hello from no " + result.User.Name; return(content); } else { return(service.CreateRedirectCASResult()); } }
public async Task AuthenticateAsync_AuthenticateWithDiscoveryService( MockAuthenticationContextWrapper mockAuthenticationContextWrapper, IAuthenticationResult authenticationResult) { var accountSession = await this.AuthenticateWithDiscoveryService(mockAuthenticationContextWrapper); Assert.AreEqual(accountSession, this.authenticationProvider.CurrentAccountSession, "Account session not cached correctly."); Assert.AreEqual(serviceEndpointUri, this.serviceInfo.BaseUrl, "Base URL not set."); Assert.AreEqual(serviceResourceId, this.serviceInfo.ServiceResource, "Service resource not set."); Assert.AreEqual(authenticationResult.AccessToken, accountSession.AccessToken, "Unexpected access token set."); Assert.AreEqual(authenticationResult.AccessTokenType, accountSession.AccessTokenType, "Unexpected access token type set."); Assert.AreEqual(AccountType.ActiveDirectory, accountSession.AccountType, "Unexpected account type set."); Assert.IsTrue(accountSession.CanSignOut, "CanSignOut set to false."); Assert.AreEqual(this.serviceInfo.AppId, accountSession.ClientId, "Unexpected client ID set."); Assert.AreEqual(authenticationResult.ExpiresOn, accountSession.ExpiresOnUtc, "Unexpected expiration set."); Assert.IsNull(accountSession.UserId, "Unexpected user ID set."); }
protected AccountSession ConvertAuthenticationResultToAccountSession(IAuthenticationResult authenticationResult) { if (authenticationResult == null) { return(null); } return(new AccountSession { AccessToken = authenticationResult.AccessToken, AccessTokenType = authenticationResult.AccessTokenType, ClientId = this.clientId, ExpiresOnUtc = authenticationResult.ExpiresOn, RefreshToken = authenticationResult.RefreshToken, UserId = authenticationResult.UserInfo == null ? null : authenticationResult.UserInfo.UniqueId, }); }
protected virtual void ValidateAuthenticationResult(IAuthenticationResult authenticationResult, string errorMessage = null) { if (string.IsNullOrEmpty(errorMessage)) { errorMessage = "Failed to retrieve a valid authentication result."; } if (authenticationResult == null) { throw new ServiceException( new Error { Code = OAuthConstants.ErrorCodes.AuthenticationFailure, Message = errorMessage, }); } }
public virtual void Connect() { if (!Connected) { //Todo: Move to Unity? ICredentialsProvider credentialsProvider = new AppConfigReaderCredentialsProvider(); ICredentialStore credentials = credentialsProvider.RetrieveCredentials(); Authorizer = new SingleUserAuthorizer { CredentialStore = credentials }; IAuthenticator authenticator = new DefaultAuthenticator(Logger); IAuthenticationResult authenticationResult = authenticator.Authenticate(Authorizer); Connected = authenticationResult.Success; Severity severity = Connected ? Severity.Information : Severity.Error; Logger.LogMessage(new LogMessage(authenticationResult.Message, severity)); } }
/// <summary> /// Retrieves an authentication result for the specified resource. /// </summary> /// <param name="resource">The resource to authenticate.</param> /// <returns>The <see cref="IAuthenticationResult"/> returned for the resource.</returns> protected override async Task <IAuthenticationResult> AuthenticateResourceAsync(string resource) { IAuthenticationResult authenticationResult = null; var adalServiceInfo = this.ServiceInfo as AdalServiceInfo; if (adalServiceInfo == null) { throw new OneDriveException( new Error { Code = OneDriveErrorCode.AuthenticationFailure.ToString(), Message = "AdalAppOnlyServiceInfoProvider requires an AdalServiceInfo." }); } if (adalServiceInfo.ClientCertificate == null) { throw new OneDriveException( new Error { Code = OneDriveErrorCode.AuthenticationFailure.ToString(), Message = "Client certificate is required for app-only authentication." }); } var clientAssertionCertificate = new ClientAssertionCertificate(adalServiceInfo.AppId, adalServiceInfo.ClientCertificate); try { authenticationResult = await this.authenticationContextWrapper.AcquireTokenAsync(resource, clientAssertionCertificate); } catch (Exception exception) { AuthenticationExceptionHelper.HandleAuthenticationException(exception); } if (authenticationResult == null) { AuthenticationExceptionHelper.HandleAuthenticationException(null); } return(authenticationResult); }
public Task <IAuthenticationResult> CASAsync(bool saveResult) { return(Task.Run <IAuthenticationResult>(() => { HttpContext httpContext = httpContextAccessor.HttpContext; AuthenticationInternalResult result = AuthenticationHelper.ExecuteCAS(httpContext); if (result != null && result.KeepUnauthenticated == false && result.User != null) { IAuthenticationResult authentication = AuthenticationResult.CAS(result.User); if (saveResult) { accessor.Result = authentication; } return authentication; } return AuthenticationResult.Unauthenticated(); })); }
protected override void ValidateAuthenticationResult(IAuthenticationResult authenticationResult, string errorMessage = null) { if (authenticationResult == null || authenticationResult.Status != AuthenticationStatus.Success) { if (string.IsNullOrEmpty(errorMessage)) { errorMessage = "Failed to retrieve a valid authentication result."; } var innerException = new Exception(authenticationResult.ErrorDescription); throw new ServiceException( new Error { Code = OAuthConstants.ErrorCodes.AuthenticationFailure, Message = errorMessage, }, innerException); } }
protected override async Task <IAuthenticationResult> AuthenticateResourceAsync(string resource) { IAuthenticationResult authenticationResult = null; var userIdentifier = this.GetUserIdentifierForAuthentication(); try { authenticationResult = await this.authenticationContextWrapper.AcquireTokenSilentAsync(resource, this.serviceInfo.AppId, userIdentifier); } catch (Exception) { // If an exception happens during silent authentication try interactive authentication. } if (authenticationResult != null && authenticationResult.Status == AuthenticationStatus.Success) { return(authenticationResult); } authenticationResult = await this.authenticationContextWrapper.AcquireTokenAsync( resource, this.ServiceInfo.AppId, new Uri(this.ServiceInfo.ReturnUrl), PromptBehavior.Auto, userIdentifier); if (authenticationResult == null || authenticationResult.Status != AuthenticationStatus.Success) { throw new OneDriveException( new Error { Code = OneDriveErrorCode.AuthenticationFailure.ToString(), Message = authenticationResult == null ? "An error occurred during active directory authentication." : string.Format("An error occurred during active directory authentication. Error: {0}. Description: {1}", authenticationResult.Error, authenticationResult.ErrorDescription), }); } return(authenticationResult); }
public async Task AuthenticateAsync_AuthenticateWithoutDiscoveryService( IAuthenticationContextWrapper authenticationContextWrapper, IAuthenticationResult authenticationResult) { this.serviceInfo.BaseUrl = "https://localhost"; this.serviceInfo.ServiceResource = serviceResourceId; this.authenticationProvider.authenticationContextWrapper = authenticationContextWrapper; var accountSession = await this.authenticationProvider.AuthenticateAsync(); Assert.AreEqual(accountSession, this.authenticationProvider.CurrentAccountSession, "Account session not cached correctly."); Assert.AreEqual(authenticationResult.AccessToken, accountSession.AccessToken, "Unexpected access token set."); Assert.AreEqual(authenticationResult.AccessTokenType, accountSession.AccessTokenType, "Unexpected access token type set."); Assert.AreEqual(AccountType.ActiveDirectory, accountSession.AccountType, "Unexpected account type set."); Assert.IsTrue(accountSession.CanSignOut, "CanSignOut set to false."); Assert.AreEqual(this.serviceInfo.AppId, accountSession.ClientId, "Unexpected client ID set."); Assert.AreEqual(authenticationResult.ExpiresOn, accountSession.ExpiresOnUtc, "Unexpected expiration set."); Assert.IsNull(accountSession.UserId, "Unexpected user ID set."); }
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); }
public void RegistryTest() { // create the container and register the mappings var container = new Container(); container.RegisterForApplication(); // retrieve the individual mappings and check the result IAuthenticationResult result = container.GetInstance <IAuthenticationResult>(); Assert.IsInstanceOf <AuthenticationResult>(result); IAuthenticationService authenticationService = container.GetInstance <IAuthenticationService>(); Assert.IsInstanceOf <AuthenticationService>(authenticationService); // TODO check what to do with all this, why is the Bootstrapper version not static available, do I need to pass it around? ObjectFactory.Configure(o => o.AddRegistry <ApplicationRegistry>()); IAuthenticationResult result2 = ObjectFactory.GetInstance <IAuthenticationResult>(); Assert.IsInstanceOf <AuthenticationResult>(result2); }
/// <summary> /// Redeems the refresh token for the provided service info to retrieve an authentication result. /// </summary> /// <param name="refreshToken">The code for retrieving the authentication token.</param> /// <returns>The <see cref="IAuthenticationResult"/> returned for the resource.</returns> public async Task <IAuthenticationResult> RedeemRefreshToken(string refreshToken) { IAuthenticationResult authenticationResult = null; var adalServiceInfo = this.serviceInfo as AdalServiceInfo; try { // If we have a client certificate authenticate using it. Use client secret authentication if not. if (adalServiceInfo != null && adalServiceInfo.ClientCertificate != null) { authenticationResult = await this.AuthenticateUsingCertificate(adalServiceInfo, refreshToken); } else if (!string.IsNullOrEmpty(serviceInfo.ClientSecret)) { authenticationResult = await this.AuthenticateUsingClientSecret(refreshToken); } else { authenticationResult = await this.authenticationContextWrapper.AcquireTokenByRefreshTokenAsync( refreshToken, this.serviceInfo.AppId, this.serviceInfo.ServiceResource); } } catch (Exception exception) { AuthenticationExceptionHelper.HandleAuthenticationException(exception); } if (authenticationResult == null) { AuthenticationExceptionHelper.HandleAuthenticationException(null); } return(authenticationResult); }
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; }
public async Task AuthenticateAsync_AuthenticateWithDiscoveryService( IAuthenticationResult authenticationResult, MockAuthenticationContextWrapper.AuthenticationResultCallback authenticationResultCallback, MockAuthenticationContextWrapper.AuthenticationResultSilentCallback authenticationResultSilentCallback) { const string serviceEndpointUri = "https://localhost"; const string serviceResourceId = "https://localhost/resource/"; var discoveryServiceResponse = new DiscoveryServiceResponse { Value = new List<DiscoveryService> { new DiscoveryService { Capability = Constants.Authentication.MyFilesCapability, ServiceApiVersion = this.serviceInfo.OneDriveServiceEndpointVersion, ServiceEndpointUri = serviceEndpointUri, ServiceResourceId = serviceResourceId, } } }; var accountSession = await this.AuthenticateWithDiscoveryService( authenticationResultCallback, authenticationResultSilentCallback); Assert.AreEqual(serviceEndpointUri, this.serviceInfo.BaseUrl, "Base URL not set."); Assert.AreEqual(serviceResourceId, this.serviceInfo.ServiceResource, "Service resource not set."); Assert.AreEqual(authenticationResult.AccessToken, accountSession.AccessToken, "Unexpected access token set."); Assert.AreEqual(authenticationResult.AccessTokenType, accountSession.AccessTokenType, "Unexpected access token type set."); Assert.AreEqual(AccountType.ActiveDirectory, accountSession.AccountType, "Unexpected account type set."); Assert.IsTrue(accountSession.CanSignOut, "CanSignOut set to false."); Assert.AreEqual(this.serviceInfo.AppId, accountSession.ClientId, "Unexpected client ID set."); Assert.AreEqual(authenticationResult.ExpiresOn, accountSession.ExpiresOnUtc, "Unexpected expiration set."); Assert.IsNull(accountSession.UserId, "Unexpected user ID set."); }