umbraco / Umbraco-CMS

Umbraco is a free and open source .NET content management system helping you deliver delightful digital experiences.
https://umbraco.com
MIT License
4.37k stars 2.64k forks source link

Error when signing in to Umbraco Backoffice using Azure AD OIDC #16565

Open cvagan opened 1 month ago

cvagan commented 1 month ago

Which Umbraco version are you using? (Please write the exact version, example: 10.1.0)

14.0.0

Bug summary

When attempting to sign in to Umbraco Backoffice using OIDC configured for Azure AD, an OpenIdConnectProtocolException is thrown saying that the OpenIdConnectProtocol requires the jwt token to have an 'iss' claim.

Specifics

Full exception message and trace:

An unhandled exception occurred while processing the request.
OpenIdConnectProtocolException: IDX21314: OpenIdConnectProtocol requires the jwt token to have an 'iss' claim. The jwt did not contain an 'iss' claim, jwt: '[PII of type 'System.IdentityModel.Tokens.Jwt.JwtSecurityToken' is hidden. For more details, see https://aka.ms/IdentityModel/PII.]'.
Microsoft.IdentityModel.Protocols.OpenIdConnect.OpenIdConnectProtocolValidator.ValidateIdToken(OpenIdConnectProtocolValidationContext validationContext)

AuthenticationFailureException: An error was encountered while handling the remote login.
Microsoft.AspNetCore.Authentication.RemoteAuthenticationHandler<TOptions>.HandleRequestAsync()

Stack Query Cookies Headers Routing
OpenIdConnectProtocolException: IDX21314: OpenIdConnectProtocol requires the jwt token to have an 'iss' claim. The jwt did not contain an 'iss' claim, jwt: '[PII of type 'System.IdentityModel.Tokens.Jwt.JwtSecurityToken' is hidden. For more details, see https://aka.ms/IdentityModel/PII.]'.
Microsoft.IdentityModel.Protocols.OpenIdConnect.OpenIdConnectProtocolValidator.ValidateIdToken(OpenIdConnectProtocolValidationContext validationContext)
Microsoft.IdentityModel.Protocols.OpenIdConnect.OpenIdConnectProtocolValidator.ValidateTokenResponse(OpenIdConnectProtocolValidationContext validationContext)
Microsoft.AspNetCore.Authentication.OpenIdConnect.OpenIdConnectHandler.HandleRemoteAuthenticateAsync()

Show raw exception details
AuthenticationFailureException: An error was encountered while handling the remote login.
Microsoft.AspNetCore.Authentication.RemoteAuthenticationHandler<TOptions>.HandleRequestAsync()
Microsoft.AspNetCore.Authentication.AuthenticationMiddleware.Invoke(HttpContext context)
StackExchange.Profiling.MiniProfilerMiddleware.Invoke(HttpContext context) in MiniProfilerMiddleware.cs
Umbraco.Cms.Web.Common.Middleware.UmbracoRequestMiddleware.InvokeAsync(HttpContext context, RequestDelegate next)
Umbraco.Cms.Web.Common.Middleware.UmbracoRequestMiddleware.InvokeAsync(HttpContext context, RequestDelegate next)
Microsoft.AspNetCore.Builder.UseMiddlewareExtensions+InterfaceMiddlewareBinder+<>c__DisplayClass2_0+<<CreateMiddleware>b__0>d.MoveNext()
Umbraco.Cms.Web.Common.Middleware.PreviewAuthenticationMiddleware.InvokeAsync(HttpContext context, RequestDelegate next)
Microsoft.AspNetCore.Builder.UseMiddlewareExtensions+InterfaceMiddlewareBinder+<>c__DisplayClass2_0+<<CreateMiddleware>b__0>d.MoveNext()
Umbraco.Cms.Web.Common.Middleware.UmbracoRequestLoggingMiddleware.InvokeAsync(HttpContext context, RequestDelegate next)
Microsoft.AspNetCore.Builder.UseMiddlewareExtensions+InterfaceMiddlewareBinder+<>c__DisplayClass2_0+<<CreateMiddleware>b__0>d.MoveNext()
SixLabors.ImageSharp.Web.Middleware.ImageSharpMiddleware.Invoke(HttpContext httpContext, bool retry)
Umbraco.Cms.Api.Management.Middleware.BackOfficeAuthorizationInitializationMiddleware.InvokeAsync(HttpContext context, RequestDelegate next)
Microsoft.AspNetCore.Builder.UseMiddlewareExtensions+InterfaceMiddlewareBinder+<>c__DisplayClass2_0+<<CreateMiddleware>b__0>d.MoveNext()
Microsoft.AspNetCore.Diagnostics.DeveloperExceptionPageMiddlewareImpl.Invoke(HttpContext context)

The external login is configured like this: image

Debugging the OnTokenValidated event shows that the claim is included in the token response from Azure: image

But the claim is not present in the validated SecurityToken, which leads me to believe that the iss claim (among others) is not being mapped properly: image

This problem was first encountered on a project that was upgraded to v14.0.0 from v13.3.0, but was also replicated on a fresh v14.0.0 installation.

The project is using the Microsoft.AspNetCore.Authentication.OpenIdConnect package version 8.0.6. Downgrading to older versions such as 8.0.2 made did not solve the issue. Version 8.0.6 was also tested on Umbraco v13.3.0 was also found to be working as intended.

Steps to reproduce

Install Nuget Package "Microsoft.AspNetCore.Authentication.OpenIdConnect" 8.0.6

Use the following configuration in Program.cs:

builder.CreateUmbracoBuilder()
    .AddBackOffice()
    .AddBackOfficeExternalLogins(loginsBuilder =>
                loginsBuilder.AddBackOfficeLogin(authBuilder =>
                    authBuilder.AddOpenIdConnect(BackOfficeAuthenticationBuilder.SchemeForBackOffice("oidc")!, "Azure AD", options =>
                    {
                        options.Authority = "https://login.microsoftonline.com/<tenantId>";
                        options.ClientId = "<clientId>";
                        options.ClientSecret = "<clientSecret>";
                        options.CallbackPath = "/signin-oidc";
                        options.ResponseType = "code";
                        options.ResponseMode = "query";
                        options.UsePkce = true;

                        options.Scope.Add("email");
                        options.GetClaimsFromUserInfoEndpoint = true;
                    }),
                    providerOptions =>
                    {
                        providerOptions.DenyLocalLogin = false;
                        providerOptions.AutoLinkOptions = new ExternalSignInAutoLinkOptions(
                            autoLinkExternalAccount: true,
                            defaultUserGroups: new[] { Constants.Security.AdminGroupAlias },
                            defaultCulture: "nb-NO")
                        {
                            OnAutoLinking = (autoLinkUser, loginInfo) =>
                            {
                                autoLinkUser.IsApproved = true;
                            }
                        };
                    }))
    .AddWebsite()
    .AddDeliveryApi()
    .AddComposers()
    .Build();

(This also requires an Enterprise app with the proper configuration in Azure.)

Add the following to /App_Plugins/ExternalLoginProviders/umbraco-package.json

{
  "$schema": "../../umbraco-package-schema.json",
  "name": "Company name",
  "allowPublicAccess": true,
  "extensions": [
    {
      "type": "authProvider",
      "alias": "My.AuthProvider.AzureAD",
      "name": "My Auth Provider",
      "forProviderName": "Umbraco.oidc",
      "meta": {
        "label": "Generic",
        "defaultView": {
          "icon": "icon-cloud"
        },
        "behavior": {
          "autoRedirect": false
        },
        "linking": {
          "allowManualLinking": true
        }
      }
    }
  ]
}

Run the solution, go to /umbraco and choose the external login option.

Expected result / actual result

Expected result: User is authenticated and is granted access to Umbraco Backoffice

Actual result: OpenIdConnectProtocolException exception occurs saying that the jwt token is missing the required 'iss' claim.

github-actions[bot] commented 1 month ago

Hi there @cvagan!

Firstly, a big thank you for raising this issue. Every piece of feedback we receive helps us to make Umbraco better.

We really appreciate your patience while we wait for our team to have a look at this but we wanted to let you know that we see this and share with you the plan for what comes next.

We wish we could work with everyone directly and assess your issue immediately but we're in the fortunate position of having lots of contributions to work with and only a few humans who are able to do it. We are making progress though and in the meantime, we will keep you in the loop and let you know when we have any questions.

Thanks, from your friendly Umbraco GitHub bot :robot: :slightly_smiling_face:

benedict-odonovan commented 1 month ago

Potentially found the problem? My version of Microsoft.IdentityModel.Protocols.OpenIdConnect package was different to the other IdentityModel packages (7.5.1). This was causing the ConfigurationManager to not deserialize OpenID configurations correctly.

I managed to solve it by manually updating Microsoft.IdentityModel.Protocols.OpenIdConnect to 7.5.1.

See here and the IdentityServer mention for another project having a similar issue.

tobias-johansson-nltg commented 4 days ago

Potentially found the problem? My version of Microsoft.IdentityModel.Protocols.OpenIdConnect package was different to the other IdentityModel packages (7.5.1). This was causing the ConfigurationManager to not deserialize OpenID configurations correctly.

I managed to solve it by manually updating Microsoft.IdentityModel.Protocols.OpenIdConnect to 7.5.1.

See here and the IdentityServer mention for another project having a similar issue.

I just want to say thank you for this. Explicitly installing a newer version of Microsoft.IdentityModel.Protocols.OpenIdConnect solved this problem for us! We had the same problem as in the original post (claims came back correctly, but were not mapped to the SecurityToken) and this solved the problem :)