private async Task RemoveClientRelationsAsync(int clientId) { //Remove old claims var clientClaims = await ClientClaims.Where(x => x.Client.Id == clientId).ToListAsync(); ClientClaims.RemoveRange(clientClaims); //Remove old allowed scopes var clientScopes = await ClientScopes.Where(x => x.Client.Id == clientId).ToListAsync(); ClientScopes.RemoveRange(clientScopes); //Remove old grant types var clientGrantTypes = await ClientGrantTypes.Where(x => x.Client.Id == clientId).ToListAsync(); ClientGrantTypes.RemoveRange(clientGrantTypes); //Remove old redirect uri var clientRedirectUris = await ClientRedirectUris.Where(x => x.Client.Id == clientId).ToListAsync(); ClientRedirectUris.RemoveRange(clientRedirectUris); //Remove old client cors var clientCorsOrigins = await ClientCorsOrigins.Where(x => x.Client.Id == clientId).ToListAsync(); ClientCorsOrigins.RemoveRange(clientCorsOrigins); //Remove old client id restrictions var clientIdPRestrictions = await ClientIdPRestrictions.Where(x => x.Client.Id == clientId).ToListAsync(); ClientIdPRestrictions.RemoveRange(clientIdPRestrictions); //Remove old client post logout redirect var clientPostLogoutRedirectUris = await ClientPostLogoutRedirectUris.Where(x => x.Client.Id == clientId).ToListAsync(); ClientPostLogoutRedirectUris.RemoveRange(clientPostLogoutRedirectUris); }
public static Claim MapClaim(this ClientClaims clientClaims) { return(new Claim(type: clientClaims.Type, value: clientClaims.Value)); }
private async Task <string> AuthenticateAsync(string server, NetworkCredential credential) { using (var client = GetHttpClient(false)) { var host = $"https://{server}:{ClientConstants.AuthorizationServerPort}/connect/token"; Log.Information($"Authenticating at {host}"); var parameters = new Dictionary <string, string>() { { ClientConstants.DeviceIdClaim, _idService.GetDeviceId() }, { ClientConstants.VersionClaim, ClientVersionHelper.GetVersion() } }; if (_domain != null) { parameters.Add(ClientConstants.DomainClaim, _domain); } TokenResponse tokenResponse = null; if (credential != null) { UserName = credential.UserName; tokenResponse = await client.RequestPasswordTokenAsync(new PasswordTokenRequest { Address = host, ClientId = _environment.GetClientId(), ClientSecret = "xtreamer.id", UserName = _appResources.AppData.UserNamePrefix + credential.UserName, Password = credential.Password, Scope = ClientConstants.ConnectionServerApi, Parameters = parameters }); } else { UserName = null; tokenResponse = await client.RequestTokenAsync(new TokenRequest { Address = host, ClientId = _environment.GetClientId(), ClientSecret = "xtreamer.id", GrantType = ClientConstants.AnonymousGrandType, Parameters = parameters }); } if (tokenResponse.IsError) { if (tokenResponse.ErrorType == ResponseErrorType.Exception && tokenResponse.Exception is HttpRequestException && tokenResponse.Exception.InnerException is SocketException) { throw new ConnectionServiceException("Connection to the service failed. Please check your internet connection.", tokenResponse.Exception); } else if (credential != null && tokenResponse.ErrorType == ResponseErrorType.Protocol && tokenResponse.HttpResponse?.StatusCode == HttpStatusCode.BadRequest && tokenResponse.ErrorDescription == "invalid_username_or_password") { throw new WrongUserNamePasswordException(); } else { throw new ConnectionServiceException($"Unknown error occured ({tokenResponse.Error}). Please contact service administrator.", tokenResponse.Exception); } } var jwt = tokenResponse.AccessToken; var handler = new JwtSecurityTokenHandler(); var token = handler.ReadJwtToken(jwt); Claims = new ClientClaims(token.Claims); if (Claims.IsDebug) { _logService.EnableDebug(); } return(tokenResponse.AccessToken); } }
/// <summary> /// Initializes a new instance of the <see cref="B2COpenidConnect"/> class. /// </summary> /// <param name="name">Name of the policy</param> /// <param name="tenant">B2C tenant</param> /// <param name="policy">B2C policy</param> /// <param name="clientId">Client id to connect to B2C App</param> /// <param name="clientSecret">Client secret to autneticate to B2C App</param> /// <param name="metadataUri">B2C metadata endpoint</param> /// <param name="redirectUri">Redirect Uri from B2C</param> /// <param name="addClientClaimsToPolicy">Defines policy and claims to add to this policy </param> public B2COpenidConnect(string name, string tenant, string policy, string clientId, string clientSecret, string metadataUri, string redirectUri, string addClientClaimsToPolicy = null) { string caption = string.Format(name, policy); if (!string.IsNullOrWhiteSpace(addClientClaimsToPolicy)) { this.clientClaims = JsonConvert.DeserializeObject <ClientClaims>(addClientClaimsToPolicy); } options = new OpenIdConnectAuthenticationOptions { Notifications = new OpenIdConnectAuthenticationNotifications() { AuthenticationFailed = context => { context.HandleResponse(); if (context.ProtocolMessage.Error == "access_denied" && context.ProtocolMessage.ErrorDescription.StartsWith("AADB2C90118")) { context.Response.Redirect("/Account/ResetPassword"); } else if (context.ProtocolMessage.Error == "access_denied" && context.ProtocolMessage.ErrorDescription.StartsWith("AADB2C90091")) { context.Response.Redirect("/Home/Index"); } else { context.Response.Redirect("/Error/Index?error=" + context.ProtocolMessage.Error + "&error_description=" + context.ProtocolMessage.ErrorDescription); } return(Task.FromResult(0)); }, RedirectToIdentityProvider = async context => { // The open id class can't deal with authorization uri which already contain '?' // We need this work around to cover it in the request var parts = context.ProtocolMessage.IssuerAddress.Split(new[] { '?' }); context.ProtocolMessage.IssuerAddress = parts[0]; if (parts.Length > 1) { context.ProtocolMessage.Parameters.Add("p", policy); } if (context.ProtocolMessage.RequestType != OpenIdConnectRequestType.LogoutRequest) { // Check to add client auth to request if (this.clientClaims != null && string.Compare(policy, clientClaims.Policy, true) == 0) { List <Claim> claims = new List <Claim> { new Claim(clientClaims.ClaimType, clientClaims.ClaimValue), new Claim("state", context.ProtocolMessage.Parameters["state"]) }; OpenIdConnectConfiguration conf = await this.GetConfiguration(context.OwinContext, context.Options); string jwt = ClientAuthToken(claims, conf.Issuer, redirectUri, clientSecret); // Add client auth assertion context.ProtocolMessage.Parameters.Add("client_assertion_type", "urn:ietf:params:oauth:client-assertion-type:jwt-bearer"); context.ProtocolMessage.Parameters.Add("client_assertion", jwt); } } await Task.FromResult(0); }, SecurityTokenValidated = context => { Console.WriteLine("B2C returned JWT : '{0}'", context.ProtocolMessage.IdToken); return(Task.FromResult(0)); } }, TokenValidationParameters = new TokenValidationParameters { SaveSigninToken = true }, UseTokenLifetime = true, Caption = caption, AuthenticationType = policy, Scope = "openid", ResponseType = "id_token", ClientId = clientId, MetadataAddress = string.Format(metadataUri, tenant, policy), ClientSecret = clientSecret, RedirectUri = redirectUri, PostLogoutRedirectUri = redirectUri }; }