Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat: support WWW-Authenticate #314

Merged
merged 1 commit into from
Oct 29, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
5 changes: 5 additions & 0 deletions charts/oidc-guard/values.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -119,6 +119,11 @@ settings:
# - https://login.microsoftonline.com/{TenantId}/v2.0
# - https://sts.windows.net/{TenantId}/

# Appends data to the WWW-Authenticate Header
# example: key=value, key2=value2
# https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/WWW-Authenticate
appendToWWWAuthenticateHeader: ""

serviceAccount:
# Specifies whether a service account should be created
create: true
Expand Down
55 changes: 45 additions & 10 deletions src/oidc-guard/Program.cs
Original file line number Diff line number Diff line change
Expand Up @@ -7,13 +7,15 @@
using Microsoft.AspNetCore.HttpOverrides;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.WebUtilities;
using Microsoft.Extensions.Options;
using Microsoft.Extensions.Primitives;
using Microsoft.IdentityModel.Protocols;
using Microsoft.IdentityModel.Protocols.OpenIdConnect;
using Microsoft.Net.Http.Headers;
using oidc_guard.Services;
using OpenTelemetry.Metrics;
using OpenTelemetry.Resources;
using System.Text;
using System.Text.Json.Nodes;
using System.Text.Json.Serialization;
using System.Text.RegularExpressions;
Expand Down Expand Up @@ -176,6 +178,17 @@
o.TokenValidationParameters.ValidIssuers = settings.JWT.ValidIssuers;
o.MapInboundClaims = false;
});

if (!string.IsNullOrEmpty(settings.JWT.AppendToWWWAuthenticateHeader))
{
builder.Services.Configure<JwtBearerOptions>(x =>
{
// Only add a comma after the first param, if any
var spacing = x.Challenge.IndexOf(' ') > 0 ? ", " : " ";

x.Challenge = x.Challenge + spacing + settings.JWT.AppendToWWWAuthenticateHeader;
});
}
}

builder.Services.AddHttpLogging(logging =>
Expand All @@ -199,6 +212,8 @@
logging.RequestHeaders.Add(HeaderNames.Origin);
logging.RequestHeaders.Add(HeaderNames.AccessControlRequestMethod);
logging.RequestHeaders.Add(HeaderNames.AccessControlRequestHeaders);

logging.ResponseHeaders.Add(HeaderNames.WWWAuthenticate);
});

builder.Services.AddAuthorization();
Expand Down Expand Up @@ -268,7 +283,7 @@
app.MapGet("/userinfo", (HttpContext httpContext) => httpContext.User.Claims.GroupBy(x => x.Type).ToDictionary(x => x.Key, y => y.Count() > 1 ? (object)y.Select(x => x.Value) : y.First().Value))
.RequireAuthorization();

app.MapGet("/auth", ([FromServices] Settings settings, [FromServices] Instrumentation meters, HttpContext httpContext) =>
app.MapGet("/auth", ([FromServices] Settings settings, [FromServices] Instrumentation meters, [FromServices] IOptionsMonitor<JwtBearerOptions> options, HttpContext httpContext) =>
{
meters.SignInCounter.Add(1);

Expand All @@ -294,7 +309,7 @@
{
foreach (var item in skipEquals)
{
var commaIndex = item.IndexOf(',');

Check warning on line 312 in src/oidc-guard/Program.cs

View workflow job for this annotation

GitHub Actions / Build & Test

Dereference of a possibly null reference.

Check warning on line 312 in src/oidc-guard/Program.cs

View workflow job for this annotation

GitHub Actions / Build & Test

Dereference of a possibly null reference.
if (commaIndex != -1)
{
var method = item[..commaIndex];
Expand All @@ -321,7 +336,7 @@
{
foreach (var item in skipNotEquals)
{
var commaIndex = item.IndexOf(',');

Check warning on line 339 in src/oidc-guard/Program.cs

View workflow job for this annotation

GitHub Actions / Build & Test

Dereference of a possibly null reference.

Check warning on line 339 in src/oidc-guard/Program.cs

View workflow job for this annotation

GitHub Actions / Build & Test

Dereference of a possibly null reference.
if (commaIndex != -1)
{
var method = item[..commaIndex];
Expand Down Expand Up @@ -360,11 +375,9 @@

return Results.Challenge(new AuthenticationProperties { RedirectUri = redirect });
}

return Results.Unauthorized();
}

return Results.Unauthorized();
return UnauthorizedResults(httpContext, options);
}

// Validate based on rules
Expand Down Expand Up @@ -469,13 +482,9 @@

return Results.Challenge(new AuthenticationProperties { RedirectUri = redirect });
}

return Results.Unauthorized();
}
else
{
return Results.Unauthorized();
}

return UnauthorizedResults(httpContext, options, "Missing Claim " + item.ToString());
}
}
}
Expand Down Expand Up @@ -512,6 +521,32 @@
app.Run();
}

private static IResult UnauthorizedResults(HttpContext context, IOptionsMonitor<JwtBearerOptions> options, string? errorDescription = null)
{
// https://tools.ietf.org/html/rfc6750#section-3.1
// WWW-Authenticate: Bearer error="invalid_token", error_description="The access token expired"
var builder = new StringBuilder(options.CurrentValue.Challenge);

if (options.CurrentValue.Challenge.IndexOf(' ') > 0)
{
// Only add a comma after the first param, if any
builder.Append(',');
}

builder.Append(" error=\"invalid_token\"");

if (!string.IsNullOrEmpty(errorDescription))
{
builder.Append(", error_description=\"");
builder.Append(errorDescription);
builder.Append('\"');
}

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

return Results.Unauthorized();
}

private static string? GetOriginalUrl(HttpContext httpContext)
{
if (httpContext.Request.Headers.TryGetValue(CustomHeaderNames.XOriginalUrl, out var xOriginalUrl))
Expand Down
1 change: 1 addition & 0 deletions src/oidc-guard/Settings.cs
Original file line number Diff line number Diff line change
Expand Up @@ -38,4 +38,5 @@ public class JWTAuthSettings
public string[]? ValidIssuers { get; set; }
public string? JWKSUrl { get; set; }
public bool PrependBearer { get; set; }
public string? AppendToWWWAuthenticateHeader { get; set; }
}
Loading
Loading