Skip to content

Commit

Permalink
code clean up
Browse files Browse the repository at this point in the history
  • Loading branch information
damienbod committed Jun 22, 2024
1 parent 9205769 commit e1eb2ee
Show file tree
Hide file tree
Showing 40 changed files with 126 additions and 152 deletions.
8 changes: 4 additions & 4 deletions api/Controllers/ValuesController.cs
Original file line number Diff line number Diff line change
Expand Up @@ -18,10 +18,10 @@ public IEnumerable<string> Get()

var jsonResult = new JsonResult(new { scheme, proofToken, claims });

return new string[]
{
"data 1 from the api protected using OAuth DPoP",
"data 2 from the api"
return new string[]
{
"data 1 from the api protected using OAuth DPoP",
"data 2 from the api"
};
}
}
5 changes: 2 additions & 3 deletions api/DPoP/ConfigureJwtBearerOptions.cs
Original file line number Diff line number Diff line change
@@ -1,6 +1,5 @@
using Microsoft.AspNetCore.Authentication.JwtBearer;
using Microsoft.Extensions.Options;
using System;

namespace Api;

Expand All @@ -24,8 +23,8 @@ public void PostConfigure(string? name, JwtBearerOptions options)
if (options.Events != null && !typeof(DPoPJwtBearerEvents).IsAssignableFrom(options.Events.GetType()))
{
throw new Exception("Events on JwtBearerOptions must derive from DPoPJwtBearerEvents to work with the DPoP support.");
}
}

if (options.Events == null && options.EventsType == null)
{
options.EventsType = typeof(DPoPJwtBearerEvents);
Expand Down
5 changes: 1 addition & 4 deletions api/DPoP/DPoPExtensions.cs
Original file line number Diff line number Diff line change
@@ -1,10 +1,7 @@
using IdentityModel;
using Microsoft.AspNetCore.Authentication;
using Microsoft.AspNetCore.Http;
using Microsoft.IdentityModel.Tokens;
using System.Collections.Generic;
using System.Diagnostics.CodeAnalysis;
using System.Linq;
using System.Text.Json;

namespace Api;
Expand All @@ -22,7 +19,7 @@ public static bool IsDPoPAuthorizationScheme(this HttpRequest request)
return authz?.StartsWith(DPoPPrefix, System.StringComparison.Ordinal) == true;
}

public static bool TryGetDPoPAccessToken(this HttpRequest request, [NotNullWhen(true)]out string? token)
public static bool TryGetDPoPAccessToken(this HttpRequest request, [NotNullWhen(true)] out string? token)
{
token = null;

Expand Down
8 changes: 3 additions & 5 deletions api/DPoP/DPoPJwtBearerEvents.cs
Original file line number Diff line number Diff line change
@@ -1,10 +1,8 @@
using IdentityModel;
using Microsoft.AspNetCore.Authentication.JwtBearer;
using Microsoft.AspNetCore.Http;
using Microsoft.Extensions.Options;
using Microsoft.Net.Http.Headers;
using System.Text;
using System.Threading.Tasks;
using static IdentityModel.OidcConstants;

namespace Api;
Expand Down Expand Up @@ -135,9 +133,9 @@ public override Task Challenge(JwtBearerChallengeContext context)
}
}

context.Response.Headers.Append(HeaderNames.WWWAuthenticate, sb.ToString());

context.Response.Headers.Append(HeaderNames.WWWAuthenticate, sb.ToString());


if (context.HttpContext.Items.ContainsKey("DPoP-Nonce"))
{
var nonce = context.HttpContext.Items["DPoP-Nonce"] as string;
Expand Down
4 changes: 1 addition & 3 deletions api/DPoP/DPoPOptions.cs
Original file line number Diff line number Diff line change
@@ -1,6 +1,4 @@
using System;

namespace Api;
namespace Api;

public class DPoPOptions
{
Expand Down
3 changes: 0 additions & 3 deletions api/DPoP/DPoPProofValidatonContext.cs
Original file line number Diff line number Diff line change
@@ -1,6 +1,3 @@
using System.Collections.Generic;
using System.Security.Claims;

namespace Api;

public class DPoPProofValidatonContext
Expand Down
4 changes: 2 additions & 2 deletions api/DPoP/DPoPProofValidatonResult.cs
Original file line number Diff line number Diff line change
Expand Up @@ -42,8 +42,8 @@ public class DPoPProofValidatonResult
/// <summary>
/// The jti value read from the payload.
/// </summary>
public string? TokenId { get; set; }
public string? TokenId { get; set; }

/// <summary>
/// The ath value read from the payload.
/// </summary>
Expand Down
17 changes: 6 additions & 11 deletions api/DPoP/DPoPProofValidator.cs
Original file line number Diff line number Diff line change
@@ -1,16 +1,11 @@
using IdentityModel;
using Microsoft.AspNetCore.DataProtection;
using Microsoft.Extensions.Logging;
using Microsoft.Extensions.Options;
using Microsoft.IdentityModel.JsonWebTokens;
using Microsoft.IdentityModel.Tokens;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Security.Cryptography;
using System.Text;
using System.Text.Json;
using System.Threading.Tasks;

namespace Api;

Expand Down Expand Up @@ -212,7 +207,7 @@ protected virtual async Task ValidateSignatureAsync(DPoPProofValidatonContext co
/// </summary>
protected virtual async Task ValidatePayloadAsync(DPoPProofValidatonContext context, DPoPProofValidatonResult result)
{
if(result.Payload is null )
if (result.Payload is null)
{
result.IsError = true;
result.ErrorDescription = "Missing payload";
Expand Down Expand Up @@ -275,11 +270,11 @@ protected virtual async Task ValidatePayloadAsync(DPoPProofValidatonContext cont
{
if (iat is int)
{
result.IssuedAt = (int) iat;
result.IssuedAt = (int)iat;
}
if (iat is long)
{
result.IssuedAt = (long) iat;
result.IssuedAt = (long)iat;
}
}

Expand Down Expand Up @@ -467,7 +462,7 @@ protected virtual ValueTask<long> GetUnixTimeFromNonceAsync(DPoPProofValidatonCo
protected virtual bool IsExpired(DPoPProofValidatonContext context, DPoPProofValidatonResult result, TimeSpan clockSkew, long issuedAtTime)
{
var now = DateTimeOffset.UtcNow.ToUnixTimeSeconds();
var start = now + (int) clockSkew.TotalSeconds;
var start = now + (int)clockSkew.TotalSeconds;
if (start < issuedAtTime)
{
var diff = issuedAtTime - now;
Expand All @@ -476,8 +471,8 @@ protected virtual bool IsExpired(DPoPProofValidatonContext context, DPoPProofVal
}

var dpopOptions = OptionsMonitor.Get(context.Scheme);
var expiration = issuedAtTime + (int) dpopOptions.ProofTokenValidityDuration.TotalSeconds;
var end = now - (int) clockSkew.TotalSeconds;
var expiration = issuedAtTime + (int)dpopOptions.ProofTokenValidityDuration.TotalSeconds;
var end = now - (int)clockSkew.TotalSeconds;
if (expiration < end)
{
var diff = now - expiration;
Expand Down
8 changes: 3 additions & 5 deletions api/DPoP/DPoPServiceCollectionExtensions.cs
Original file line number Diff line number Diff line change
@@ -1,7 +1,5 @@
using Microsoft.AspNetCore.Authentication.JwtBearer;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Options;
using System;

namespace Api;

Expand All @@ -16,9 +14,9 @@ public static IServiceCollection ConfigureDPoPTokensForScheme(this IServiceColle
services.AddDistributedMemoryCache();
services.AddTransient<IReplayCache, DefaultReplayCache>();

services.AddSingleton<IPostConfigureOptions<JwtBearerOptions>>(new ConfigureJwtBearerOptions(scheme));

services.AddSingleton<IPostConfigureOptions<JwtBearerOptions>>(new ConfigureJwtBearerOptions(scheme));


return services;
}

Expand Down
2 changes: 0 additions & 2 deletions api/DPoP/DefaultReplayCache.cs
Original file line number Diff line number Diff line change
@@ -1,6 +1,4 @@
using Microsoft.Extensions.Caching.Distributed;
using System;
using System.Threading.Tasks;

namespace Api;

Expand Down
3 changes: 0 additions & 3 deletions api/DPoP/IReplayCache.cs
Original file line number Diff line number Diff line change
@@ -1,6 +1,3 @@
using System;
using System.Threading.Tasks;

namespace Api;

public interface IReplayCache
Expand Down
4 changes: 2 additions & 2 deletions api/HostingExtensions.cs
Original file line number Diff line number Diff line change
Expand Up @@ -77,14 +77,14 @@ public static WebApplication ConfigureServices(this WebApplicationBuilder builde

return builder.Build();
}

public static WebApplication ConfigurePipeline(this WebApplication app)
{
IdentityModelEventSource.ShowPII = true;
JsonWebTokenHandler.DefaultInboundClaimTypeMap.Clear();

app.UseSerilogRequestLogging();

if (app.Environment.IsDevelopment())
{
app.UseDeveloperExceptionPage();
Expand Down
2 changes: 1 addition & 1 deletion api/Program.cs
Original file line number Diff line number Diff line change
Expand Up @@ -23,7 +23,7 @@

app.Run();
}
catch (Exception ex) when(ex.GetType().Name is not "StopTheHostException" && ex.GetType().Name is not "HostAbortedException")
catch (Exception ex) when (ex.GetType().Name is not "StopTheHostException" && ex.GetType().Name is not "HostAbortedException")
{
Log.Fatal(ex, "Unhandled exception");
}
Expand Down
Binary file modified identityserver/AspIdUsers.db-shm
Binary file not shown.
Binary file modified identityserver/AspIdUsers.db-wal
Binary file not shown.
4 changes: 2 additions & 2 deletions identityserver/Data/ApplicationDbContext.cs
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
using Microsoft.AspNetCore.Identity.EntityFrameworkCore;
using IdentityServer.Models;
using Microsoft.AspNetCore.Identity.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore;
using IdentityServer.Models;

namespace IdentityServer.Data;

Expand Down
3 changes: 1 addition & 2 deletions identityserver/Data/Migrations/20230806083442_Users.cs
Original file line number Diff line number Diff line change
@@ -1,5 +1,4 @@
using System;
using Microsoft.EntityFrameworkCore.Migrations;
using Microsoft.EntityFrameworkCore.Migrations;

#nullable disable

Expand Down
21 changes: 10 additions & 11 deletions identityserver/HostingExtensions.cs
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,6 @@
using Microsoft.IdentityModel.JsonWebTokens;
using Microsoft.IdentityModel.Logging;
using Serilog;
using System.IdentityModel.Tokens.Jwt;

namespace IdentityServer;

Expand Down Expand Up @@ -39,8 +38,8 @@ public static WebApplication ConfigureServices(this WebApplicationBuilder builde
.AddInMemoryIdentityResources(Config.IdentityResources)
.AddInMemoryApiScopes(Config.ApiScopes)
.AddInMemoryClients(Config.Clients)
.AddAspNetIdentity<ApplicationUser>();
.AddAspNetIdentity<ApplicationUser>();

builder.Services.AddAuthentication()
.AddGoogle(options =>
{
Expand All @@ -54,14 +53,14 @@ public static WebApplication ConfigureServices(this WebApplicationBuilder builde
});

return builder.Build();
}
}

public static WebApplication ConfigurePipeline(this WebApplication app)
{
IdentityModelEventSource.ShowPII = true;
app.UseSerilogRequestLogging();
IdentityModelEventSource.ShowPII = true;

app.UseSerilogRequestLogging();

if (app.Environment.IsDevelopment())
{
app.UseDeveloperExceptionPage();
Expand All @@ -70,8 +69,8 @@ public static WebApplication ConfigurePipeline(this WebApplication app)
app.UseStaticFiles();
app.UseRouting();
app.UseIdentityServer();
app.UseAuthorization();
app.UseAuthorization();

app.MapRazorPages()
.RequireAuthorization();

Expand Down
30 changes: 15 additions & 15 deletions identityserver/Pages/Account/Login/Index.cshtml.cs
Original file line number Diff line number Diff line change
Expand Up @@ -22,11 +22,11 @@ public class Index : PageModel
private readonly IAuthenticationSchemeProvider _schemeProvider;
private readonly IIdentityProviderStore _identityProviderStore;

public ViewModel View { get; set; }
public ViewModel View { get; set; }

[BindProperty]
public InputModel Input { get; set; }
public InputModel Input { get; set; }

public Index(
IIdentityServerInteractionService interaction,
IAuthenticationSchemeProvider schemeProvider,
Expand All @@ -41,21 +41,21 @@ public Index(
_schemeProvider = schemeProvider;
_identityProviderStore = identityProviderStore;
_events = events;
}
}

public async Task<IActionResult> OnGet(string returnUrl)
{
await BuildModelAsync(returnUrl);
await BuildModelAsync(returnUrl);

if (View.IsExternalLoginOnly)
{
// we only have one option for logging in and it's an external provider
return RedirectToPage("/ExternalLogin/Challenge", new { scheme = View.ExternalLoginScheme, returnUrl });
}

return Page();
}
}

public async Task<IActionResult> OnPost()
{
// check if we are in the context of an authorization request
Expand Down Expand Up @@ -125,22 +125,22 @@ public async Task<IActionResult> OnPost()
}
}

await _events.RaiseAsync(new UserLoginFailureEvent(Input.Username, "invalid credentials", clientId:context?.Client.ClientId));
await _events.RaiseAsync(new UserLoginFailureEvent(Input.Username, "invalid credentials", clientId: context?.Client.ClientId));
ModelState.AddModelError(string.Empty, LoginOptions.InvalidCredentialsErrorMessage);
}

// something went wrong, show form with error
await BuildModelAsync(Input.ReturnUrl);
return Page();
}
}

private async Task BuildModelAsync(string returnUrl)
{
Input = new InputModel
{
ReturnUrl = returnUrl
};
};

var context = await _interaction.GetAuthorizationContextAsync(returnUrl);
if (context?.IdP != null && await _schemeProvider.GetSchemeAsync(context.IdP) != null)
{
Expand Down
12 changes: 6 additions & 6 deletions identityserver/Pages/Account/Login/InputModel.cs
Original file line number Diff line number Diff line change
Expand Up @@ -9,13 +9,13 @@ namespace IdentityServer.Pages.Login;
public class InputModel
{
[Required]
public string Username { get; set; }
public string Username { get; set; }

[Required]
public string Password { get; set; }
public bool RememberLogin { get; set; }
public string Password { get; set; }

public bool RememberLogin { get; set; }

public string ReturnUrl { get; set; }

public string Button { get; set; }
Expand Down
4 changes: 2 additions & 2 deletions identityserver/Pages/Account/Login/ViewModel.cs
Original file line number Diff line number Diff line change
Expand Up @@ -12,8 +12,8 @@ public class ViewModel
public IEnumerable<ViewModel.ExternalProvider> VisibleExternalProviders => ExternalProviders.Where(x => !String.IsNullOrWhiteSpace(x.DisplayName));

public bool IsExternalLoginOnly => EnableLocalLogin == false && ExternalProviders?.Count() == 1;
public string ExternalLoginScheme => IsExternalLoginOnly ? ExternalProviders?.SingleOrDefault()?.AuthenticationScheme : null;
public string ExternalLoginScheme => IsExternalLoginOnly ? ExternalProviders?.SingleOrDefault()?.AuthenticationScheme : null;

public class ExternalProvider
{
public string DisplayName { get; set; }
Expand Down
Loading

0 comments on commit e1eb2ee

Please sign in to comment.