Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Azure Active Directory won't logout using ASP.NET Core 2.1 MVC

I have an ASP.NET Core 2.1 MVC application and I'm trying to use Azure AD to authenticate. The application redirects to the Microsoft login page but when I logout and then go back to the homepage of the application it automatically logs back in.

I've tried calling https://login.microsoftonline.com/common/oauth2/v2.0/logout and clearing the cookies but to no avail.

public void ConfigureServices(IServiceCollection services)
{
    services.Configure<CookiePolicyOptions>(options =>
        {
            // This lambda determines whether user consent for non-essential cookies is needed for a given request.
            options.CheckConsentNeeded = context => true;
            options.MinimumSameSitePolicy = SameSiteMode.None;
        });

    services.AddAuthentication(AzureADDefaults.AuthenticationScheme)
            .AddAzureAD(options => Configuration.Bind("AzureAd", options));

    services.Configure<OpenIdConnectOptions>(AzureADDefaults.OpenIdScheme, options =>
        {
            options.Authority = options.Authority + "/v2.0/";
            options.TokenValidationParameters.ValidateIssuer = false;
            options.Events.OnRedirectToIdentityProviderForSignOut = async context =>
            {
                var h = new HttpClient();
                var r = await h.GetAsync($"https://login.microsoftonline.com/common/oauth2/v2.0/logout?post_logout_redirect_uri=https%3A%2F%2Flocalhost%2%3A5001%2F");

                foreach (var cookie in context.Request.Cookies.Keys)
                {
                    context.Response.Cookies.Delete(cookie);
                }
            };

            options.Events.OnTokenResponseReceived = async conext =>
            {
                var t = 1;
            };
        });

    services.AddMvc(options =>
        {
            var policy = new AuthorizationPolicyBuilder()
                .RequireAuthenticatedUser()
                .Build();
            options.Filters.Add(new AuthorizeFilter(policy));
        })
        .SetCompatibilityVersion(CompatibilityVersion.Version_2_1);
}

public async Task<IActionResult> Logout()
{
    var result =  SignOut("AzureAD", "AzureADOpenID", "AzureADCookie");
    return result;
}
like image 635
L T Avatar asked Apr 05 '19 14:04

L T


2 Answers

Please check my way to add Azure AD authentication to ASP.NET Core 2.1 MVC application. The tool will add the authentication code for you. What you need to do is binding your sign in/out button to the method.

1.Click Connected Services->choose Authentication with Azure Active Directory.

enter image description here

2.You need to provide a login button for trigger the login page.

enter image description here

3.Input your tenant name for Domain and choose a way for providing application settings.

enter image description here

4.Click finish button to complete the configuration.

5.Delete app.UseBrowserLink() in Startup.cs.

6.Call SignOut() method in AccountController.cs to sign out the user. It works well.

[HttpGet]
        public IActionResult SignOut()
        {
            var callbackUrl = Url.Action(nameof(SignedOut), "Account", values: null, protocol: Request.Scheme);
            return SignOut(
                new AuthenticationProperties { RedirectUri = callbackUrl },
                CookieAuthenticationDefaults.AuthenticationScheme,
                OpenIdConnectDefaults.AuthenticationScheme);
        }
like image 104
Tony Ju Avatar answered Oct 18 '22 18:10

Tony Ju


Since you are using the Microsoft.AspNetCore.Authentication.AzureAD.UI library , you can directly redirect user to https://localhost:xxxxx/AzureAD/Account/SignOut for sign out , Source code :

[HttpGet("{scheme?}")]
public IActionResult SignOut([FromRoute] string scheme)
{
    scheme = scheme ?? AzureADDefaults.AuthenticationScheme;
    var options = Options.Get(scheme);
    var callbackUrl = Url.Page("/Account/SignedOut", pageHandler: null, values: null, protocol: Request.Scheme);
    return SignOut(
        new AuthenticationProperties { RedirectUri = callbackUrl },
        options.CookieSchemeName,
        options.OpenIdConnectSchemeName);
}

You can now remove the OnRedirectToIdentityProviderForSignOut event .

like image 39
Nan Yu Avatar answered Oct 18 '22 20:10

Nan Yu