private async Task <Response <string> > AddAsync(ClientViewModel viewModel) { //判断 var identityResource = await _configurationDbContext.Clients.FirstOrDefaultAsync(d => d.ClientId == viewModel.ClientId); if (identityResource != null) { return(new Response <string>(success: false, msg: "Api域名称已存在!") { Data = "Api域名称已存在!" }); } identityResource = new IdentityServer4.EntityFramework.Entities.Client { ClientId = viewModel.ClientId, ClientName = viewModel.ClientName, Description = viewModel.Description, }; await _configurationDbContext.Clients.AddAsync(identityResource); var result = await _configurationDbContext.SaveChangesAsync(); if (result < 1) { return(new Response <string>(success: false, msg: "注册失败,请重试!") { Data = "注册失败,请重试!" }); } return(new Response <string>(msg: "注册成功!") { Data = "注册成功!" }); }
public async Task <IActionResult> CreateImplicitApplicationAsync([FromBody] CreateApplicationViewModel applicationViewModel) { Client client = new Client { ClientId = Guid.NewGuid().ToString().Replace("-", ""), ClientName = applicationViewModel.ApplicationName, AllowedGrantTypes = GrantTypes.Implicit, AllowAccessTokensViaBrowser = true, ClientUri = applicationViewModel.HomepageURL, RedirectUris = { $"{applicationViewModel.AuthorizationCallbackURL}/swagger/oauth2-redirect.html" }, PostLogoutRedirectUris = { $"{applicationViewModel.HomepageURL}/swagger/" }, AllowedScopes = { "orders" } }; IdentityServer4.EntityFramework.Entities.Client clientEntity = client.ToEntity(); clientEntity.Description = applicationViewModel.ApplicationDescription; _context.Clients.Add(clientEntity); await _context.SaveChangesAsync(); return(CreatedAtAction(nameof(GetAsync), new { id = clientEntity.Id }, null)); }
public async Task <IActionResult> OnPostAsync() { if (!ModelState.IsValid) { await LoadLookups(); return(Page()); } Client client; var isNew = Client.Id == 0; if (isNew) { PrepareClientTypeForNewClient(Client); client = Client.ToEntity(); await _dbContext.Clients.AddAsync(client); } else { client = await LoadClient(Client.Id); Client.ToEntity(client); } await _dbContext.SaveChangesAsync(); return(isNew ? RedirectToPage("/Clients/Edit", new { id = client.Id }) : RedirectToPage("/Clients/Index")); }
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 async Task <ClientModel> PrepareClientModel(ClientModel model, Client client, bool excludeProperties = false) { if (client != null) { model = model ?? client.ToModel(); if (!excludeProperties) { model.Enabled = client.Enabled; model.JavaScriptClient = client.AllowedGrantTypes.Any(g => g.GrantType.Equals(OidcConstants.GrantTypes.Implicit)); model.ClientId = client.ClientId; model.ClientName = client.ClientName; model.ClientSecret = client.ClientSecrets.FirstOrDefault()?.Description; model.AccessTokenLifetime = client.AccessTokenLifetime; model.RefreshTokenLifetime = client.AbsoluteRefreshTokenLifetime; } //prepare nested search models await PrepareUrisSearchModel(model.UrisSearchModel, client); } //set default values for the new model if (client == null) { model.Enabled = true; model.JavaScriptClient = false; model.ClientSecret = Guid.NewGuid().ToString(); model.ClientId = Guid.NewGuid().ToString(); model.AccessTokenLifetime = Configurations.DefaultAccessTokenExpiration; model.RefreshTokenLifetime = Configurations.DefaultRefreshTokenExpiration; } return(model); }
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); }
public static SecretsModel FromEntity(IdentityServer4.EntityFramework.Entities.Client client) { return(new SecretsModel { Client = ClientModel.FromEntity(client), Secrets = client.ClientSecrets?.Select(x => FromEntity(x))?.ToList(), }); }
protected string GetClientProperty(PropertyMetadata propMetadata, IdentityServer4.EntityFramework.Entities.Client client) { string val; if (propMetadata.TryGet(client, out val)) { return(val); } throw new Exception("Invalid property type " + propMetadata.Type); }
public Task <IdentityAdminResult <CreateResult> > CreateClientAsync(IEnumerable <PropertyValue> properties) { var clientNameClaim = properties.Single(x => x.Type == "ClientName"); var clientIdClaim = properties.Single(x => x.Type == "ClientId"); var clientId = clientIdClaim.Value; var clientName = clientNameClaim.Value; string[] exclude = new string[] { "ClientName", "ClientId" }; var otherProperties = properties.Where(x => !exclude.Contains(x.Type)).ToArray(); var metadata = GetMetadata(); var createProps = metadata.CreateProperties; var client = new Client(); var inMemoryClient = new IdentityServer4.EntityFramework.Entities.Client { ClientId = clientId, ClientName = clientName, //Id = _clients.Count + 1, AbsoluteRefreshTokenLifetime = client.AbsoluteRefreshTokenLifetime, AccessTokenLifetime = client.AccessTokenLifetime, IdentityTokenLifetime = client.IdentityTokenLifetime, SlidingRefreshTokenLifetime = client.SlidingRefreshTokenLifetime, Enabled = true, EnableLocalLogin = true, }; foreach (var prop in otherProperties) { var propertyResult = SetClientProperty(createProps, inMemoryClient, prop.Type, prop.Value); if (!propertyResult.IsSuccess) { return(Task.FromResult(new IdentityAdminResult <CreateResult>(propertyResult.Errors.ToArray()))); } } using (var db = new ConfigurationDbContext(connection)) { try { db.Clients.Add(inMemoryClient); db.SaveChanges(); } catch (Exception ex) { return(Task.FromResult(new IdentityAdminResult <CreateResult>(ex.Message))); } } return (Task.FromResult( new IdentityAdminResult <CreateResult>(new CreateResult { Subject = inMemoryClient.Id.ToString() }))); }
public async Task <int> UpdateClientsAsync(List <Client> input) { using (var db = _contextFactory()) { foreach (var dto in input) { IdentityServer4.EntityFramework.Entities.Client entity = null; if (dto.ClientSecrets != null && dto.ClientSecrets.Count >= 1 && !string.IsNullOrEmpty(dto.ClientSecrets.First().Value)) { entity = db.Clients .Include(x => x.AllowedGrantTypes) .Include(x => x.RedirectUris) .Include(x => x.PostLogoutRedirectUris) .Include(x => x.AllowedScopes) .Include(x => x.ClientSecrets) .Where(s => s.ClientId == dto.ClientId).FirstOrDefault(); } else { entity = db.Clients .Include(x => x.AllowedGrantTypes) .Include(x => x.RedirectUris) .Include(x => x.PostLogoutRedirectUris) .Include(x => x.AllowedScopes) .Where(s => s.ClientId == dto.ClientId).FirstOrDefault(); } db.ClientGrantType.RemoveRange(entity.AllowedGrantTypes); db.ClientPostLogoutRedirectUri.RemoveRange(entity.PostLogoutRedirectUris); db.ClientRedirectUri.RemoveRange(entity.RedirectUris); if (entity.ClientSecrets != null) { db.ClientSecret.RemoveRange(entity.ClientSecrets); } db.ClientScope.RemoveRange(entity.AllowedScopes); var inputEntity = dto.ToEntity(); entity.ClientName = inputEntity.ClientName; var FirstSecrts = inputEntity.ClientSecrets.FirstOrDefault(); if (FirstSecrts != null && !string.IsNullOrEmpty(FirstSecrts.Value)) { entity.ClientSecrets = inputEntity.ClientSecrets; } // else entity.ClientSecrets = entity.ClientSecrets; entity.AllowedGrantTypes = inputEntity.AllowedGrantTypes; entity.AllowedScopes = inputEntity.AllowedScopes; entity.RedirectUris = inputEntity.RedirectUris; entity.PostLogoutRedirectUris = inputEntity.PostLogoutRedirectUris; db.Clients.Update(entity); } return(await db.SaveChangesAsync()); } }
public IActionResult Post([FromBody] IdentityServer4.EntityFramework.Entities.Client client) { var res = _context.Clients.Add(client); if (_context.SaveChanges() > 0) { return(Ok(true)); } else { return(Ok(false)); } }
public async Task <IActionResult> CreateOAuthApplicationAsync([FromBody] CreateApplicationViewModel applicationViewModel) { Client client = new Client { ClientId = Guid.NewGuid().ToString().Replace("-", ""), ClientName = applicationViewModel.ApplicationName, ClientSecrets = new List <Secret> { new Secret("secret".Sha256()) }, ClientUri = $"{applicationViewModel.HomepageURL}", //public uri of the client AllowedGrantTypes = GrantTypes.CodeAndClientCredentials, // or GrantTypes.Code AllowAccessTokensViaBrowser = false, RequireConsent = false, AllowOfflineAccess = true, AlwaysIncludeUserClaimsInIdToken = true, RedirectUris = new List <string> { $"{applicationViewModel.AuthorizationCallbackURL}/signin-oidc" }, PostLogoutRedirectUris = new List <string> { $"{applicationViewModel.HomepageURL}/signout-callback-oidc" }, AllowedScopes = new List <string> { IdentityServerConstants.StandardScopes.OpenId, IdentityServerConstants.StandardScopes.Profile, IdentityServerConstants.StandardScopes.OfflineAccess, "orders", "basket", "locations", "marketing", "webshoppingagg", "orders.signalrhub", "webhooks" }, AccessTokenLifetime = 60 * 60 * 2, // 2 hours IdentityTokenLifetime = 60 * 60 * 2 // 2 hours }; IdentityServer4.EntityFramework.Entities.Client clientEntity = client.ToEntity(); clientEntity.Description = applicationViewModel.ApplicationDescription; _context.Clients.Add(clientEntity); await _context.SaveChangesAsync(); return(CreatedAtAction(nameof(GetAsync), new { id = clientEntity.Id }, null)); }
private IdentityServer4.EntityFramework.Entities.Client MapUpdateClient(IdentityServer4.EntityFramework.Entities.Client clientEntity, IdentityServer4.EntityFramework.Entities.Client clientUpdateEntity) { clientEntity.ClientSecrets = clientUpdateEntity.ClientSecrets; clientEntity.RedirectUris = clientUpdateEntity.RedirectUris; clientEntity.PostLogoutRedirectUris = clientUpdateEntity.PostLogoutRedirectUris; clientEntity.AbsoluteRefreshTokenLifetime = clientUpdateEntity.AbsoluteRefreshTokenLifetime; clientEntity.AccessTokenLifetime = clientUpdateEntity.AccessTokenLifetime; clientEntity.AuthorizationCodeLifetime = clientUpdateEntity.AuthorizationCodeLifetime; clientEntity.ConsentLifetime = clientUpdateEntity.ConsentLifetime; clientEntity.IdentityTokenLifetime = clientUpdateEntity.IdentityTokenLifetime; clientEntity.SlidingRefreshTokenLifetime = clientUpdateEntity.SlidingRefreshTokenLifetime; clientEntity.AllowedScopes = clientUpdateEntity.AllowedScopes; return(clientEntity); }
protected Task PrepareUrisSearchModel(UrisSearchModel searchModel, Client client) { if (searchModel == null) { throw new ArgumentNullException(nameof(searchModel)); } if (client == null) { throw new ArgumentNullException(nameof(client)); } searchModel.ClientId = client.Id; searchModel.SetGridPageSize(); return(Task.FromResult(searchModel)); }
public ClientDto MapToClientDto(IdentityServer4.EntityFramework.Entities.Client entity) { var clientDto = new ClientDto(); clientDto.Id = entity.Id; clientDto.ClientId = entity.ClientId; clientDto.ClientName = entity.ClientName; clientDto.ClientSecrets = entity.ClientSecrets?.Select(x => x.Value).ToList(); clientDto.AllowedScopes = entity.AllowedScopes?.Select(x => x.Scope).ToList(); clientDto.RedirectUris = entity.RedirectUris?.Select(x => x.RedirectUri).ToList(); clientDto.PostLogoutRedirectUris = entity.PostLogoutRedirectUris?.Select(x => x.PostLogoutRedirectUri).ToList(); clientDto.AbsoluteRefreshTokenLifetime = entity.AbsoluteRefreshTokenLifetime; clientDto.AccessTokenLifetime = entity.AccessTokenLifetime; clientDto.AuthorizationCodeLifetime = entity.AuthorizationCodeLifetime; clientDto.ConsentLifetime = (int)entity.ConsentLifetime; clientDto.IdentityTokenLifetime = entity.IdentityTokenLifetime; clientDto.SlidingRefreshTokenLifetime = entity.SlidingRefreshTokenLifetime; return(clientDto); }
public async Task <IActionResult> Post(string clientId, string key, string value) { //IdentityServer4.Models.Client client = await _clientStore.FindClientByIdAsync(clientId); IdentityServer4.EntityFramework.Entities.Client client = _configurationDbContext.Clients.SingleOrDefault(c => c.ClientId == clientId); if (client == null) { return(NotFound()); } IdentityServer4.EntityFramework.Entities.ClientProperty clientProperty = null; if (client.Properties == null) { client.Properties = new List <IdentityServer4.EntityFramework.Entities.ClientProperty>(); } else { clientProperty = client.Properties?.SingleOrDefault(prop => prop.Key == key); } if (clientProperty != null) //if (client.Properties.ContainsKey(key)) { //client.Properties.Remove(key); client.Properties.Remove(clientProperty); } //client.Properties.Add(key, value); client.Properties.Add(new IdentityServer4.EntityFramework.Entities.ClientProperty { Client = client, Key = key, Value = value }); //client.Properties.Add(new KeyValuePair<string, string>(key, value)); //_configurationDbContext.Clients.Attach(client.ToEntity()); //_configurationDbContext.Clients.Update(client.ToEntity()); await _configurationDbContext.SaveChangesAsync(); return(Ok()); }
/// <summary> /// Creates a new instace of <see cref="ClientInfo"/> from a <see cref="IdentityServer4.EntityFramework.Entities.Client"/> object. /// </summary> /// <param name="client">The client instance.</param> public static ClientInfo FromClient(IdentityServer4.EntityFramework.Entities.Client client) => new()
protected IdentityAdminResult SetClientProperty(IEnumerable <PropertyMetadata> propsMeta, IdentityServer4.EntityFramework.Entities.Client client, string type, string value) { IdentityAdminResult result; if (propsMeta.TrySet(client, type, value, out result)) { return(result); } throw new Exception("Invalid property type " + type); }
public async Task <CorsOriginUrisListModel> PrepareCorsOriginsListModel(UrisSearchModel searchModel, Client client) { if (searchModel == null) { throw new ArgumentNullException(nameof(searchModel)); } if (client == null) { throw new ArgumentNullException(nameof(client)); } var corsOriginsUris = await _clientService.GetCostOriginsUris( clientId : client.Id, pageIndex : searchModel.Page - 1, pageSize : searchModel.PageSize); var model = new CorsOriginUrisListModel { Data = corsOriginsUris.Select(co => { var model1 = co.ToModel(); model1.ClientId = co.ClientId; model1.Url = co.Origin; return(model1); }), Total = corsOriginsUris.Count }; if (searchModel.Sort != null && searchModel.Sort.Any()) { foreach (var s in searchModel.Sort) { model.Data = await model.Data.Sort(s.Field, s.Dir); } } if (searchModel.Filter != null && searchModel.Filter.Filters != null && searchModel.Filter.Filters.Any()) { var filter = searchModel.Filter; model.Data = await model.Data.Filter(filter); model.Total = model.Data.Count(); } return(model); }