JP Gutton
JP Gutton

Reputation: 123

Issue with logout on Azure AD B2C and ASP.NET Core

I am playing with ASP.NET Core and Azure AD B2C, when using the code sample from GitHub (active-directory-dotnet-webapp-openidconnect-aspnetcore-b2c) the logoff part does not work. in the Account Controller

        [HttpGet]
    public async Task LogOff()
    {
        if (HttpContext.User != null && HttpContext.User.Identity.IsAuthenticated)
        {
            string scheme = (HttpContext.User.FindFirst("http://schemas.microsoft.com/claims/authnclassreference"))?.Value;
            await HttpContext.Authentication.SignOutAsync(CookieAuthenticationDefaults.AuthenticationScheme);
            await HttpContext.Authentication.SignOutAsync(scheme.ToLower(), new AuthenticationProperties { RedirectUri = "/" });
        }
    }

the scheme has a null value returned. I can't find a way to logoff properly. Any help will be appreciated.

Upvotes: 5

Views: 2324

Answers (2)

Kevin Ortman
Kevin Ortman

Reputation: 1919

Alex is correct. If you don't modify your code, you should change the representation to "acr".

However, "acr" is only provided for backward-compatibility and Microsoft recommends that "tfp" should be used instead. Azure Active Directory B2C: Token, session and single sign-on configuration

I recommend that you modify the example code as shown below. I also submitted a pull request to the original author with similar code.

        if (HttpContext.User != null && HttpContext.User.Identity.IsAuthenticated)
        {
            // try to find the tfp policy id claim (default)
            var scheme = (HttpContext.User.FindFirst("tfp"))?.Value;

            // fall back to legacy acr policy id claim
            if (string.IsNullOrEmpty(scheme))
                scheme = (HttpContext.User.FindFirst("http://schemas.microsoft.com/claims/authnclassreference"))?.Value;

            await HttpContext.Authentication.SignOutAsync(CookieAuthenticationDefaults.AuthenticationScheme);
            await HttpContext.Authentication.SignOutAsync(scheme.ToLower(), new AuthenticationProperties { RedirectUri = "/" });
        }

Upvotes: 0

Alex Lobakov
Alex Lobakov

Reputation: 714

Your code is looking for an "acr" claim and apparently not finding one. Open Azure portal and navigate to your Azure AD B2C, then check the "Token, Session and SSO config" section in each of your sign-in/sign-up policies. Under Token Compatibility Settings, you should have the following switch as shown:

enter image description here

If the switch has tfp selected (which is the default position), the auth token will contain no "acr" claim, therefore it won't be added into the collection of claims of the ClaimsPrincipal object after login, and is subsequently unavailable to your code in the LogOff method. Hope this helps.

Upvotes: 2

Related Questions