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

configure openid connect #809

Merged
merged 17 commits into from
May 28, 2024
Merged
Show file tree
Hide file tree
Changes from 13 commits
Commits
Show all changes
17 commits
Select commit Hold shift + click to select a range
8bb01b1
attempt to add openid connect support
hahn-kev May 15, 2024
906d2a2
update dotnet ef tool version
hahn-kev May 16, 2024
347cebb
disable openId in production using a config option. This lets us figu…
hahn-kev May 16, 2024
79a028c
fix redirect loop trying to send the user to the login page, if that'…
hahn-kev May 16, 2024
b37c112
trim down claims check list since most aren't used, allow name claim …
hahn-kev May 16, 2024
6d2909c
correct vite proxy to send traces to the collector and not dotnet.
hahn-kev May 16, 2024
c348d2b
configure the login page to handle return urls
hahn-kev May 16, 2024
493dce6
allow application manager to be null in seeding data to allow for cas…
hahn-kev May 17, 2024
c189fb9
Merge branch 'refs/heads/develop' into chore/openid-connect
hahn-kev May 17, 2024
c01cebc
require pkce and disable implicit flow, enable oauth to work over htt…
hahn-kev May 20, 2024
a318639
create approval flow for oauth login
hahn-kev May 20, 2024
22e8864
correct vite proxy so https isn't used incorrectly when the backend r…
hahn-kev May 20, 2024
d4940a6
pass redirect uri along via google login, fix bug where redirect url …
hahn-kev May 21, 2024
c475d7b
Merge remote-tracking branch 'origin/develop' into chore/openid-connect
myieye May 28, 2024
dd593df
Redesign authorize page
myieye May 28, 2024
040eac8
Merge branch 'refs/heads/develop' into chore/openid-connect
hahn-kev May 28, 2024
aabb651
extract oauth code out of LoginController.cs and into OauthController…
hahn-kev May 28, 2024
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
2 changes: 1 addition & 1 deletion .config/dotnet-tools.json
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@
"isRoot": true,
"tools": {
"dotnet-ef": {
"version": "7.0.10",
"version": "8.0.5",
"commands": [
"dotnet-ef"
]
Expand Down
2 changes: 2 additions & 0 deletions .idea/.idea.LexBox/.idea/.gitignore

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

57 changes: 39 additions & 18 deletions .idea/.idea.LexBox/.idea/dataSources.xml

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

3 changes: 2 additions & 1 deletion .idea/.idea.LexBox/.idea/indexLayout.xml

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

3 changes: 2 additions & 1 deletion .idea/.idea.LexBox/.idea/vcs.xml

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

78 changes: 74 additions & 4 deletions backend/LexBoxApi/Auth/AuthKernel.cs
Original file line number Diff line number Diff line change
Expand Up @@ -5,12 +5,14 @@
using LexBoxApi.Auth.Requirements;
using LexBoxApi.Controllers;
using LexCore.Auth;
using LexData;
using Microsoft.AspNetCore.Authentication.Cookies;
using Microsoft.AspNetCore.Authentication.JwtBearer;
using Microsoft.AspNetCore.Authorization;
using Microsoft.Extensions.Options;
using Microsoft.IdentityModel.Logging;
using Microsoft.OpenApi.Models;
using OpenIddict.Validation.AspNetCore;

namespace LexBoxApi.Auth;

Expand Down Expand Up @@ -66,6 +68,8 @@ public static void AddLexBoxAuth(IServiceCollection services,
.BindConfiguration("Authentication:Jwt")
.ValidateDataAnnotations()
.ValidateOnStart();
services.AddOptions<OpenIdOptions>()
.BindConfiguration("Authentication:OpenId");
services.AddAuthentication(options =>
{
options.DefaultScheme = DefaultScheme;
Expand All @@ -78,7 +82,13 @@ public static void AddLexBoxAuth(IServiceCollection services,
{
options.ForwardDefaultSelector = context =>
{

if (context.Request.Headers.ContainsKey("Authorization") &&
context.Request.Headers.Authorization.ToString().StartsWith("Bearer") &&
context.RequestServices.GetService<IOptions<OpenIdOptions>>()?.Value.Enable == true)
{
//fow now this will use oauth
return OpenIddictValidationAspNetCoreDefaults.AuthenticationScheme;
}
if (context.Request.IsJwtRequest())
{
return JwtBearerDefaults.AuthenticationScheme;
Expand All @@ -101,9 +111,9 @@ public static void AddLexBoxAuth(IServiceCollection services,
.AddCookie(options =>
{
configuration.Bind("Authentication:Cookie", options);
options.LoginPath = "/api/login";
options.LoginPath = "/login";
options.Cookie.Name = AuthCookieName;
options.ForwardChallenge = JwtBearerDefaults.AuthenticationScheme;
// options.ForwardChallenge = JwtBearerDefaults.AuthenticationScheme;
options.ForwardForbid = JwtBearerDefaults.AuthenticationScheme;
})
.AddJwtBearer(options =>
Expand Down Expand Up @@ -152,7 +162,8 @@ public static void AddLexBoxAuth(IServiceCollection services,
context.HandleResponse();
var loginController = context.HttpContext.RequestServices.GetRequiredService<LoginController>();
loginController.ControllerContext.HttpContext = context.HttpContext;
var redirectTo = await loginController.CompleteGoogleLogin(context.Principal, context.Properties?.RedirectUri);
//using context.ReturnUri and not context.Properties.RedirectUri because the latter is null
var redirectTo = await loginController.CompleteGoogleLogin(context.Principal, context.ReturnUri);
context.HttpContext.Response.Redirect(redirectTo);
};
});
Expand Down Expand Up @@ -185,6 +196,65 @@ public static void AddLexBoxAuth(IServiceCollection services,
}
});
});

var openIdOptions = configuration.GetSection("Authentication:OpenId").Get<OpenIdOptions>();
if (openIdOptions?.Enable == true) AddOpenId(services, environment);
}

private static void AddOpenId(IServiceCollection services, IWebHostEnvironment environment)
{
services.Add(ScopeRequestFixer.Descriptor.ServiceDescriptor);

//openid server
services.AddOpenIddict()
.AddCore(options =>
{
options.UseEntityFrameworkCore().UseDbContext<LexBoxDbContext>();
options.UseQuartz();
})
.AddServer(options =>
{
options.RegisterScopes("openid", "profile", "email");
options.RegisterClaims("aud", "email", "exp", "iss", "iat", "sub", "name");
hahn-kev marked this conversation as resolved.
Show resolved Hide resolved
options.SetAuthorizationEndpointUris("api/login/open-id-auth");
options.SetTokenEndpointUris("api/login/token");
options.SetIntrospectionEndpointUris("api/connect/introspect");
options.SetUserinfoEndpointUris("api/connect/userinfo");
options.Configure(serverOptions => serverOptions.Handlers.Add(ScopeRequestFixer.Descriptor));

options.AllowAuthorizationCodeFlow()
.AllowRefreshTokenFlow();

options.RequireProofKeyForCodeExchange();//best practice to use PKCE with auth code flow and no implicit flow

options.IgnoreResponseTypePermissions();
options.IgnoreScopePermissions();
if (environment.IsDevelopment())
{
options.AddDevelopmentEncryptionCertificate();
options.AddDevelopmentSigningCertificate();
}
else
{
//see docs: https://documentation.openiddict.com/configuration/encryption-and-signing-credentials.html
throw new NotImplementedException("need to implement loading keys from a file");
}

var aspnetCoreBuilder = options.UseAspNetCore()
.EnableAuthorizationEndpointPassthrough()
.EnableTokenEndpointPassthrough();
if (environment.IsDevelopment())
{
aspnetCoreBuilder.DisableTransportSecurityRequirement();
}
})
.AddValidation(options =>
{
options.UseLocalServer();
options.UseAspNetCore();
options.AddAudiences(Enum.GetValues<LexboxAudience>().Where(a => a != LexboxAudience.Unknown).Select(a => a.ToString()).ToArray());
options.EnableAuthorizationEntryValidation();
});
}

public static AuthorizationPolicyBuilder RequireDefaultLexboxAuth(this AuthorizationPolicyBuilder builder)
Expand Down
9 changes: 9 additions & 0 deletions backend/LexBoxApi/Auth/OpenIdOptions.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
using System.ComponentModel.DataAnnotations;

namespace LexBoxApi.Auth;

public class OpenIdOptions
{
[Required]
public required bool Enable { get; set; }
}
28 changes: 28 additions & 0 deletions backend/LexBoxApi/Auth/ScopeRequestFixer.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,28 @@
using OpenIddict.Abstractions;
using OpenIddict.Server;

namespace LexBoxApi.Auth;

/// <summary>
/// the MSAL library makes requests with the scope parameter, which is invalid, this attempts to remove the scope before it's rejected
/// </summary>
public sealed class ScopeRequestFixer : IOpenIddictServerHandler<OpenIddictServerEvents.ValidateTokenRequestContext>
{
public static OpenIddictServerHandlerDescriptor Descriptor { get; }
= OpenIddictServerHandlerDescriptor.CreateBuilder<OpenIddictServerEvents.ValidateTokenRequestContext>()
.UseSingletonHandler<ScopeRequestFixer>()
.SetOrder(OpenIddictServerHandlers.Exchange.ValidateResourceOwnerCredentialsParameters.Descriptor.Order + 1)
.SetType(OpenIddictServerHandlerType.Custom)
.Build();

public ValueTask HandleAsync(OpenIddictServerEvents.ValidateTokenRequestContext context)
{
if (!string.IsNullOrEmpty(context.Request.Scope) && (context.Request.IsAuthorizationCodeGrantType() ||
context.Request.IsDeviceCodeGrantType()))
{
context.Request.Scope = null;
}

return default;
}
}
Loading
Loading