public async static Task <LoginResult> RefreshTokenAsync(OidcSettings settings, string refreshToken) { var config = await LoadOpenIdConnectConfigurationAsync(settings); var tokenClient = new TokenClient( config.TokenEndpoint, settings.ClientId, settings.ClientSecret); var provider = JwkNetExtensions.CreateProvider(); var jwk = provider.ToJsonWebKey(); var tokenResponse = await tokenClient.RequestRefreshTokenPopAsync( refreshToken : refreshToken, algorithm : jwk.Alg, key : jwk.ToJwkString()); if (tokenResponse.IsError) { return(new LoginResult { ErrorMessage = tokenResponse.Error }); } else { return(new LoginResult { Success = true, AccessToken = tokenResponse.AccessToken, RefreshToken = tokenResponse.RefreshToken, IdentityToken = tokenResponse.IdentityToken, AccessTokenExpiration = DateTime.Now.AddSeconds(tokenResponse.ExpiresIn) }); } }
public AuthRequestBuilder(OidcSettings settings, IServiceProvider serviceProvider, IOidcLogger <AuthRequestBuilder> logger) { Settings = settings; ServiceProvider = serviceProvider; Metadata = serviceProvider.GetRequiredService <IMetadataService>(); Logger = logger; }
public Store(OidcSettings settings, IMetadataService metadata, IStorage storage, IOidcLogger <Store> logger) { Settings = settings; Metadata = metadata; Storage = storage; Logger = logger; }
public OidcSettingsValidationResult Validate(OidcSettings settings) { var result = new OidcSettingsValidationResult(); if (settings == null) { result.AddError("Missing Oidc settings"); return(result); } if (settings.Issuer == null) { result.AddError("Missing issuer"); } if (settings.ClientId.IsEmpty()) { result.AddError("Missing client id"); } if (settings.ResponseType.IsEmpty()) { result.AddError("Missing response type"); } if (settings.Scope.IsEmpty()) { result.AddError("Missing scope"); } if (settings.StoragePrefix.IsEmpty()) { result.AddError("Missing storage prefix"); } return(result); }
public Metadata(OidcSettings settings) { Issuer = settings.Issuer; MetadataEndpoint = settings.MetadataEndpoint; Endpoints = settings.Endpoints ?? new OpenidEndpoints(); Jwks = settings.Jwks; }
public static IServiceCollection AddOidc(this IServiceCollection services, OidcSettings settings) { new OidcSettingsValidator().EnsureValidSettings(services, settings); services.AddAuthorizationCore(); services.TryAddScoped(settings); services.TryAddScoped <Metadata>(); services.TryAddScoped <Interop>(); //TODO: ensure that IJSRuntime is singleton too services.TryAddScoped <AuthenticationStateProvider, AuthStateProvider>(); services.TryAddScoped <OidcHttpClient>(); services.TryAddScoped <IUserManager, UserManager>(); services.TryAddTransient(typeof(IOidcLogger <>), typeof(OidcLogger <>)); services.TryAddTransient <IMetadataService, MetadataService>(); services.TryAddTransient <ISignatureValidatorFactory, SignatureValidatorFactory>(); services.TryAddTransient <IJwtValidator, JwtValidator>(); services.TryAddTransient <ITokenParser, TokenParser>(); services.TryAddTransient <ITokenRevocationClient, TokenRevocationClient>(); services.TryAddTransient <IAuthRequestBuilder, AuthRequestBuilder>(); services.TryAddTransient <IAuthResponseParser, AuthResponseParser>(); services.TryAddTransient <IOidcClient, OidcClient>(); services.TryAddTransient <ISessionMonitor, SessionMonitor>(); services.TryAddTransient <ILogoutRequestBuilder, LogoutRequestBuilder>(); services.TryAddTransient <ILogoutResponseParser, LogoutResponseParser>(); services.TryAddTransient <ILogoutClient, LogoutClient>(); services.TryAddTransientStorage(settings); return(services); }
public BrowserStorage(OidcSettings settings, Interop interop, IOidcLogger <BrowserStorage> logger) { StorageType = settings.StorageType.IsLocal() ? "localStorage" : "sessionStorage"; KeyPrefix = settings.StoragePrefix; Interop = interop; Logger = logger; }
public SessionMonitor(OidcSettings settings, Interop interop, IMetadataService metadata, IOidcLogger <SessionMonitor> logger) { Settings = settings; Interop = interop; Metadata = metadata; Logger = logger; Timer = new Timer(TimerCallback, null, Timeout.Infinite, Timeout.Infinite); }
public async Task LoginAsync(OidcSettings settings) { _settings = settings; if (_config == null) { await LoadOpenIdConnectConfigurationAsync(); } this.Visibility = Visibility.Visible; webView.Navigate(CreateUrl()); }
private static void TryAddTransientStorage(this IServiceCollection services, OidcSettings settings) { services.TryAddTransient <IStore, Store>(); if (settings.StorageType.IsMemory()) { services.TryAddTransient <IStorage, MemoryStorage>(); } else { services.TryAddTransient <IStorage, BrowserStorage>(); } }
private async void LoginButton_Click(object sender, RoutedEventArgs e) { var settings = new OidcSettings { Authority = "https://localhost:44333/core", ClientId = "wpf.hybrid", ClientSecret = "secret", RedirectUri = "http://localhost/wpf.hybrid", Scope = "openid profile write", LoadUserProfile = true }; await _login.LoginAsync(settings); }
private static string CreateUrl(OidcSettings settings, OpenIdConnectConfiguration config, string nonce, string verifier) { var challenge = verifier.ToCodeChallenge(); var request = new AuthorizeRequest(config.AuthorizationEndpoint); return(request.CreateAuthorizeUrl( clientId: settings.ClientId, responseType: "code id_token", scope: settings.Scope, redirectUri: settings.RedirectUri, nonce: nonce, responseMode: OidcConstants.ResponseModes.FormPost, acrValues: settings.AcrValues, codeChallenge: settings.UsePkce ? challenge : null, codeChallengeMethod: settings.UsePkce ? OidcConstants.CodeChallengeMethods.Sha256 : null)); }
public void EnsureValidSettings(IServiceCollection services, OidcSettings settings) { if (services == null) { throw new ArgumentNullException(nameof(services)); } var validationResult = Validate(settings); if (!validationResult.HasErrors) { return; } validationResult.PrintErrors(); throw new OidcException("Oidc configuration aborted", true); }
public UserManager( OidcSettings settings, IOidcClient oidcClient, ILogoutClient logoutClient, ISessionMonitor monitor, IUserManagerHelper helper, IOidcLogger <UserManager> logger ) { Settings = settings; OidcClient = oidcClient; LogoutClient = logoutClient; Monitor = monitor; Helper = helper; Logger = logger; Version = GetType().InformationalVersion(); if (Settings.MonitorSession) { Monitor.OnSessionChanged += SessionChanged; } }
public MainWindow() { InitializeComponent(); _settings = new OidcSettings { Authority = "https://localhost:44333/core", ClientId = "wpf.hybrid.pop", ClientSecret = "secret", RedirectUri = "http://localhost/wpf.hybrid.pop", Scope = "openid profile write offline_access", LoadUserProfile = true }; _login = new LoginWebView(_settings.RedirectUri); _login.Done += _login_Done; Loaded += MainWindow_Loaded; //IdentityTextBox.Visibility = Visibility.Hidden; }
public OidcSettingsValidationResult Validate(OidcSettings settings) { var result = new OidcSettingsValidationResult(); if (settings == null) { result.AddError("Missing Oidc settings"); return(result); } if (settings.Issuer == null) { result.AddError("Missing issuer"); } if (settings.ClientId.IsEmpty()) { result.AddError("Missing client id"); } if (settings.ResponseType.IsEmpty()) { result.AddError("Missing response type"); } if (settings.Scope.IsEmpty()) { result.AddError("Missing scope"); } if (settings.StorageType.IsMemory() && settings.InteractionType.IsRedirect()) { result.AddError("Interaction type cannot be redirect using memory storage"); } if (!settings.StorageType.IsMemory() && settings.StoragePrefix.IsEmpty()) { result.AddError("Missing storage prefix"); } return(result); }
public static IServiceCollection AddOidc(this IServiceCollection services, Uri issuer, Action <OidcSettings, Uri> configure) { services.AddAuthorizationCore(); services.TryAddScoped <Metadata>(); services.TryAddScoped <Interop>(); //TODO: ensure that IJSRuntime is singleton too services.TryAddScoped <AuthenticationStateProvider, AuthStateProvider>(); services.TryAddScoped <OidcHttpClient>(); services.TryAddScoped <IUserManager, UserManager>(); services.TryAddScoped(typeof(IOidcLogger <>), typeof(OidcLogger <>)); // remove this when this will be published (https://github.com/aspnet/AspNetCore/pull/12928) services.TryAddScoped <IMetadataService, MetadataService>(); services.TryAddScoped <ISignatureValidatorFactory, SignatureValidatorFactory>(); services.TryAddScoped <IJwtValidator, JwtValidator>(); services.TryAddScoped <ITokenParser, TokenParser>(); services.TryAddScoped <ITokenRevocationClient, TokenRevocationClient>(); services.TryAddScoped <IAuthRequestBuilder, AuthRequestBuilder>(); services.TryAddScoped <IAuthResponseParser, AuthResponseParser>(); services.TryAddScoped <IUserManagerHelper, UserManagerHelper>(); services.TryAddScoped <IOidcClient, OidcClient>(); services.TryAddScoped <ISessionMonitor, SessionMonitor>(); services.TryAddScoped <ILogoutRequestBuilder, LogoutRequestBuilder>(); services.TryAddScoped <ILogoutResponseParser, LogoutResponseParser>(); services.TryAddScoped <ILogoutClient, LogoutClient>(); services.TryAddScoped <IStorage, BrowserStorage>(); services.TryAddScoped <IStore, Store>(); services.TryAddScoped(b => { var navigationManager = b.GetRequiredService <NavigationManager>(); var settings = new OidcSettings(issuer); settings.UseDefaultActions(); configure?.Invoke(settings, new Uri(navigationManager.BaseUri)); new OidcSettingsValidator().EnsureValidSettings(services, settings); return(settings); }); return(services); }
private static List <Claim> ValidateIdentityToken(string identityToken, OidcSettings settings, OpenIdConnectConfiguration config) { var tokens = new List <X509SecurityToken>( from key in config.JsonWebKeySet.Keys select new X509SecurityToken(new X509Certificate2(Convert.FromBase64String(key.X5c.First())))); var parameter = new TokenValidationParameters { ValidIssuer = config.Issuer, ValidAudience = settings.ClientId, IssuerSigningTokens = tokens }; JwtSecurityTokenHandler.InboundClaimTypeMap.Clear(); try { var handler = new JwtSecurityTokenHandler(); return(handler.ValidateToken(identityToken, parameter, out var token).Claims.ToList()); } catch { return(null); } }
public async static Task <LoginResult> AuthenticateAsync(OidcSettings settings) { var taskCompletion = new TaskCompletionSource <LoginResult>(); var nonce = CryptoRandom.CreateUniqueId(32); var verifier = CryptoRandom.CreateUniqueId(32); var config = await LoadOpenIdConnectConfigurationAsync(settings); var login = new LoginWebView(settings.RedirectUri); login.Completed += async(o, e) => { if (e == null) { taskCompletion.TrySetCanceled(); } else { try { var result = await ValidateResponseAsync(e, settings, config, nonce, verifier); taskCompletion.SetResult(result); } catch (Exception ex) { taskCompletion.SetException(ex); } } }; login.WindowStartupLocation = WindowStartupLocation.CenterScreen; login.ShowDialog(CreateUrl(settings, config, nonce, verifier)); return(await taskCompletion.Task); }
public static FlowExtensions UseDemoFlow(this OidcSettings settings) { return(new FlowExtensions(settings)); }
public static OidcSettings CodeWithShortLivedToken(OidcSettings settings) { settings.ClientId = "spa.short"; settings.ResponseType = "code"; return(settings); }
public OidcLogger(OidcSettings settings, ILoggerFactory loggerFactory) { Settings = settings; RealLogger = loggerFactory.CreateLogger <T>(); }
public FlowExtensions(OidcSettings settings) { Settings = settings; }
public TokenParser(OidcSettings settings, IJwtValidator validator, ILogger <TokenParser> logger) { Settings = settings; Validator = validator; Logger = logger; }
public AuthResponseParser(OidcSettings settings, ITokenParser tokenParser, IOidcLogger <AuthResponseParser> logger) { Settings = settings; TokenParser = tokenParser; Logger = logger; }
public static OidcSettings Code(OidcSettings settings) { settings.ClientId = "spa"; settings.ResponseType = "code"; return(settings); }
public AuthRequestBuilder(OidcSettings settings, IMetadataService metadata, IOidcLogger <AuthRequestBuilder> logger) { Settings = settings; Metadata = metadata; Logger = logger; }
public static OidcSettings ImplicitReference(OidcSettings settings) { settings.ClientId = "implicit.reference"; settings.ResponseType = "id_token token"; return(settings); }
public static OidcSettings ImplicitWithShortLivedToken(OidcSettings settings) { settings.ClientId = "implicit.shortlived"; settings.ResponseType = "id_token token"; return(settings); }
private static ClaimsPrincipal CreatePrincipal(List <Claim> tokenClaims, List <Claim> profileClaims, OidcSettings settings) { List <Claim> filteredClaims = new List <Claim>(tokenClaims); if (settings.FilterClaims) { filteredClaims = tokenClaims.Where(c => !settings.FilterClaimTypes.Contains(c.Type)).ToList(); } var allClaims = new List <Claim>(); allClaims.AddRange(filteredClaims); allClaims.AddRange(profileClaims); var id = new ClaimsIdentity(allClaims.Distinct(new ClaimComparer()), "OIDC"); return(new ClaimsPrincipal(id)); }