1
0
mirror of https://git.teknik.io/Teknikode/Teknik.git synced 2023-08-02 14:16:22 +02:00

Fixed identity APi responses/management errors

This commit is contained in:
Uncled1023 2021-07-12 20:21:50 -07:00
parent 0bc7abed27
commit e41fa8c199
10 changed files with 60 additions and 52 deletions

1
.gitignore vendored
View File

@ -269,3 +269,4 @@ __pycache__/
/ServiceWorker/Properties/launchSettings.json /ServiceWorker/Properties/launchSettings.json
/IdentityServer/App_Data/Config.json /IdentityServer/App_Data/Config.json
/ServiceWorker/Output /ServiceWorker/Output
/IdentityServer/tempkey.jwk

View File

@ -18,6 +18,8 @@ namespace Teknik.Configuration
public string APIName { get; set; } public string APIName { get; set; }
public string APISecret { get; set; } public string APISecret { get; set; }
public string SigningCertificate { get; set; }
public IdentityServerConfig() public IdentityServerConfig()
{ {
Host = "localhost:5002"; Host = "localhost:5002";

View File

@ -89,12 +89,12 @@ namespace Teknik.IdentityServer.Controllers
if (foundUser != null) if (foundUser != null)
{ {
// Find this user's clients // Find this user's clients
var foundClients = configContext.Clients.Where(c => var lowerUsername = model.Username.ToLower();
c.Properties.Exists(p => var foundClients = configContext.Clients
p.Key == "username" && .Select(c => new { Client = c, Username = c.Properties.FirstOrDefault(p => p.Key == "username").Value })
p.Value.ToLower() == model.Username.ToLower()) .Where(c => c.Username.ToLower() == lowerUsername)
).ToList(); .Select(c => c.Client);
if (foundClients != null) if (foundClients.Any())
{ {
configContext.Clients.RemoveRange(foundClients); configContext.Clients.RemoveRange(foundClients);
configContext.SaveChanges(); configContext.SaveChanges();
@ -133,7 +133,8 @@ namespace Teknik.IdentityServer.Controllers
var foundUser = await GetCachedUser(username); var foundUser = await GetCachedUser(username);
if (foundUser != null) if (foundUser != null)
{ {
return new JsonResult(new { success = true, data = foundUser.ToJson() }); var userJson = foundUser.ToJson();
return new JsonResult(new { success = true, data = userJson });
} }
return new JsonResult(new { success = false, message = "User does not exist." }); return new JsonResult(new { success = false, message = "User does not exist." });
} }
@ -479,15 +480,15 @@ namespace Teknik.IdentityServer.Controllers
if (string.IsNullOrEmpty(clientId)) if (string.IsNullOrEmpty(clientId))
return new JsonResult(new { success = false, message = "Client Id is required" }); return new JsonResult(new { success = false, message = "Client Id is required" });
var client = configContext.Clients.FirstOrDefault(c => var lowerUsername = username.ToLower();
c.ClientId == clientId && var client = configContext.Clients
c.Properties.Exists(p => .Select(c => new { Id = c.ClientId, Username = c.Properties.FirstOrDefault(p => p.Key == "username").Value })
p.Key == "username" && .FirstOrDefault(c =>
p.Value.ToLower() == username.ToLower()) c.Id == clientId &&
); c.Username.ToLower() == lowerUsername);
if (client != null) if (client != null)
{ {
var foundClient = await clientStore.FindClientByIdAsync(client.ClientId); var foundClient = await clientStore.FindClientByIdAsync(client.Id);
return new JsonResult(new { success = true, data = foundClient }); return new JsonResult(new { success = true, data = foundClient });
} }
@ -500,15 +501,14 @@ namespace Teknik.IdentityServer.Controllers
if (string.IsNullOrEmpty(username)) if (string.IsNullOrEmpty(username))
return new JsonResult(new { success = false, message = "Username is required" }); return new JsonResult(new { success = false, message = "Username is required" });
var foundClientIds = configContext.Clients.Where(c => var lowerUsername = username.ToLower();
c.Properties.Exists(p => var foundClientIds = configContext.Clients
p.Key == "username" && .Select(c => new { Id = c.ClientId, Username = c.Properties.FirstOrDefault(p => p.Key == "username").Value })
p.Value.ToLower() == username.ToLower()) .Where(c => c.Username.ToLower() == lowerUsername);
).Select(c => c.ClientId);
var clients = new List<IdentityServer4.Models.Client>(); var clients = new List<IdentityServer4.Models.Client>();
foreach (var clientId in foundClientIds) foreach (var client in foundClientIds)
{ {
var foundClient = await clientStore.FindClientByIdAsync(clientId); var foundClient = await clientStore.FindClientByIdAsync(client.Id);
if (foundClient != null) if (foundClient != null)
clients.Add(foundClient); clients.Add(foundClient);
} }

View File

@ -26,6 +26,7 @@
<PackageReference Include="IdentityServer4.EntityFramework" Version="4.1.2" /> <PackageReference Include="IdentityServer4.EntityFramework" Version="4.1.2" />
<PackageReference Include="Microsoft.AspNetCore.Identity.EntityFrameworkCore" Version="5.0.7" /> <PackageReference Include="Microsoft.AspNetCore.Identity.EntityFrameworkCore" Version="5.0.7" />
<PackageReference Include="Microsoft.AspNetCore.Mvc.Core" Version="2.2.5" /> <PackageReference Include="Microsoft.AspNetCore.Mvc.Core" Version="2.2.5" />
<PackageReference Include="Microsoft.AspNetCore.Mvc.NewtonsoftJson" Version="5.0.7" />
<PackageReference Include="Microsoft.EntityFrameworkCore.Proxies" Version="5.0.7" /> <PackageReference Include="Microsoft.EntityFrameworkCore.Proxies" Version="5.0.7" />
<PackageReference Include="Microsoft.EntityFrameworkCore.SqlServer" Version="5.0.7" /> <PackageReference Include="Microsoft.EntityFrameworkCore.SqlServer" Version="5.0.7" />
<PackageReference Include="Microsoft.EntityFrameworkCore.Tools" Version="5.0.7"> <PackageReference Include="Microsoft.EntityFrameworkCore.Tools" Version="5.0.7">

View File

@ -11,7 +11,7 @@ by editing this MSBuild file. In order to learn more about this please visit htt
<SiteUrlToLaunchAfterPublish>https://authdev.teknik.io</SiteUrlToLaunchAfterPublish> <SiteUrlToLaunchAfterPublish>https://authdev.teknik.io</SiteUrlToLaunchAfterPublish>
<LaunchSiteAfterPublish>True</LaunchSiteAfterPublish> <LaunchSiteAfterPublish>True</LaunchSiteAfterPublish>
<ExcludeApp_Data>True</ExcludeApp_Data> <ExcludeApp_Data>True</ExcludeApp_Data>
<TargetFramework>netcoreapp2.2</TargetFramework> <TargetFramework>net5.0</TargetFramework>
<ProjectGuid>05842e03-223a-4f43-9e81-d968a9475a97</ProjectGuid> <ProjectGuid>05842e03-223a-4f43-9e81-d968a9475a97</ProjectGuid>
<SelfContained>false</SelfContained> <SelfContained>false</SelfContained>
<_IsPortable>true</_IsPortable> <_IsPortable>true</_IsPortable>

View File

@ -65,6 +65,7 @@ namespace Teknik.IdentityServer
var devEnv = config?.DevEnvironment ?? true; var devEnv = config?.DevEnvironment ?? true;
var defaultConn = config?.DbConnection ?? string.Empty; var defaultConn = config?.DbConnection ?? string.Empty;
var authority = config?.UserConfig?.IdentityServerConfig?.Authority ?? string.Empty; var authority = config?.UserConfig?.IdentityServerConfig?.Authority ?? string.Empty;
var signingCert = config?.UserConfig?.IdentityServerConfig?.SigningCertificate ?? string.Empty;
if (devEnv) if (devEnv)
{ {
@ -95,7 +96,8 @@ namespace Teknik.IdentityServer
services.AddScoped<IErrorController, ErrorController>(); services.AddScoped<IErrorController, ErrorController>();
services.AddControllersWithViews() services.AddControllersWithViews()
.AddControllersAsServices(); .AddControllersAsServices()
.AddNewtonsoftJson();
// Sessions // Sessions
services.AddResponseCaching(); services.AddResponseCaching();
@ -132,7 +134,7 @@ namespace Teknik.IdentityServer
.AddEntityFrameworkStores<ApplicationDbContext>() .AddEntityFrameworkStores<ApplicationDbContext>()
.AddDefaultTokenProviders(); .AddDefaultTokenProviders();
services.AddIdentityServer(options => var identityBuilder = services.AddIdentityServer(options =>
{ {
options.Events.RaiseErrorEvents = true; options.Events.RaiseErrorEvents = true;
options.Events.RaiseInformationEvents = true; options.Events.RaiseInformationEvents = true;
@ -154,8 +156,16 @@ namespace Teknik.IdentityServer
builder.UseSqlServer(defaultConn, sqlOptions => sqlOptions.MigrationsAssembly(migrationsAssembly))) builder.UseSqlServer(defaultConn, sqlOptions => sqlOptions.MigrationsAssembly(migrationsAssembly)))
.AddConfigurationStoreCache() .AddConfigurationStoreCache()
.AddAspNetIdentity<ApplicationUser>() .AddAspNetIdentity<ApplicationUser>()
.AddRedirectUriValidator<TeknikRedirectUriValidator>() .AddRedirectUriValidator<TeknikRedirectUriValidator>();
.AddDeveloperSigningCredential();
if (!string.IsNullOrEmpty(signingCert))
{
identityBuilder.AddSigningCredential($"CN={signingCert}");
}
else
{
identityBuilder.AddDeveloperSigningCredential();
}
services.AddAuthorization(options => services.AddAuthorization(options =>
{ {
@ -236,6 +246,10 @@ namespace Teknik.IdentityServer
app.UseIdentityServer(); app.UseIdentityServer();
// Authorize all the things!
app.UseAuthentication();
app.UseAuthorization();
app.UseEndpoints(endpoints => app.UseEndpoints(endpoints =>
{ {
endpoints.MapDefaultControllerRoute(); endpoints.MapDefaultControllerRoute();

View File

@ -1282,7 +1282,7 @@ namespace Teknik.Areas.Users.Controllers
string renderedView = await RenderPartialViewToString(viewEngine, "~/Areas/User/Views/User/Settings/ClientView.cshtml", model); string renderedView = await RenderPartialViewToString(viewEngine, "~/Areas/User/Views/User/Settings/ClientView.cshtml", model);
return Json(new { result = true, clientId = client["id"], secret = client["secret"], html = renderedView }); return Json(new { result = true, clientId = client["id"].ToString(), secret = client["secret"].ToString(), html = renderedView });
} }
return Json(new { error = result.Message }); return Json(new { error = result.Message });
} }

View File

@ -32,26 +32,22 @@ namespace Teknik.Areas.Users.Models
{ {
if (claims.FirstOrDefault(c => c.Type == "creation-date") != null) if (claims.FirstOrDefault(c => c.Type == "creation-date") != null)
{ {
DateTime dateTime = new DateTime(); if (DateTime.TryParse(claims.FirstOrDefault(c => c.Type == "creation-date").Value, out var dateTime))
if (DateTime.TryParse(claims.FirstOrDefault(c => c.Type == "creation-date").Value, out dateTime))
CreationDate = dateTime; CreationDate = dateTime;
} }
if (claims.FirstOrDefault(c => c.Type == "last-seen") != null) if (claims.FirstOrDefault(c => c.Type == "last-seen") != null)
{ {
DateTime dateTime = new DateTime(); if (DateTime.TryParse(claims.FirstOrDefault(c => c.Type == "last-seen").Value, out var dateTime))
if (DateTime.TryParse(claims.FirstOrDefault(c => c.Type == "last-seen").Value, out dateTime))
CreationDate = dateTime; CreationDate = dateTime;
} }
if (claims.FirstOrDefault(c => c.Type == "account-type") != null) if (claims.FirstOrDefault(c => c.Type == "account-type") != null)
{ {
AccountType accountType = Utilities.AccountType.Basic; if (Enum.TryParse(claims.FirstOrDefault(c => c.Type == "account-type").Value, out AccountType accountType))
if (Enum.TryParse(claims.FirstOrDefault(c => c.Type == "account-type").Value, out accountType))
AccountType = accountType; AccountType = accountType;
} }
if (claims.FirstOrDefault(c => c.Type == "account-status") != null) if (claims.FirstOrDefault(c => c.Type == "account-status") != null)
{ {
AccountStatus accountStatus = Utilities.AccountStatus.Active; if (Enum.TryParse(claims.FirstOrDefault(c => c.Type == "account-status").Value, out AccountStatus accountStatus))
if (Enum.TryParse(claims.FirstOrDefault(c => c.Type == "account-status").Value, out accountStatus))
AccountStatus = accountStatus; AccountStatus = accountStatus;
} }
if (claims.FirstOrDefault(c => c.Type == "recovery-email") != null) if (claims.FirstOrDefault(c => c.Type == "recovery-email") != null)
@ -60,14 +56,12 @@ namespace Teknik.Areas.Users.Models
} }
if (claims.FirstOrDefault(c => c.Type == "recovery-verified") != null) if (claims.FirstOrDefault(c => c.Type == "recovery-verified") != null)
{ {
bool verified = false; if (bool.TryParse(claims.FirstOrDefault(c => c.Type == "recovery-verified").Value, out var verified))
if (bool.TryParse(claims.FirstOrDefault(c => c.Type == "recovery-verified").Value, out verified))
RecoveryVerified = verified; RecoveryVerified = verified;
} }
if (claims.FirstOrDefault(c => c.Type == "2fa-enabled") != null) if (claims.FirstOrDefault(c => c.Type == "2fa-enabled") != null)
{ {
bool twoFactor = false; if (bool.TryParse(claims.FirstOrDefault(c => c.Type == "2fa-enabled").Value, out var twoFactor))
if (bool.TryParse(claims.FirstOrDefault(c => c.Type == "2fa-enabled").Value, out twoFactor))
TwoFactorEnabled = twoFactor; TwoFactorEnabled = twoFactor;
} }
if (claims.FirstOrDefault(c => c.Type == "pgp-public-key") != null) if (claims.FirstOrDefault(c => c.Type == "pgp-public-key") != null)
@ -80,26 +74,22 @@ namespace Teknik.Areas.Users.Models
{ {
if (info["creation-date"] != null) if (info["creation-date"] != null)
{ {
DateTime dateTime = new DateTime(); if (DateTime.TryParse(info["creation-date"].ToString(), out var dateTime))
if (DateTime.TryParse(info["creation-date"].ToString(), out dateTime))
CreationDate = dateTime; CreationDate = dateTime;
} }
if (info["last-seen"] != null) if (info["last-seen"] != null)
{ {
DateTime dateTime = new DateTime(); if (DateTime.TryParse(info["last-seen"].ToString(), out var dateTime))
if (DateTime.TryParse(info["last-seen"].ToString(), out dateTime))
LastSeen = dateTime; LastSeen = dateTime;
} }
if (info["account-type"] != null) if (info["account-type"] != null)
{ {
AccountType accountType = Utilities.AccountType.Basic; if (Enum.TryParse(info["account-type"].ToString(), out AccountType accountType))
if (Enum.TryParse(info["account-type"].ToString(), out accountType))
AccountType = accountType; AccountType = accountType;
} }
if (info["account-status"] != null) if (info["account-status"] != null)
{ {
AccountStatus accountStatus = Utilities.AccountStatus.Active; if (Enum.TryParse(info["account-status"].ToString(), out AccountStatus accountStatus))
if (Enum.TryParse(info["account-status"].ToString(), out accountStatus))
AccountStatus = accountStatus; AccountStatus = accountStatus;
} }
if (info["recovery-email"] != null) if (info["recovery-email"] != null)
@ -108,14 +98,12 @@ namespace Teknik.Areas.Users.Models
} }
if (info["recovery-verified"] != null) if (info["recovery-verified"] != null)
{ {
bool verified = false; if (bool.TryParse(info["recovery-verified"].ToString(), out var verified))
if (bool.TryParse(info["recovery-verified"].ToString(), out verified))
RecoveryVerified = verified; RecoveryVerified = verified;
} }
if (info["2fa-enabled"] != null) if (info["2fa-enabled"] != null)
{ {
bool twoFactor = false; if (bool.TryParse(info["2fa-enabled"].ToString(), out var twoFactor))
if (bool.TryParse(info["2fa-enabled"].ToString(), out twoFactor))
TwoFactorEnabled = twoFactor; TwoFactorEnabled = twoFactor;
} }
if (info["pgp-public-key"] != null) if (info["pgp-public-key"] != null)

View File

@ -95,7 +95,8 @@ namespace Teknik
}); });
services.AddControllersWithViews() services.AddControllersWithViews()
.AddControllersAsServices(); .AddControllersAsServices()
.AddNewtonsoftJson();
services.AddHostedService<TrackingService>(); services.AddHostedService<TrackingService>();
services.AddSingleton<IBackgroundTaskQueue, BackgroundTaskQueue>(); services.AddSingleton<IBackgroundTaskQueue, BackgroundTaskQueue>();

View File

@ -40,6 +40,7 @@
<PackageReference Include="IdentityServer4.AspNetIdentity" Version="4.1.2" /> <PackageReference Include="IdentityServer4.AspNetIdentity" Version="4.1.2" />
<PackageReference Include="IdentityServer4.EntityFramework" Version="4.1.2" /> <PackageReference Include="IdentityServer4.EntityFramework" Version="4.1.2" />
<PackageReference Include="Microsoft.AspNet.WebApi.Client" Version="5.2.7" /> <PackageReference Include="Microsoft.AspNet.WebApi.Client" Version="5.2.7" />
<PackageReference Include="Microsoft.AspNetCore.Mvc.NewtonsoftJson" Version="5.0.7" />
<PackageReference Include="Microsoft.VisualStudio.Web.CodeGeneration.Design" Version="5.0.2" /> <PackageReference Include="Microsoft.VisualStudio.Web.CodeGeneration.Design" Version="5.0.2" />
<PackageReference Include="Microsoft.AspNetCore.SignalR.Client" Version="5.0.7" /> <PackageReference Include="Microsoft.AspNetCore.SignalR.Client" Version="5.0.7" />
<PackageReference Include="Microsoft.EntityFrameworkCore.Proxies" Version="5.0.7" /> <PackageReference Include="Microsoft.EntityFrameworkCore.Proxies" Version="5.0.7" />