static TokenInfo TokenIsValid(IKeyValueSettings settings, string token) { // Check we have all the data available: a token, settings and the ServiceApplicationId. if (null == settings) { return(null); } if (String.IsNullOrWhiteSpace(token)) { return(null); } if (!settings.Values.ContainsKey(TokenKeys.ServiceApplicationIdKey)) { return(null); } var audience = settings.Values[TokenKeys.ServiceApplicationIdKey]; var jwtToken = new JwtSecurityToken(token); if (jwtToken.Audiences.Any(a => a.StartsWith(audience, StringComparison.InvariantCultureIgnoreCase))) { return(new TokenInfo("Bearer", token, String.Empty, jwtToken.ValidTo)); } return(null); }
public void SignOut(IKeyValueSettings settings) { GetSettings(settings, out var serviceId, out _, out var passwordStoreKey); try { // remove the passord information. var pwdkey = passwordStoreKey + "_pwd"; secureCache.Remove(pwdkey); } catch (Exception ex) { Logger.Technical().From <UsernamePasswordTokenProvider>().Exception(ex).Log(); } try { // remove de access token information. secureCache.Remove(serviceId); } catch (Exception ex) { Logger.Technical().From <UsernamePasswordTokenProvider>().Exception(ex).Log(); } }
private void ValidateSettings(IKeyValueSettings settings) { if (null == settings) { throw new ArgumentNullException(nameof(settings)); } var messages = new Messages(); if (!settings.Values.ContainsKey(TokenKeys.ProviderIdKey)) { messages.Add(new Message(Arc4u.ServiceModel.MessageCategory.Technical, MessageType.Error, "No Provider defined.")); } else if (!settings.Values[TokenKeys.ProviderIdKey].Equals(ProviderName)) { messages.Add(new Message(Arc4u.ServiceModel.MessageCategory.Technical, MessageType.Error, $"Provider {settings.Values[TokenKeys.ProviderIdKey]} is not the expected one: {ProviderName}.")); } if (!settings.Values.ContainsKey("OboEndpointUrl")) { messages.Add(new Message(Arc4u.ServiceModel.MessageCategory.Technical, MessageType.Error, "No Obo url defined.")); } else if (!Uri.TryCreate(settings.Values["OboEndpointUrl"], UriKind.Absolute, out var uri)) { messages.Add(new Message(Arc4u.ServiceModel.MessageCategory.Technical, MessageType.Error, "Obo url is invalid.")); } messages.LogAndThrowIfNecessary(this); // I can do this because settings is registered in the DI as Shared => Singleton! _settings.Add(settings.GetHashCode(), settings); }
private static void ValidateKeys(IKeyValueSettings settings, out string clientSecret, out string serviceApplicationId, out CertificateInfo certificateInfo) { var messages = new Messages(); if (!settings.Values.ContainsKey(TokenKeys.ServiceApplicationIdKey)) { throw new ArgumentException("ServiceApplicationId is missing. Cannot process the request."); } serviceApplicationId = settings.Values[TokenKeys.ServiceApplicationIdKey]; if (!settings.Values.ContainsKey(TokenKeys.ClientSecret)) { throw new ArgumentException("Client secret is missing. Cannot process the request."); } clientSecret = settings.Values[TokenKeys.ClientSecret]; if (String.IsNullOrWhiteSpace(clientSecret)) { messages.Add(new Message(ServiceModel.MessageCategory.Technical, ServiceModel.MessageType.Warning, $"{TokenKeys.ClientSecret} is not defined in the configuration file.")); } else { Logger.Technical.From <ClientSecretTokenProvider>().System($"{TokenKeys.ApplicationKey} = {clientSecret}.").Log(); } var certificateName = settings.Values.ContainsKey(TokenKeys.CertificateName) ? settings.Values[TokenKeys.CertificateName] : null; var findType = settings.Values.ContainsKey(TokenKeys.FindType) ? settings.Values[TokenKeys.FindType] : null; var storeLocation = settings.Values.ContainsKey(TokenKeys.StoreLocation) ? settings.Values[TokenKeys.StoreLocation] : null; var storeName = settings.Values.ContainsKey(TokenKeys.StoreName) ? settings.Values[TokenKeys.StoreName] : null; if (null == certificateName) { Logger.Technical.From <ClientSecretTokenProvider>().System("No Certificate, Base64 encoding of the username password.").Log(); certificateInfo = null; } else { certificateInfo = new CertificateInfo { Name = certificateName }; if (Enum.TryParse(findType, out X509FindType x509FindType)) { certificateInfo.FindType = x509FindType; } if (Enum.TryParse(storeLocation, out StoreLocation storeLocation_)) { certificateInfo.Location = storeLocation_; } if (Enum.TryParse(storeName, out StoreName storeName_)) { certificateInfo.StoreName = storeName_; } } messages.LogAndThrowIfNecessary(typeof(ClientSecretTokenProvider)); }
private async Task <TokenInfo> AuthenticationResultAsync(IKeyValueSettings settings) { ValidateKeys(settings, out string clientSecret, out string serviceApplicationId, out var certificateInfo); var cacheKey = "Secret_" + serviceApplicationId.ToLowerInvariant() + clientSecret.GetHashCode().ToString(); var tokenInfo = TokenCache.Get <TokenInfo>(cacheKey); if (null == tokenInfo || tokenInfo.ExpiresOnUtc < DateTime.UtcNow.AddMinutes(-1)) { CredentialsResult credential; if (null != certificateInfo) { credential = GetCredential(clientSecret, certificateInfo); } else { // extract from the client secret the upn and password. credential = GetCredential(clientSecret); } if (!credential.CredentialsEntered) { return(null); } tokenInfo = await CreateBasicTokenInfoAsync(settings, credential); TokenCache.Put(cacheKey, tokenInfo); } return(tokenInfo); }
public Task <TokenInfo> GetTokenAsync(IKeyValueSettings settings, object platformParameters) { if (null == settings) { throw new ArgumentNullException(nameof(settings)); } // Read the settings to extract the data: // HeaderKey => default = SecretKey // ClientSecret: the encrypted username/password. var headerKey = "SecretKey"; if (settings.Values.ContainsKey(TokenKeys.ClientSecretHeader)) { headerKey = settings.Values[TokenKeys.ClientSecretHeader]; } if (!settings.Values.ContainsKey(TokenKeys.ClientSecret)) { throw new ArgumentException("Client secret is missing. Cannot process the request."); } var clientSecret = settings.Values[TokenKeys.ClientSecret]; return(Task.FromResult(new TokenInfo(headerKey, clientSecret, "", DateTime.UtcNow + TimeSpan.FromHours(1)))); }
private async Task <AuthenticationResult> AuthenticationResultAsync(IKeyValueSettings settings) { var authContext = GetContext(settings, out string serviceApplicationId, out string userObjectId, out ClientCredential credential, out string clientId, out Uri redirectUri); AuthenticationResult result = null; if (null != credential) { Logger.Technical().From(this).System("Acquire a token silently for an application identified by his application key.").Log(); if (Enum.TryParse <UserIdentifierType>(oAuthConfig.User.Identifier, out var identifier)) { result = await authContext.AcquireTokenSilentAsync(serviceApplicationId, credential, new UserIdentifier(userObjectId, identifier)); } } if (null != result) { // Dump no sensitive information. Logger.Technical().From(this).System($"Token information for user {result.UserInfo.DisplayableId}.").Log(); Logger.Technical().From(this).System($"Token expiration = {result.ExpiresOn.ToString("dd-MM-yyyy HH:mm:ss")}.").Log(); } return(result); }
private void ExtractFromSettings(IKeyValueSettings settings, out string passwordStoreKey) { passwordStoreKey = "secret"; if (settings.Values.ContainsKey(TokenKeys.PasswordStoreKey)) { passwordStoreKey = String.IsNullOrWhiteSpace(settings.Values[TokenKeys.PasswordStoreKey]) ? passwordStoreKey : settings.Values[TokenKeys.PasswordStoreKey]; } }
public void SignOut(IKeyValueSettings settings) { ValidateKeys(settings, out string clientSecret, out string serviceApplicationId, out var certificateInfo); var cacheKey = "Secret_" + serviceApplicationId.ToLowerInvariant() + clientSecret.GetHashCode().ToString(); TokenCache.DeleteItem(cacheKey); }
private AuthenticationContext GetContext(IKeyValueSettings settings, out string serviceId, out string clientId, out string authority) { // Valdate arguments. if (!settings.Values.ContainsKey(TokenKeys.AuthorityKey)) { throw new ArgumentException("Authority is missing. Cannot process the request."); } if (!settings.Values.ContainsKey(TokenKeys.ClientIdKey)) { throw new ArgumentException("ClientId is missing. Cannot process the request."); } if (!settings.Values.ContainsKey(TokenKeys.ServiceApplicationIdKey)) { throw new ArgumentException("ApplicationId is missing. Cannot process the request."); } Logger.Technical().From <AdalTokenProvider>().System($"Creating an authentication context for the request.").Log(); clientId = settings.Values[TokenKeys.ClientIdKey]; serviceId = settings.Values[TokenKeys.ServiceApplicationIdKey]; authority = settings.Values[TokenKeys.AuthorityKey]; // Check the information. var messages = new ServiceModel.Messages(); if (String.IsNullOrWhiteSpace(clientId)) { messages.Add(new Message(ServiceModel.MessageCategory.Technical, ServiceModel.MessageType.Warning, $"{TokenKeys.ClientIdKey} is not defined in the configuration file.")); } else { Logger.Technical().From <AdalTokenProvider>().System($"{TokenKeys.ClientIdKey} = {clientId}.").Log(); } if (String.IsNullOrWhiteSpace(serviceId)) { messages.Add(new Message(ServiceModel.MessageCategory.Technical, ServiceModel.MessageType.Warning, $"No information from the application settings section about an entry: {TokenKeys.ServiceApplicationIdKey}.")); } if (String.IsNullOrWhiteSpace(authority)) { messages.Add(new Message(ServiceModel.MessageCategory.Technical, ServiceModel.MessageType.Warning, $"{TokenKeys.AuthorityKey} is not defined in the configuration file.")); } else { Logger.Technical().From <AdalTokenProvider>().System($"{TokenKeys.AuthorityKey} = {authority}.").Log(); } messages.LogAndThrowIfNecessary(typeof(AdalTokenProvider)); messages.Clear(); // The cache is per user on the device and Application. var authContext = CreateAuthenticationContext(authority, serviceId); Logger.Technical().From <AdalTokenProvider>().System("Authentication context is created.").Log(); return(authContext); }
public void SignOutUser(IKeyValueSettings settings) { RemoveClaimsCache(); if (Container.TryResolve(settings.Values[ProviderKey], out ITokenProvider provider)) { provider.SignOut(settings); } }
public async Task <TokenInfo> GetTokenAsync(IKeyValueSettings settings, object platformParameters) { if (null == settings) { throw new NullReferenceException("settings"); } return(await AuthenticationResultAsync(settings)); }
private Messages GetContext(IKeyValueSettings settings, out string clientId, out string authority, out string authenticationType, out string serviceApplicationId) { // Check the information. var messages = new Messages(); if (null == settings) { messages.Add(new Message(ServiceModel.MessageCategory.Technical, ServiceModel.MessageType.Error, "Settings parameter cannot be null.")); clientId = null; authority = null; authenticationType = null; serviceApplicationId = null; return(messages); } // Valdate arguments. if (!settings.Values.ContainsKey(TokenKeys.AuthorityKey)) { messages.Add(new Message(ServiceModel.MessageCategory.Technical, ServiceModel.MessageType.Error, "Authority is missing. Cannot process the request.")); } if (!settings.Values.ContainsKey(TokenKeys.ClientIdKey)) { messages.Add(new Message(ServiceModel.MessageCategory.Technical, ServiceModel.MessageType.Error, "ClientId is missing. Cannot process the request.")); } if (!settings.Values.ContainsKey(TokenKeys.ServiceApplicationIdKey)) { messages.Add(new Message(ServiceModel.MessageCategory.Technical, ServiceModel.MessageType.Error, "ApplicationId is missing. Cannot process the request.")); } if (!settings.Values.ContainsKey(TokenKeys.AuthenticationTypeKey)) { messages.Add(new Message(ServiceModel.MessageCategory.Technical, ServiceModel.MessageType.Error, "Authentication type key is missing. Cannot process the request.")); } Logger.Technical().From <CredentialTokenCacheTokenProvider>().System($"Creating an authentication context for the request.").Log(); clientId = settings.Values[TokenKeys.ClientIdKey]; serviceApplicationId = settings.Values[TokenKeys.ServiceApplicationIdKey]; authority = settings.Values[TokenKeys.AuthorityKey]; authenticationType = settings.Values[TokenKeys.AuthenticationTypeKey]; Logger.Technical().From <CredentialTokenCacheTokenProvider>().System($"ClientId = {clientId}.").Log(); Logger.Technical().From <CredentialTokenCacheTokenProvider>().System($"ServiceApplicationId = {serviceApplicationId}.").Log(); Logger.Technical().From <CredentialTokenCacheTokenProvider>().System($"Authority = {authority}.").Log(); Logger.Technical().From <CredentialTokenCacheTokenProvider>().System($"Authentication type = {authenticationType}.").Log(); return(messages); }
public string GetHeader(IKeyValueSettings settings) { ExtractFromSettings(settings, out var passwordStoreKey); var userkey = passwordStoreKey + "_upn"; var pwdkey = passwordStoreKey + "_pwd"; secureCache.TryGetValue <string>(userkey, out var upn); secureCache.TryGetValue <string>(pwdkey, out var pwd); return($"Basic {Convert.ToBase64String(Encoding.UTF8.GetBytes($"{upn.Trim()}:{pwd.Trim()}"))}"); }
/// <summary> /// Create a JwtHttpHandler. Use services.AddHttpHandler to add one and <see cref="ConfigurePrimaryHttpMessageHandler"/> if you need to /// customize the HttpHandler. /// </summary> /// <param name="settings">The settings needed for the <see cref="ITokenProvider"/>.</param> /// <param name="handler">The handler, can be a <see cref="DelegatingHandler"/></param> public JwtHttpHandler(IContainerResolve container, IKeyValueSettings settings, IPlatformParameters parameters = null) { _container = container ?? throw new ArgumentNullException(nameof(container)); _logger = container.Resolve <ILogger <JwtHttpHandler> >(); _settings = settings ?? throw new ArgumentNullException(nameof(settings)); _parameters = parameters; _settingsName = null; container.TryResolve <IApplicationContext>(out _applicationContext); }
public static X509Certificate2 ExtractCertificate(IKeyValueSettings settings) { var certificateName = settings.Values.ContainsKey("CertificateName") ? settings.Values["CertificateName"] : string.Empty; var findType = settings.Values.ContainsKey("FindType") ? settings.Values["FindType"] : string.Empty; var storeLocation = settings.Values.ContainsKey("StoreLocation") ? settings.Values["StoreLocation"] : string.Empty; var storeName = settings.Values.ContainsKey("StoreName") ? settings.Values["StoreName"] : string.Empty; if (null == certificateName) { throw new AppException("No CertificateName key found in the settings provided."); } else { var certificateInfo = new CertificateInfo { Name = certificateName }; if (Enum.TryParse(findType, out X509FindType x509FindType)) { certificateInfo.FindType = x509FindType; } if (Enum.TryParse(storeLocation, out StoreLocation storeLocation_)) { certificateInfo.Location = storeLocation_; } if (Enum.TryParse(storeName, out StoreName storeName_)) { certificateInfo.StoreName = storeName_; } try { var certificate = Certificate.FindCertificate( certificateInfo.Name, certificateInfo.FindType, certificateInfo.Location, certificateInfo.StoreName); return(certificate); } catch (KeyNotFoundException) { Logger.Technical.From(typeof(Certificate)).Error($"No certificate found with {certificateInfo.FindType} = in location = {certificateInfo.Location}.").Log(); throw; } } }
private UserProfile BuildProfile(IKeyValueSettings settings, Messages messages) { UserProfile profile = UserProfile.Empty; if (Container.TryResolve(out IClaimProfileFiller profileFiller)) { profile = profileFiller.GetProfile(Identity); messages.Add(new Message(ServiceModel.MessageCategory.Technical, ServiceModel.MessageType.Information, $"Fill the profile information to the principal.")); } else { messages.Add(new Message(ServiceModel.MessageCategory.Technical, ServiceModel.MessageType.Warning, $"No class was found to fill the principal profile.")); } return(profile); }
private async Task <TokenInfo> AuthenticationResultAsync(IKeyValueSettings settings, IPlatformParameters platformParameters) { var authContext = GetContext(settings, out string serviceId, out string clientId, out string authority); var redirectUri = new Uri(settings.Values[TokenKeys.RedirectUrl]); Logger.Technical().From <AdalTokenProvider>().System($"{TokenKeys.RedirectUrl} = {redirectUri}.").Log(); Logger.Technical().From <AdalTokenProvider>().System("Acquire a token.").Log(); // Start Vpn if needed. Network.Handler.OnCalling?.Invoke(new Uri(authority)); AuthenticationResult result = null; // Check if we have an AuthenticationResult cached and still valid. if (_resultCache.ContainsKey(clientId)) { result = _resultCache[clientId]; // Is valid with a security margin of 1 minute. if (null == result || result.ExpiresOn.LocalDateTime.AddMinutes(-1) < DateTime.Now) { Logger.Technical().From <AdalTokenProvider>().System($"Token cached for clientId = {clientId} is expired. Is removed from the cache.").Log(); _resultCache.Remove(clientId); result = null; } } if (null == result) { result = await authContext.AcquireTokenAsync(serviceId, clientId, redirectUri, platformParameters); _resultCache.Add(clientId, result); Logger.Technical().From <AdalTokenProvider>().System($"Add the token in the cache for clientId = {clientId}.").Log(); } if (null != result) { // Dump no sensitive information. Logger.Technical().From <AdalTokenProvider>().System($"Token information for user {result.UserInfo.DisplayableId}.").Log(); Logger.Technical().From <AdalTokenProvider>().System($"Token expiration = {result.ExpiresOn.ToString("dd-MM-yyyy HH:mm:ss")}.").Log(); return(result.ToTokenInfo()); } return(null); }
/// <summary> /// Based on the token provider Id, the method will call the token provider and build a claimPrincipal! /// The provider id is the string used by the Composition library to register the type and not the provider Id used by the token provider itself (Microsoft, google, or other...). /// Today only the connected scenario is covered! /// </summary> /// <param name="IAppSettings">The settings needed to authenticate the user.</param> private Authorization BuildAuthorization(IKeyValueSettings settings, Messages messages) { var authorization = new Authorization(); // We need to fill the authorization and user profile from the provider! if (Container.TryResolve(out IClaimAuthorizationFiller claimAuthorizationFiller)) { authorization = claimAuthorizationFiller.GetAuthorization(Identity); messages.Add(new Message(ServiceModel.MessageCategory.Technical, ServiceModel.MessageType.Information, $"Fill the authorization information to the principal.")); } else { messages.Add(new Message(ServiceModel.MessageCategory.Technical, ServiceModel.MessageType.Warning, $"No class waw found to fill the authorization to the principal.")); } return(authorization); }
public async Task <TokenInfo> GetTokenAsync(IKeyValueSettings settings, object platformParameters) { if (!_settings.ContainsKey(settings.GetHashCode())) { ValidateSettings(settings); } if (_tokenInfos.TryGetValue(settings.Values["OboEndpointUrl"], out var tokenInfo)) { if (tokenInfo.ExpiresOnUtc > DateTime.UtcNow.AddMinutes(-1)) { return(tokenInfo); } } // tokenInfo is expired or not yet available! var oauth = settings.Values.ContainsKey("OAuthSettingsReader") ? settings.Values["OAuthSettingsReader"] : "OAuth"; var httpClient = _httpClientFactory.CreateClient(oauth); try { var response = await httpClient.GetAsync(settings.Values["OboEndpointUrl"]); if (response.IsSuccessStatusCode) { var accessToken = await response.Content.ReadAsStringAsync(); // validate that is a beare token! var jwtToken = new JwtSecurityToken(accessToken); tokenInfo = new TokenInfo("Bearer", accessToken, String.Empty, jwtToken.ValidTo); _tokenInfos[settings.Values["OboEndpointUrl"]] = tokenInfo; return(tokenInfo); } } catch (Exception ex) { _logger.Technical().Exception(ex).Log(); throw ex; } throw new ApplicationException("No token could be retrieve"); }
private async Task <TokenInfo> GetOpenIdTokenAsync(IKeyValueSettings settings, ClaimsIdentity identity) { // Check the information. var messages = new Messages(); if (null == settings) { throw new AppException(new Message(ServiceModel.MessageCategory.Technical, MessageType.Error, "Settings parameter cannot be null.")); } var settingsProviderName = settings.Values.ContainsKey("OpenIdSettingsReader") ? settings.Values["OpenIdSettingsReader"] : "OpenID"; if (Container.TryResolve <IKeyValueSettings>(settingsProviderName, out var openIdSettings)) { if (!openIdSettings.Values.ContainsKey(TokenKeys.ProviderIdKey)) { messages.Add(new Message(ServiceModel.MessageCategory.Technical, MessageType.Error, "No Provider defined in OpenId Settings.")); } else { var tokenProviderName = openIdSettings.Values[TokenKeys.ProviderIdKey]; if (Container.TryResolve <ITokenProvider>(tokenProviderName, out var openIdTokenProvider)) { return(await openIdTokenProvider.GetTokenAsync(openIdSettings, identity)); } else { messages.Add(new Message(ServiceModel.MessageCategory.Technical, MessageType.Error, $"Cannot resolve a token provider with name {tokenProviderName}.")); } } } else { messages.Add(new Message(ServiceModel.MessageCategory.Technical, MessageType.Error, $"Cannot resolve the KeyValues settings with name {settingsProviderName}.")); } messages.LogAndThrowIfNecessary(this); messages.Clear(); return(null); }
private static (string instance, string tenantId) ExtractFromAuthority(IKeyValueSettings settings) { var authority = new Uri(settings.Values[TokenKeys.AuthorityKey]); var instance = authority.GetLeftPart(UriPartial.Authority); var tenantId = authority.AbsolutePath.Trim(new char[] { '/', ' ' }); if (settings.Values.ContainsKey(TokenKeys.TenantIdKey)) { tenantId = settings.Values[TokenKeys.TenantIdKey]; } if (settings.Values.ContainsKey(TokenKeys.InstanceKey)) { instance = settings.Values[TokenKeys.InstanceKey]; } return(instance, tenantId); }
private async Task <AuthenticationResult> AuthenticationResultAsync(IKeyValueSettings settings) { // Have a bootstrap token? var identity = _applicationContext.Principal.Identity as ClaimsIdentity; var accessToken = identity?.BootstrapContext?.ToString() ?? (await GetOpenIdTokenAsync(settings, identity)).AccessToken; var authContext = GetOAuthContext(settings, identity, out string serviceApplicationId, out ClientCredential credential); if (null == credential) { throw new AppException("No client credential was created. This is needed for an on behalf of scenario."); } Logger.Technical().From(typeof(AdalOboTokenProvider)).Debug("Acquire a token on behal of.").Log(); return(await authContext.AcquireTokenAsync(serviceApplicationId, credential, new UserAssertion(accessToken))); }
public async Task <TokenInfo> GetTokenAsync(IKeyValueSettings settings, object platformParameters) { if (null == settings) { throw new ArgumentNullException(nameof(settings)); } var token = await GetToken(); if (null != token) { return(token); } var authority = settings.Values.ContainsKey(TokenKeys.AuthorityKey) ? settings.Values[TokenKeys.AuthorityKey] : throw new ArgumentNullException(TokenKeys.AuthorityKey); var redirectUrl = settings.Values.ContainsKey(TokenKeys.RedirectUrl) ? settings.Values[TokenKeys.RedirectUrl] : throw new ArgumentNullException(TokenKeys.RedirectUrl); await WindowInterop.OpenWindowAsync(_jsRuntime, _localStorage, UriHelper.Encode(new Uri($"{authority}?redirectUrl={redirectUrl}"))); return(await GetToken() ?? throw new Exception("No token found!")); }
public async Task <TokenInfo> GetTokenAsync(IKeyValueSettings settings, CredentialsResult credential) { var messages = GetContext(settings, out string clientId, out string authority, out string serviceApplicationId); if (String.IsNullOrWhiteSpace(credential.Upn)) { messages.Add(new Message(ServiceModel.MessageCategory.Technical, ServiceModel.MessageType.Warning, "No Username is provided.")); } if (String.IsNullOrWhiteSpace(credential.Password)) { messages.Add(new Message(ServiceModel.MessageCategory.Technical, ServiceModel.MessageType.Warning, "No password is provided.")); } messages.LogAndThrowIfNecessary(this); messages.Clear(); // no cache, do a direct call on every calls. Logger.Technical().From <CredentialTokenProvider>().System($"Call STS: {authority} for user: {credential.Upn}").Log(); return(await GetTokenInfoAsync(serviceApplicationId, clientId, authority, credential.Upn, credential.Password)); }
public async Task <AppPrincipal> CreatePrincipal(IKeyValueSettings settings, Messages messages, object parameter = null) { Identity = new ClaimsIdentity("OAuth2Bearer", System.Security.Claims.ClaimTypes.Upn, ClaimsIdentity.DefaultRoleClaimType); if (null == settings) { throw new ArgumentNullException(nameof(settings)); } if (null == messages) { throw new ArgumentNullException(nameof(messages)); } /// when we have no internet connectivity may be we have claims in cache. if (NetworkStatus.None == NetworkInformation.Status) { // In a scenario where the claims cached are always for one user like a UI, the identity is not used => so retrieving the claims in the cache is possible! var identity = new ClaimsIdentity(); cachedClaims = GetClaimsFromCache(identity); Identity.AddClaims(cachedClaims.Select(p => new Claim(p.ClaimType, p.Value))); messages.Add(new Message(ServiceModel.MessageCategory.Technical, ServiceModel.MessageType.Information, "Create the principal from the cache due to no network connectivity.")); } else { await BuildTheIdentity(settings, messages, parameter); } var authorization = BuildAuthorization(settings, messages); var user = BuildProfile(settings, messages); var principal = new AppPrincipal(authorization, Identity, null) { Profile = user }; ApplicationContext.SetPrincipal(principal); return(principal); }
private void GetSettings(IKeyValueSettings settings, out string serviceId, out string authority, out string passwordStoreKey) { // Validate arguments. if (!settings.Values.ContainsKey(TokenKeys.AuthorityKey)) { throw new ArgumentException("Authority is missing. Cannot process the request."); } if (!settings.Values.ContainsKey(TokenKeys.ServiceApplicationIdKey)) { throw new ArgumentException("ApplicationId is missing. Cannot process the request."); } serviceId = settings.Values[TokenKeys.ServiceApplicationIdKey]; authority = settings.Values[TokenKeys.AuthorityKey]; // Check the information. var messages = new Arc4u.ServiceModel.Messages(); if (String.IsNullOrWhiteSpace(serviceId)) { messages.Add(new Message(ServiceModel.MessageCategory.Technical, ServiceModel.MessageType.Warning, $"No information from the application settings section about an entry: {TokenKeys.ServiceApplicationIdKey}.")); } if (String.IsNullOrWhiteSpace(authority)) { messages.Add(new Message(ServiceModel.MessageCategory.Technical, ServiceModel.MessageType.Warning, $"{TokenKeys.AuthorityKey} is not defined in the configuration file.")); } messages.LogAndThrowIfNecessary(this); messages.Clear(); passwordStoreKey = "secret"; if (settings.Values.ContainsKey(TokenKeys.PasswordStoreKey)) { passwordStoreKey = String.IsNullOrWhiteSpace(settings.Values[TokenKeys.PasswordStoreKey]) ? passwordStoreKey : settings.Values[TokenKeys.PasswordStoreKey]; } }
/// <summary> /// Request a token in a backend scenario. /// As this is a backend token provider, platformParameter is not used as ADAL expect it in a UI app. /// </summary> /// <param name="settings">The settings to retrieve the token.</param> /// <param name="platformParameters">null</param> /// <returns></returns> public async Task <TokenInfo> GetTokenAsync(IKeyValueSettings settings, object platformParameters) { // give the identity to platform parameter when used in the BE which is the purpose of this ITokenProvide. identity = platformParameters as ClaimsIdentity; if (null == identity && Container.TryResolve <IApplicationContext>(out var applicationContext)) { identity = applicationContext.Principal?.Identity as ClaimsIdentity; } if (null != identity?.BootstrapContext) { var tokenInfo = TokenIsValid(settings, identity.BootstrapContext.ToString()); if (null != tokenInfo) { return(tokenInfo); } } var result = await AuthenticationResultAsync(settings); return(result.ToTokenInfo()); }
public void SignOut(IKeyValueSettings settings) { _localStorage.RemoveItemAsync("token").AsTask().Wait(); }
public static IApplicationBuilder UseClientSecretAuthentication(this IApplicationBuilder app, IContainerResolve container, IKeyValueSettings settings, string settingsSectionName) { if (null == app) { throw new ArgumentNullException(nameof(app)); } if (null == container) { throw new ArgumentNullException(nameof(container)); } if (null == settings) { throw new ArgumentNullException(nameof(settings)); } var option = new ClientSecretAuthenticationOption(settings); container.Resolve <IConfiguration>().Bind(settingsSectionName, option); return(app.UseMiddleware <ClientSecretAuthenticationMiddleware>(container, option)); }