1

When I use HttpContext.SignOutAsync with AuthenticationProperties together with a RedirectUri I expect to be redirected to a URL, but instead I am not redirected.

How can I debug this? I do not see any Exception or Warning.

  • Is this my implementation swallowing this?

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

Here is the Logout Implementation:

    [AllowAnonymous]
    public async Task Logout()
    {
        var oidcAuth = false;
        // clear the auth cookies
        if (HttpContext.Request.Cookies.Count> 0)
        {
            foreach (var (key, _) in HttpContext.Request.Cookies)
            {
                if (key.Contains(Startup.COOKIE_NAME_BASIC))
                {
                    Response.Cookies.Delete(key);
                } else if (key.Contains(Startup.COOKIE_NAME_OIDC))
                {
                    oidcAuth = true;
                    Response.Cookies.Delete(key);
                }
            }
        }
        
        HttpContext.Session.Clear();
        if (oidcAuth)
        {
            await HttpContext.SignOutAsync(Startup.COOKIE_NAME_OIDC);
            await HttpContext.SignOutAsync(OpenIdConnectDefaults.AuthenticationScheme);
        }
        else
        {
            await HttpContext.SignOutAsync(CookieAuthenticationDefaults.AuthenticationScheme,
                    new AuthenticationProperties { RedirectUri = "/" });
        }
    }

2 Answers 2

2

Firstly,you can refer to the official doc,and you can see RedirectUri is only used on a few specific paths by default, for example, the login path and logout paths. So if you want to redirect,you need to make sure your current path is login or logout path.Here is a demo: Startup.cs:

public void ConfigureServices(IServiceCollection services)
        {
            services.AddControllersWithViews();
            services.AddAuthentication(CookieAuthenticationDefaults.AuthenticationScheme)
            .AddCookie(options =>
            {
                options.LoginPath = "/Home/Login";
                options.LogoutPath = "/Home/Logout";
            });
            

        }
public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
        {
            if (env.IsDevelopment())
            {
                app.UseDeveloperExceptionPage();
            }
            else
            {
                app.UseExceptionHandler("/Home/Error");
                // The default HSTS value is 30 days. You may want to change this for production scenarios, see https://aka.ms/aspnetcore-hsts.
                app.UseHsts();
            }
            app.UseHttpsRedirection();
            app.UseStaticFiles();

            app.UseRouting();
            app.UseAuthentication();
            app.UseAuthorization();
            app.UseSession();
          

            app.UseEndpoints(endpoints =>
            {
                endpoints.MapControllerRoute(
                    name: "default",
                    pattern: "{controller=Home}/{action=Index}/{id?}");
            });
        }

HomeController:

[HttpPost]
        public async Task Logout()
        {

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

result: enter image description here

Sign up to request clarification or add additional context in comments.

1 Comment

Thanks for sharing!! Your Video / Gif was very helpful.
0

The official documentation does not mention what the "special" conditions are, but the source code does. No Exception or warning is given when the Redirect URI is being ignored.

The source code located here explains it all:

        // Only redirect on the login path
        var shouldRedirect = Options.LoginPath.HasValue && OriginalPath == Options.LoginPath;
        await ApplyHeaders(shouldRedirect, signedInContext.Properties);

        Logger.AuthenticationSchemeSignedIn(Scheme.Name);

Some important bits:

In Startup make sure the options.LogoutPath matches the path of your actual LogoutController's Logout Action.

Secondly the Logout Action should not perform the redirect and should return a Task and not a Task<IActionResult>

Also not to handle the OnRedirectToReturnUrl yourself.

LogoutController: Sign-out and set the Redirect URI The Path = "Logout/Logout"

    [AllowAnonymous]
    [HttpPost]
    public async Task Logout()
    {
        await HttpContext.SignOutAsync(CookieAuthenticationDefaults.AuthenticationScheme,
                    new AuthenticationProperties { RedirectUri = "/" });

    }

Startup: Configure the path

.AddCookie(CookieAuthenticationDefaults.AuthenticationScheme,"Cookie",options => {

  // must match path of Logout Controller                
  options.LogoutPath = new PathString("/Logout/Logout");


  // do not handle the event yourself
  // options.Events.OnRedirectToReturnUrl = async context =>
  // {
  //    await Task.CompletedTask;
  // };

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.