IdentityServer4 icon indicating copy to clipboard operation
IdentityServer4 copied to clipboard

Issues when implementing local identity and Azure Ad

Open DanielClausen opened this issue 6 years ago • 8 comments

I have an Identity server set up to authenticate internal business users via Azure AD and external customers via ASP.Net core Identity. It appeared to work fine at first but then I noticed that silent renew wasn't working in the client applications when logged in via Azure AD.

I discovered if I changed the AddAuthentication line to specify a default authentication scheme like so: services.AddAuthentication(x => x.DefaultAuthenticateScheme = IdentityServerConstants.DefaultCookieAuthenticationScheme) that it would fix the silent renew error.

However once I made that change asp.net core identity login no longer works and users logging in via identity gets continually redirected to the login page. At this point I feel like I've tried a billion different things and I just keep going in a loop. I can fix one problem but then the other returns and visa versa.

Here is the relevant section of my startup.cs file:

            services.AddIdentityServer(options =>
            {
                options.Authentication.CookieLifetime = new TimeSpan(1, 2, 3, 0);
                options.Authentication.CookieSlidingExpiration = true;
            })
                .AddSigningCredential(identCert)
                 .AddConfigurationStore(options =>
                 {
                     options.ConfigureDbContext = builder =>
                         builder.UseSqlServer(Configuration.GetConnectionString("IdentityDbConnection"),
                             sql => sql.MigrationsAssembly(migrationsAssembly));
                 })
                .AddAspNetIdentity<CmrUser>();

            services.AddAuthentication(x => x.DefaultAuthenticateScheme = IdentityServerConstants.DefaultCookieAuthenticationScheme)
                    .AddAzureAD(ExternalAuth.cmrAadProvider, AzureADDefaults.OpenIdScheme, AzureADDefaults.CookieScheme, "CMR AAD", options => Configuration.Bind("AzureAd", options));

            services.Configure<OpenIdConnectOptions>(AzureADDefaults.OpenIdScheme, options =>
            {
                options.SignInScheme = "Identity.External";
                options.ResponseType = OpenIdConnectResponseType.CodeIdToken;
                options.Authority = options.Authority + "/v2.0/"; // Microsoft identity platform

                options.TokenValidationParameters.ValidateIssuer = true;
                options.TokenValidationParameters.NameClaimType = "preferred_username";

                options.Scope.Add("email");
                options.Scope.Add("offline_access");
                options.Scope.Add("profile");
                options.Scope.Add("openid");

                options.Events.OnRedirectToIdentityProvider = context =>
                {
                    var login = context.Properties.GetParameter<string>(OpenIdConnectParameterNames.LoginHint);
                    if (!string.IsNullOrWhiteSpace(login))
                    {
                        context.ProtocolMessage.LoginHint = login;
                        context.ProtocolMessage.DomainHint = context.Properties.GetParameter<string>(
                            OpenIdConnectParameterNames.DomainHint);

                        // delete the login_hint and domainHint from the Properties when we are done otherwise
                        // it will take up extra space in the cookie.
                        context.Properties.Parameters.Remove(OpenIdConnectParameterNames.LoginHint);
                        context.Properties.Parameters.Remove(OpenIdConnectParameterNames.DomainHint);
                    }

                    // Additional claims
                    if (context.Properties.Items.ContainsKey("claims"))
                    {
                        context.ProtocolMessage.SetParameter("claims",
                            context.Properties.Items["claims"]);
                    }

                    return Task.FromResult(0);
                };

                var handler = options.Events.OnAuthorizationCodeReceived;
                options.Events.OnAuthorizationCodeReceived = async context =>
                {
                    var tokenAcquisition = context.HttpContext.RequestServices.GetRequiredService<ITokenAcquisition>();
                    await tokenAcquisition.AddAccountToCacheFromAuthorizationCodeAsync(context, options.Scope).ConfigureAwait(false);
                    await handler(context).ConfigureAwait(false);
                };

                // Handling the sign-out: removing the account from MSAL.NET cache
                options.Events.OnRedirectToIdentityProviderForSignOut = async context =>
                {
                    // Remove the account from MSAL.NET token cache
                    var tokenAcquisition = context.HttpContext.RequestServices.GetRequiredService<ITokenAcquisition>();
                    await tokenAcquisition.RemoveAccountAsync(context).ConfigureAwait(false);
                };
            })
            .AddInMemoryTokenCaches();

DanielClausen avatar Jan 03 '20 14:01 DanielClausen

It appeared to work fine at first but then I noticed that silent renew wasn't working in the client applications when logged in via Azure AD.

I don't understand this comment. After authentication there is no difference between the two use cases from our point of view. You'd need to investigate more, what the difference is between the two scenarios (like on the wire).

leastprivilege avatar Jan 05 '20 17:01 leastprivilege

We have seen issues with OpenIdConnect using IdentityModel with a constant redirect loop, which we tracked back to KB4530689 (Windows Server 2016). If you have this installed, try uninstalling this and rebooting your server and see if the problem goes away.

We're still trying to identify a fix for this, so if you come up with an answer please post; we'll do the same if we work it out.

@leastprivilege I found a post here which led me down this path. Will update if I find anything further, but I'd be surprised if more of these issues don't pop up. Because the update related to the KB seems to have nothing directly to do with identity it could be hard to identify.

malcartwright avatar Jan 07 '20 02:01 malcartwright

Hello @malcartwright is there anyone one from Microsoft working on this one?

ghost avatar Jan 17 '20 07:01 ghost

@leastprivilege Sorry for the delay getting back to this, it's been difficult finding time to test and go through the trace logs as you suggested.

Scenario 1: Using services.AddAuthentication(x => x.DefaultAuthenticateScheme = IdentityServerConstants.DefaultCookieAuthenticationScheme)

Local Asp.Net Core Identity Login (Constant Login Redirect)

- Post to Account/Login:
    - Set-Cookie: .AspNetCore.Identity.Application=********************** path=/; secure; samesite=none; httponly
- GET Connect/Authorize:
  - Log "Showing login: User is not authenticated"
  - 302 Redirect back to Account/Login

External Login via Azure Ad (works)

- GET /External/Challenge?
- login.microsoft.com GET /{tenentId}/oauth2/v2.0/authorize?client_id={clientId}&redirect_uri=https%3A%2F%2Flocalhost%3A44315%2Fsignin-oidc&response_type=code%20id_token&scope=openid%20profile%20email%20offline_access&response_mode=form_post&nonce=**********************&x-client-SKU=ID_NETSTANDARD2_0&x-client-ver=5.5.0.0 HTTP/1.1
- POST /signin-oidc
    - Set-Cookie: .AspNetCore.Correlation.AzureADOpenID.**********************; expires=Thu, 01 Jan 1970 00:00:00 GMT; path=/signin-oidc; secure; samesite=none; httponly
    - Set-Cookie: .AspNetCore.OpenIdConnect.Nonce.**********************; expires=Thu, 01 Jan 1970 00:00:00 GMT; path=/signin-oidc; secure; samesite=none; httponly
    - Set-Cookie: Identity.External=**********************; path=/; secure; samesite=none; httponly
- /External/Callback
    - Set-Cookie: Identity.External=; expires=Thu, 01 Jan 1970 00:00:00 GMT; path=/; secure; samesite=none; httponly
    - Set-Cookie: idsrv=**********************; expires=Mon, 20 Jan 2020 17:53:23 GMT; path=/; secure; samesite=none; httponly
    - Set-Cookie: idsrv.session=6PQ9MaOKRcPd7oMJ5tOhAg; path=/; secure; samesite=none
- connect/authorize:
    - Set-Cookie: idsrv=**********************; expires=Mon, 20 Jan 2020 17:53:23 GMT; path=/; secure; samesite=none; httponly

Scenario 2: Using services.AddAuthentication(IISDefaults.AuthenticationScheme)

Local Asp.Net Core Identity (Works)

- POST to Account/Login:
    - Set-Cookie: .AspNetCore.Identity.Application=**********************; path=/; secure; samesite=none; httponly
    - Set-Cookie: idsrv.session=C3MeEV4DlWGR-X80eQK9eg; path=/; secure; samesite=none
- GET /connect/authorize/Callback
    - Set-Cookie: .AspNetCore.Identity.Application=**********************; path=/; secure; samesite=none; httponly
Silent Renew
- GET /connect/authorize?client_id=inflow-client&redirect_uri=http%3A%2F%2Flocalhost%3A3000%2Fsilent-renew&response_type=token%20id_token&scope=openid%20profile%20cmr.profile%20inflow-api%20inflow-profile&state=**********************&prompt=none&id_token_hint=********************** HTTP/1.1
    - Cookie: .AspNetCore.Antiforgery.7vdWcyBRA-Q=**********************
                idsrv.session=C3MeEV4DlWGR-X80eQK9eg; 
                .AspNetCore.Identity.Application=**********************
    - 302 client/silent_rewnew#id_token = ******

External Login via Azure Ad (Silent Renew Doesn't work)

- GET /External/Challenge
    - Set-Cookie: .AspNetCore.Correlation.AzureADOpenID.**********************; expires=Sun, 19 Jan 2020 16:34:09 GMT; path=/signin-oidc; secure; samesite=none; httponly
    - Set-Cookie: .AspNetCore.OpenIdConnect.Nonce.**********************; expires=Sun, 19 Jan 2020 16:34:09 GMT; path=/signin-oidc; secure; samesite=none; httponly
- login.microsoft.com GET /{tenent_id}/oauth2/v2.0/authorize?client_id={client_id}
    - Set-Cookie: SignInStateCookie=**********************; path=/; secure; HttpOnly; SameSite=None
- POST /signin-oidc
    - Set-Cookie: .AspNetCore.Correlation.AzureADOpenID.**********************; expires=Thu, 01 Jan 1970 00:00:00 GMT; path=/signin-oidc; secure; samesite=none; httponly
    - Set-Cookie: .AspNetCore.OpenIdConnect.Nonce.**********************; expires=Thu, 01 Jan 1970 00:00:00 GMT; path=/signin-oidc; secure; samesite=none; httponly
    - Set-Cookie: idsrv.external=**********************; path=/; secure; samesite=none; httponly
- GET External/Callback
    - Set-Cookie: .AspNetCore.Identity.Application=**********************; expires=Sun, 02 Feb 2020 17:34:48 GMT; path=/; secure; samesite=none; httponly
    - Set-Cookie: idsrv.external=; expires=Thu, 01 Jan 1970 00:00:00 GMT; path=/; secure; samesite=none; httponly
    - Set-Cookie: idsrv.session=l7XVPipRmh6D5eDeI-SqJg; path=/; secure; samesite=none
- GET /connect/authorize/callback
    - Set-Cookie: .AspNetCore.Identity.Application=**********************; expires=Sun, 02 Feb 2020 17:34:48 GMT; path=/; secure; samesite=none; httponly
Silent Renew
- GET /connect/authorize?client_id=inflow-client&redirect_uri=http%3A%2F%2Flocalhost%3A3000%2Fsilent-renew&response_type=token%20id_token&scope=openid%20profile%20cmr.profile%20inflow-api%20inflow-profile&state=d3519aedea074bfba3a5b897a84c52b8&nonce=3b3a8ca461aa47af9622c7d7cb2e1286&prompt=none&id_token_hint=********************** HTTP/1.1
    - Logs show "Showing login: User is not authenticated"
    - Cookie: .AspNetCore.Antiforgery.**********************;
                idsrv.session=l7XVPipRmh6D5eDeI-SqJg; 
                .AspNetCore.Identity.Application=**********************;
    - 302 #error = login_required

I noticed that for the local login in Scenario 1 the idsvr.session cookie isn't being set. I'm guessing this could be the cause of the redirect loop?

I'm still stumped as to why the silent renew doesn't work for the external login in Scenario 2. The cookie names are different but they are being passed around the same so I'm not sure it should matter. Also curiously the dates on the cookies are different but they are both valid so again that shouldn't seem to matter here.

DanielClausen avatar Jan 19 '20 19:01 DanielClausen

Hello @malcartwright is there anyone one from Microsoft working on this one?

Hi @Preeti5233, I'm not aware of anyone working on this. We can't explain why uninstalling that KB worked but it did. The client who had the problem was using an ADFS setup. Perhaps the update included something to deal with the upcoming Chrome 80 changes to cookies?

malcartwright avatar Jan 19 '20 22:01 malcartwright

@leastprivilege I can reproduce this issue using the IdentityServer 4 Demo Project.

If I take that project, plug in my Azure AD Config and run, everything works as expected. If I add EF to the project, login via Azure, wait an hour, then refresh it will expire my cookies.

The only change I made to implement AspNetIdentity was to add the following packages:

  • Microsoft.AspNetCore.Identity.EntityFrameworkCore
  • IdentityServer4.AspNetIdentity
  • Microsoft.EntityFrameworkCore.SqlServer

Then in the Startup.cs add:

services.AddDbContext<TestIdentityDbContext>(options =>
                options.UseSqlServer(
                    Configuration.GetConnectionString("IdentityDbConnection")));
            
services.AddIdentity<TestUser, IdentityRole>()
                .AddEntityFrameworkStores<TestIdentityDbContext>()
                .AddDefaultTokenProviders();

And change AddIdentityServer to use AspNetIdentity:

services.AddIdentityServer(options =>
            {
                options.Events.RaiseErrorEvents = true;
                options.Events.RaiseFailureEvents = true;
                options.Events.RaiseInformationEvents = true;
                options.Events.RaiseSuccessEvents = true;
            })
               .AddInMemoryApiResources(Config.GetApis())
                .AddInMemoryIdentityResources(Config.GetIdentityResources())
                .AddInMemoryClients(Config.GetClients())
                .AddAspNetIdentity<TestUser>()
                .AddDeveloperSigningCredential(persistKey: false);

With those few changes the you can login to Azure AD, wait an hour, refresh, and watch as the cookies are set to expire. Login with an Identity User and the cookies will remain as long as the session is active.

DanielClausen avatar Jan 28 '20 14:01 DanielClausen

This issue has been automatically marked as stale because it has not had recent activity. It will be closed if no further activity occurs. Questions are community supported only and the authors/maintainers may or may not have time to reply. If you or your company would like commercial support, please see here for more information.

stale[bot] avatar Feb 11 '20 14:02 stale[bot]

This thread has been automatically locked since there has not been any recent activity after it was closed. Please open a new issue for related bugs.

lock[bot] avatar Mar 21 '20 20:03 lock[bot]