2

My code is entering an infinite loop, hitting azure login page (hosted by Microsoft), then redirecting back to my app, then back to ms host login page etc etc etc.

In my code I have a breakpoint in the OnAuthorizationCodeReceived event...

    public void ConfigureAzureAd(IServiceCollection services)
    {
        //set authentication to use Azure AD
        services.AddAuthentication(auth =>
        {                
            auth.DefaultAuthenticateScheme = CookieAuthenticationDefaults.AuthenticationScheme;
            auth.DefaultChallengeScheme = OpenIdConnectDefaults.AuthenticationScheme;
            auth.DefaultSignInScheme = CookieAuthenticationDefaults.AuthenticationScheme;
        })
        .AddCookie()
        .AddOpenIdConnect(opts =>
        {

            Configuration.GetSection("OpenIdConnect").Bind(opts);

            opts.Events = new OpenIdConnectEvents
            {
                OnAuthorizationCodeReceived = async ctx =>
                {
                    HttpRequest request = ctx.HttpContext.Request;
                    //We need to also specify the redirect URL used
                    string currentUri = UriHelper.BuildAbsolute(request.Scheme, request.Host, request.PathBase, request.Path);
                    //Credentials for app itself
                    var credential = new ClientCredential(ctx.Options.ClientId, ctx.Options.ClientSecret);

                    //Construct token cache
                    ITokenCacheFactory cacheFactory = ctx.HttpContext.RequestServices.GetRequiredService<ITokenCacheFactory>();
                    TokenCache cache = cacheFactory.CreateForUser(ctx.Principal);

                    var authContext = new AuthenticationContext(ctx.Options.Authority, cache);

                    //Get token for Microsoft Graph API using the authorization code
                    string resource = "https://graph.microsoft.com";
                    AuthenticationResult result = await authContext.AcquireTokenByAuthorizationCodeAsync(
                        ctx.ProtocolMessage.Code, new Uri(currentUri), credential, resource);

                    //Tell the OIDC middleware we got the tokens, it doesn't need to do anything
                    ctx.HandleCodeRedemption(result.AccessToken, result.IdToken);
                    //ctx.HandleCodeRedemption();
                }
            };
        });
    }

and I can inspect the data in result, and it all looks ok (though not sure what failure would look like), it appears the login is working but my app is unable to recognize that the login has happened, or it's not saving, and keeps retrying

I've also asked someone else to try logging in with a user not in my Active Directory, and it fails appropriately, it really looks like Active Directory is happy, but my app just keeps redirecting.

I'm using .Net Core 2.2 (my first core project)

I'm using Active Directory Free

Update in response to @Marilee Turscak - MSFT

If i do not have the correct Reply Url setup in portal.azure.com and pass in it via C# then azure throws an error, so I've definitely got a reply URL in there and it matches correctly

Config looks like this:

"OpenIdConnect": {
    "ClientId": "<guid in here>", // Application ID
    "ClientSecret": "<secrect from portal.azure.com>",
    "Authority":     "https://login.microsoftonline.com/emailwithout@symbol.onmicrosoft.com/",
    "PostLogoutRedirectUri": "http://www.<projectname_in_here>.local",
    "CallbackPath": "/signin-oidc",
    "ResponseType": "code id_token"
}
ajay_whiz
  • 17,573
  • 4
  • 36
  • 44
Ninjanoel
  • 2,864
  • 4
  • 33
  • 53
  • How is your login process started? If you don't specify a redirect URL in a challenge result, this is the behaviour you would get. – juunas Jan 03 '19 at 17:42

2 Answers2

4

You need to set a Reply URL both in your code and in your application registration in Azure AD. You should set your Reply URL to wherever you want the user to be redirected (generally your main published homepage url - like https://myapp.azurewebsites.net).

For reference, you can see the examples in the Github samples. https://azure.microsoft.com/en-us/resources/samples/active-directory-dotnet-webapp-openidconnect/

Marilee Turscak - MSFT
  • 7,367
  • 3
  • 18
  • 28
  • 1
    There is also a good explanation on the Microsoft Docs regarding setting up authentication to Azure AD: https://learn.microsoft.com/en-us/azure/app-service/configure-authentication-provider-aad – Henrik Stanley Mortensen Jan 03 '19 at 20:18
0

Answering my own question...

I think my issue was somehow related to feature folders. I was implementing custom routing to enable feature folders, but the Azure AD code sets it's own custom route to "/signin-oidc". I came to this conclusion by using Visual Studio to create a new project with Azure Active Directory wizard, got the test project signing-in, but when I ported my old code to the new test project, I got exactly the same error, but in the new "Visual Studio Wizard" there was very little configuration, AND it interfaced with my Azure AD and registered the app and added all the required configuration, so i knew it would before adding the feature folders, and produced exactly the same error behavior after feature folders, so conclude it was something to do with the feature folders custom routing.

Url to the code I found to help implement feature folders if anyone is interested: https://github.com/ardalis/OrganizingAspNetCore/tree/master/CoreFeatureFolders

Ninjanoel
  • 2,864
  • 4
  • 33
  • 53