Exemple #1
0
        public async Task <bool> DeleteAsync(Core.Models.Client client)
        {
            using (var transaction = await _context.Database.BeginTransactionAsync().ConfigureAwait(false))
            {
                try
                {
                    var result = await _context.Clients.FirstOrDefaultAsync(c => c.ClientId == client.ClientId).ConfigureAwait(false);

                    if (result == null)
                    {
                        return(false);
                    }

                    _context.Clients.Remove(result);
                    await _context.SaveChangesAsync().ConfigureAwait(false);

                    transaction.Commit();
                    return(true);
                }
                catch (Exception ex)
                {
                    _managerEventSource.Failure(ex);
                    transaction.Rollback();
                    return(false);
                }
            }
        }
        public async Task <ActionResult> Index(string code)
        {
            var request           = _dataProtector.Unprotect <AuthorizationRequest>(code);
            var client            = new Core.Models.Client();
            var authenticatedUser = await this.GetAuthenticatedUser(Constants.CookieName);

            var actionResult = await _consentActions.DisplayConsent(request.ToParameter(),
                                                                    authenticatedUser);

            var result = this.CreateRedirectionFromActionResult(actionResult.ActionResult, request);

            if (result != null)
            {
                return(result);
            }

            await TranslateConsentScreen(request.UiLocales);

            var viewModel = new ConsentViewModel
            {
                ClientDisplayName        = client.ClientName,
                AllowedScopeDescriptions = actionResult.Scopes == null ? new List <string>() : actionResult.Scopes.Select(s => s.Description).ToList(),
                AllowedIndividualClaims  = actionResult.AllowedClaims == null ? new List <string>() : actionResult.AllowedClaims,
                LogoUri   = client.LogoUri,
                PolicyUri = client.PolicyUri,
                TosUri    = client.TosUri,
                Code      = code
            };

            return(View(viewModel));
        }
        public async Task <bool> DeleteAsync(Core.Models.Client client)
        {
            using (var transaction = _context.Database.BeginTransaction())
            {
                try
                {
                    var connectedClient = await _context.Clients
                                          .Include(c => c.ClientScopes)
                                          .Include(c => c.JsonWebKeys)
                                          .Include(c => c.ClientSecrets)
                                          .FirstOrDefaultAsync(c => c.ClientId == client.ClientId)
                                          .ConfigureAwait(false);

                    if (connectedClient == null)
                    {
                        return(false);
                    }

                    _context.Clients.Remove(connectedClient);
                    await _context.SaveChangesAsync().ConfigureAwait(false);

                    transaction.Commit();
                }
                catch (Exception ex)
                {
                    _managerEventSource.Failure(ex);
                    transaction.Rollback();
                    return(false);
                }
            }

            return(true);
        }
        public static Core.Models.Client ToDomain(this IdentityServer4.EntityFramework.Entities.Client client)
        {
            var result = new Core.Models.Client
            {
                ClientId                    = client.ClientId,
                ClientSecret                = client.ClientSecrets == null || !client.ClientSecrets.Any() ? string.Empty : client.ClientSecrets.First().Value,
                LogoUri                     = client.LogoUri,
                ClientName                  = client.ClientName,
                ClientUri                   = client.ClientUri,
                IdTokenSignedResponseAlg    = "RS256",
                IdTokenEncryptedResponseAlg = null,
                IdTokenEncryptedResponseEnc = null,
                TokenEndPointAuthMethod     = TokenEndPointAuthenticationMethods.client_secret_basic,
                AllowedScopes               = client.AllowedScopes == null || !client.AllowedScopes.Any() ? new List <Core.Models.Scope>() : client.AllowedScopes.Select(s => s.ToDomain()).ToList(),
                RedirectionUrls             = client.RedirectUris == null || !client.RedirectUris.Any() ? new List <string>() : client.RedirectUris.Select(s => s.RedirectUri).ToList(),
                ApplicationType             = ApplicationTypes.web
            };

            if (client.AllowedGrantTypes != null)
            {
                var grantingMethod = _mappingIdServerGrantTypesToGrantingMethods.FirstOrDefault(m =>
                                                                                                client.AllowedGrantTypes.Count() == m.Key.Count() &&
                                                                                                m.Key.All(g => client.AllowedGrantTypes.Any(c => c.GrantType == g)));
                if (!grantingMethod.Equals(default(KeyValuePair <IEnumerable <string>, GrantingMethod>)))
                {
                    result.ResponseTypes = grantingMethod.Value.ResponseTypes;
                    result.GrantTypes    = grantingMethod.Value.GrantTypes;
                }
            }

            return(result);
        }
        public static IdentityServer4.EntityFramework.Entities.Client ToEntity(this Core.Models.Client client)
        {
            var result = new IdentityServer4.EntityFramework.Entities.Client
            {
                ClientId                     = client.ClientId,
                ClientName                   = client.ClientName,
                Enabled                      = true,
                RequireClientSecret          = true,
                RequireConsent               = true,
                AllowRememberConsent         = true,
                LogoutSessionRequired        = true,
                IdentityTokenLifetime        = 300,
                AccessTokenLifetime          = 3600,
                AuthorizationCodeLifetime    = 300,
                AbsoluteRefreshTokenLifetime = 2592000,
                SlidingRefreshTokenLifetime  = 1296000,
                RefreshTokenUsage            = (int)TokenUsage.OneTimeOnly,
                RefreshTokenExpiration       = (int)TokenExpiration.Absolute,
                EnableLocalLogin             = true,
                PrefixClientClaims           = true,
                AllowAccessTokensViaBrowser  = true,
                LogoUri                      = client.LogoUri,
                ClientUri                    = client.ClientUri,
                AllowedScopes                = client.AllowedScopes == null || !client.AllowedScopes.Any() ? new List <IdentityServer4.EntityFramework.Entities.ClientScope>() : client.AllowedScopes.Select(s => new IdentityServer4.EntityFramework.Entities.ClientScope
                {
                    Scope = s.Name
                }).ToList(),
                RedirectUris = client.RedirectionUrls == null || !client.RedirectionUrls.Any() ? new List <IdentityServer4.EntityFramework.Entities.ClientRedirectUri>() : client.RedirectionUrls.Select(r => new IdentityServer4.EntityFramework.Entities.ClientRedirectUri
                {
                    RedirectUri = r
                }).ToList(),
                ClientSecrets = string.IsNullOrWhiteSpace(client.ClientSecret) ? new List <IdentityServer4.EntityFramework.Entities.ClientSecret>() : new List <IdentityServer4.EntityFramework.Entities.ClientSecret>
                {
                    new IdentityServer4.EntityFramework.Entities.ClientSecret
                    {
                        Value = client.ClientSecret,
                        Type  = "SharedSecret"
                    }
                }
            };

            var grantingMethod = new GrantingMethod
            {
                GrantTypes    = client.GrantTypes,
                ResponseTypes = client.ResponseTypes
            };

            var meth = _mappingIdServerGrantTypesToGrantingMethods.FirstOrDefault(m => m.Value.Equals(grantingMethod));

            if (meth.Equals(default(KeyValuePair <IEnumerable <string>, GrantingMethod>)))
            {
                throw new InvalidOperationException("The grant type is not supported");
            }

            result.AllowedGrantTypes = meth.Key.Select(g => new IdentityServer4.EntityFramework.Entities.ClientGrantType {
                GrantType = g
            }).ToList();
            return(result);
        }
Exemple #6
0
        public async Task <bool> UpdateAsync(Core.Models.Client client)
        {
            using (var transaction = await _context.Database.BeginTransactionAsync().ConfigureAwait(false))
            {
                try
                {
                    var record = client.ToEntity();
                    var result = await _context.Clients.FirstOrDefaultAsync(c => c.ClientId == record.ClientId).ConfigureAwait(false);

                    if (result == null)
                    {
                        return(false);
                    }

                    result.ClientName                   = record.ClientName;
                    result.Enabled                      = record.Enabled;
                    result.RequireClientSecret          = record.RequireClientSecret;
                    result.RequireConsent               = record.RequireConsent;
                    result.AllowRememberConsent         = record.AllowRememberConsent;
                    result.LogoutSessionRequired        = record.LogoutSessionRequired;
                    result.IdentityTokenLifetime        = record.IdentityTokenLifetime;
                    result.AccessTokenLifetime          = record.AccessTokenLifetime;
                    result.AuthorizationCodeLifetime    = record.AuthorizationCodeLifetime;
                    result.AbsoluteRefreshTokenLifetime = record.AbsoluteRefreshTokenLifetime;
                    result.SlidingRefreshTokenLifetime  = record.SlidingRefreshTokenLifetime;
                    result.RefreshTokenUsage            = record.RefreshTokenUsage;
                    result.RefreshTokenExpiration       = record.RefreshTokenExpiration;
                    result.EnableLocalLogin             = record.EnableLocalLogin;
                    result.PrefixClientClaims           = record.PrefixClientClaims;
                    result.LogoUri                      = record.LogoUri;
                    result.ClientUri                    = record.ClientUri;
                    result.AllowedScopes                = record.AllowedScopes;
                    result.RedirectUris                 = record.RedirectUris;
                    result.AllowedGrantTypes            = record.AllowedGrantTypes;
                    await _context.SaveChangesAsync().ConfigureAwait(false);;
                    transaction.Commit();
                    return(true);
                }
                catch (Exception ex)
                {
                    _managerEventSource.Failure(ex);
                    transaction.Rollback();
                    return(false);
                }
            }
        }
        public static IdentityClient ToEntity(this Core.Models.Client s)
        {
            if (s == null)
            {
                return(null);
            }

            if (s.ClientSecrets == null)
            {
                s.ClientSecrets = new List <Secret>();
            }
            if (s.RedirectUris == null)
            {
                s.RedirectUris = new List <string>();
            }
            if (s.PostLogoutRedirectUris == null)
            {
                s.PostLogoutRedirectUris = new List <string>();
            }
            if (s.AllowedScopes == null)
            {
                s.AllowedScopes = new List <string>();
            }
            if (s.IdentityProviderRestrictions == null)
            {
                s.IdentityProviderRestrictions = new List <string>();
            }
            if (s.Claims == null)
            {
                s.Claims = new List <Claim>();
            }
            if (s.AllowedCustomGrantTypes == null)
            {
                s.AllowedCustomGrantTypes = new List <string>();
            }
            if (s.AllowedCorsOrigins == null)
            {
                s.AllowedCorsOrigins = new List <string>();
            }

            return(Config.CreateMapper().Map <Core.Models.Client, IdentityClient>(s));
        }
Exemple #8
0
 public async Task <bool> InsertAsync(Core.Models.Client client)
 {
     using (var transaction = await _context.Database.BeginTransactionAsync().ConfigureAwait(false))
     {
         try
         {
             var record = client.ToEntity();
             _context.Clients.Add(record);
             await _context.SaveChangesAsync().ConfigureAwait(false);;
             transaction.Commit();
             return(true);
         }
         catch (Exception ex)
         {
             _managerEventSource.Failure(ex);
             transaction.Rollback();
             return(false);
         }
     }
 }
        public async Task <bool> UpdateAsync(Core.Models.Client client)
        {
            using (var translation = _context.Database.BeginTransaction())
            {
                try
                {
                    var grantTypes = client.GrantTypes == null
                        ? string.Empty
                        : ConcatListOfIntegers(client.GrantTypes.Select(k => (int)k).ToList());
                    var responseTypes = client.ResponseTypes == null
                        ? string.Empty
                        : ConcatListOfIntegers(client.ResponseTypes.Select(r => (int)r).ToList());
                    var connectedClient = await _context.Clients
                                          .Include(c => c.ClientScopes)
                                          .FirstOrDefaultAsync(c => c.ClientId == client.ClientId)
                                          .ConfigureAwait(false);

                    connectedClient.ClientName                  = client.ClientName;
                    connectedClient.ClientUri                   = client.ClientUri;
                    connectedClient.Contacts                    = ConcatListOfStrings(client.Contacts);
                    connectedClient.DefaultAcrValues            = client.DefaultAcrValues;
                    connectedClient.DefaultMaxAge               = client.DefaultMaxAge;
                    connectedClient.GrantTypes                  = grantTypes;
                    connectedClient.IdTokenEncryptedResponseAlg = client.IdTokenEncryptedResponseAlg;
                    connectedClient.IdTokenEncryptedResponseEnc = client.IdTokenEncryptedResponseEnc;
                    connectedClient.IdTokenSignedResponseAlg    = client.IdTokenSignedResponseAlg;
                    connectedClient.InitiateLoginUri            = client.InitiateLoginUri;
                    connectedClient.JwksUri                     = client.JwksUri;
                    connectedClient.LogoUri                     = client.LogoUri;
                    connectedClient.PolicyUri                   = client.PolicyUri;
                    connectedClient.RedirectionUrls             = ConcatListOfStrings(client.RedirectionUrls);
                    connectedClient.RequestObjectEncryptionAlg  = client.RequestObjectEncryptionAlg;
                    connectedClient.RequestObjectEncryptionEnc  = client.RequestObjectEncryptionEnc;
                    connectedClient.RequestObjectSigningAlg     = client.RequestObjectSigningAlg;
                    connectedClient.RequestUris                 = ConcatListOfStrings(client.RequestUris);
                    connectedClient.RequireAuthTime             = client.RequireAuthTime;
                    connectedClient.ResponseTypes               = responseTypes;
                    connectedClient.SectorIdentifierUri         = client.SectorIdentifierUri;
                    connectedClient.SubjectType                 = client.SubjectType;
                    connectedClient.TokenEndPointAuthMethod     = (TokenEndPointAuthenticationMethods)client.TokenEndPointAuthMethod;
                    connectedClient.TokenEndPointAuthSigningAlg = client.TokenEndPointAuthSigningAlg;
                    connectedClient.TosUri = client.TosUri;
                    connectedClient.UserInfoEncryptedResponseAlg = client.UserInfoEncryptedResponseAlg;
                    connectedClient.UserInfoEncryptedResponseEnc = client.UserInfoEncryptedResponseEnc;
                    connectedClient.UserInfoSignedResponseAlg    = client.UserInfoSignedResponseAlg;
                    connectedClient.ScimProfile = client.ScimProfile;
                    var scopesNotToBeDeleted = new List <string>();
                    if (client.AllowedScopes != null)
                    {
                        foreach (var scope in client.AllowedScopes)
                        {
                            var record = connectedClient.ClientScopes.FirstOrDefault(c => c.ScopeName == scope.Name);
                            if (record == null)
                            {
                                record = new ClientScope
                                {
                                    ClientId  = connectedClient.ClientId,
                                    ScopeName = scope.Name
                                };
                                connectedClient.ClientScopes.Add(record);
                            }

                            scopesNotToBeDeleted.Add(record.ScopeName);
                        }
                    }

                    var scopeNames = connectedClient.ClientScopes.Select(o => o.ScopeName).ToList();
                    foreach (var scopeName in scopeNames.Where(id => !scopesNotToBeDeleted.Contains(id)))
                    {
                        connectedClient.ClientScopes.Remove(connectedClient.ClientScopes.First(s => s.ScopeName == scopeName));
                    }

                    await _context.SaveChangesAsync();

                    translation.Commit();
                }
                catch (Exception ex)
                {
                    _managerEventSource.Failure(ex);
                    translation.Rollback();
                    return(false);
                }
            }

            return(true);
        }
        public async Task <bool> InsertAsync(Core.Models.Client client)
        {
            using (var transaction = _context.Database.BeginTransaction())
            {
                try
                {
                    var scopes        = new List <ClientScope>();
                    var jsonWebKeys   = new List <JsonWebKey>();
                    var clientSecrets = new List <ClientSecret>();
                    var grantTypes    = client.GrantTypes == null
                        ? string.Empty
                        : ConcatListOfIntegers(client.GrantTypes.Select(k => (int)k).ToList());
                    var responseTypes = client.ResponseTypes == null
                        ? string.Empty
                        : ConcatListOfIntegers(client.ResponseTypes.Select(r => (int)r).ToList());
                    if (client.AllowedScopes != null)
                    {
                        var scopeNames = client.AllowedScopes.Select(s => s.Name).ToList();
                        scopes = _context.Scopes.Where(s => scopeNames.Contains(s.Name))
                                 .Select(s => new ClientScope {
                            ScopeName = s.Name
                        })
                                 .ToList();
                    }

                    if (client.JsonWebKeys != null)
                    {
                        client.JsonWebKeys.ForEach(jsonWebKey =>
                        {
                            var jsonWebKeyRecord = new JsonWebKey
                            {
                                Kid           = jsonWebKey.Kid,
                                Use           = (Use)jsonWebKey.Use,
                                Kty           = (KeyType)jsonWebKey.Kty,
                                SerializedKey = jsonWebKey.SerializedKey,
                                X5t           = jsonWebKey.X5t,
                                X5tS256       = jsonWebKey.X5tS256,
                                X5u           = jsonWebKey.X5u == null ? string.Empty : jsonWebKey.X5u.AbsoluteUri,
                                Alg           = (AllAlg)jsonWebKey.Alg,
                                KeyOps        = jsonWebKey.KeyOps == null ? string.Empty : ConcatListOfIntegers(jsonWebKey.KeyOps.Select(k => (int)k).ToList())
                            };

                            jsonWebKeys.Add(jsonWebKeyRecord);
                        });
                    }

                    if (client.Secrets != null)
                    {
                        foreach (var secret in client.Secrets)
                        {
                            clientSecrets.Add(new ClientSecret
                            {
                                Id       = Guid.NewGuid().ToString(),
                                ClientId = client.ClientId,
                                Type     = (SecretTypes)secret.Type,
                                Value    = secret.Value
                            });
                        }
                    }

                    var newClient = new Models.Client
                    {
                        ClientId   = client.ClientId,
                        ClientName = client.ClientName,
                        ClientUri  = client.ClientUri,
                        IdTokenEncryptedResponseAlg = client.IdTokenEncryptedResponseAlg,
                        IdTokenEncryptedResponseEnc = client.IdTokenEncryptedResponseEnc,
                        JwksUri   = client.JwksUri,
                        TosUri    = client.TosUri,
                        LogoUri   = client.LogoUri,
                        PolicyUri = client.PolicyUri,
                        RequestObjectEncryptionAlg = client.RequestObjectEncryptionAlg,
                        RequestObjectEncryptionEnc = client.RequestObjectEncryptionEnc,
                        IdTokenSignedResponseAlg   = client.IdTokenSignedResponseAlg,
                        RequireAuthTime            = client.RequireAuthTime,
                        SectorIdentifierUri        = client.SectorIdentifierUri,
                        SubjectType = client.SubjectType,
                        TokenEndPointAuthSigningAlg  = client.TokenEndPointAuthSigningAlg,
                        UserInfoEncryptedResponseAlg = client.UserInfoEncryptedResponseAlg,
                        UserInfoSignedResponseAlg    = client.UserInfoSignedResponseAlg,
                        UserInfoEncryptedResponseEnc = client.UserInfoEncryptedResponseEnc,
                        DefaultMaxAge           = client.DefaultMaxAge,
                        DefaultAcrValues        = client.DefaultAcrValues,
                        InitiateLoginUri        = client.InitiateLoginUri,
                        RequestObjectSigningAlg = client.RequestObjectSigningAlg,
                        TokenEndPointAuthMethod = (Models.TokenEndPointAuthenticationMethods)client.TokenEndPointAuthMethod,
                        ApplicationType         = (Models.ApplicationTypes)client.ApplicationType,
                        RequestUris             = ConcatListOfStrings(client.RequestUris),
                        RedirectionUrls         = ConcatListOfStrings(client.RedirectionUrls),
                        Contacts      = ConcatListOfStrings(client.Contacts),
                        ClientScopes  = scopes,
                        JsonWebKeys   = jsonWebKeys,
                        GrantTypes    = grantTypes,
                        ResponseTypes = responseTypes,
                        ScimProfile   = client.ScimProfile,
                        ClientSecrets = clientSecrets
                    };

                    _context.Clients.Add(newClient);
                    await _context.SaveChangesAsync().ConfigureAwait(false);

                    transaction.Commit();
                }
                catch (Exception ex)
                {
                    _managerEventSource.Failure(ex);
                    transaction.Rollback();
                    return(false);
                }
            }

            return(true);
        }