4

Good day! I am currently creating a website which utilises the Google authentication to enable content personalisation. I have no problem with sign-in and retrieving the logged in user's info, but .NET is not signing the user out completely when I call the SignOutAsync() function, as the user could immediately log in when clicking on the Login button again. Once I clear the browser cache, the user will be redirected to the Google sign-in page when clicking on the Login button.

The services configuration at Startup.cs:

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;
        });

        // Configure authentication service
        services.AddAuthentication(options =>
        {
            options.DefaultAuthenticateScheme = CookieAuthenticationDefaults.AuthenticationScheme;
            options.DefaultSignInScheme = CookieAuthenticationDefaults.AuthenticationScheme;
            options.DefaultChallengeScheme = "Google";
        })
            .AddCookie("Cookies")
            .AddGoogle("Google", options =>
            {
                options.ClientId = Configuration["Authentication:Google:ClientId"];
                options.ClientSecret = Configuration["Authentication:Google:ClientSecret"];
            });

        services.AddSingleton<IHttpContextAccessor, HttpContextAccessor>();
        services.AddSingleton<IRecommender, OntologyRecommender>();

        services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_1);
    }

The middleware configuration at Startup.cs:

public void Configure(IApplicationBuilder app, IHostingEnvironment env)
    {
        if (env.IsDevelopment())
        {
            app.UseDeveloperExceptionPage();
        }
        else
        {
            app.UseExceptionHandler("/Home/Error");
            app.UseHsts();
        }

        app.UseHttpsRedirection();
        app.UseStaticFiles();
        app.UseCookiePolicy();
        app.UseAuthentication();

        app.UseMvc(routes =>
        {
            routes.MapRoute(
                name: "default",
                template: "{controller=Home}/{action=Index}/{id?}");
        });
    }

Login action at the UserController.cs:

 public IActionResult Login()
    {
        return Challenge(new AuthenticationProperties() { RedirectUri = "/" });
    }

Logout action at the UserController.cs:

[HttpPost]
    [ValidateAntiForgeryToken]
    public async Task<IActionResult> Logout()
    {   
        await HttpContext.SignOutAsync();
        HttpContext.Response.Cookies.Delete(".AspNetCore.Cookies");
        return RedirectToAction("Index", "Home");
    }

I am new to the ASP.NET Core authentication area, so I would appreciate if anyone could just assist me on this matter, thank you!

jazb
  • 5,498
  • 6
  • 37
  • 44
Samuel Cheah
  • 71
  • 1
  • 7
  • 2
    possible duplicate: https://stackoverflow.com/questions/33083824/login-with-google-how-to-log-out – jazb Nov 05 '18 at 03:45

3 Answers3

3

you need to loop thru the application cookies - here is a sample code snippet:

if (HttpContext.Request.Cookies[".MyCookie"] != null)
{
    var siteCookies = HttpContext.Request.Cookies.Where(c => c.Key.StartsWith(".MyCookie"));
    foreach (var cookie in siteCookies)
    {
        Response.Cookies.Delete(cookie.Key);
    }
}
jazb
  • 5,498
  • 6
  • 37
  • 44
  • Thanks for your prompt response. I looped through the application cookies and deleted them as suggested; however, it seems like the browser is still keeping the cookies that allow the user to immediately sign in without being redirected to the Google sign-in page. – Samuel Cheah Nov 05 '18 at 04:24
3

You can redirect user to Google's logout endpoint to logout :

 await HttpContext.SignOutAsync();
 HttpContext.Response.Cookies.Delete(".AspNetCore.Cookies");
 return Redirect("https://www.google.com/accounts/Logout?continue=https://appengine.google.com/_ah/logout?continue=https://localhost:44310");

Replace "https://localhost:44310" with your own website url . After that , when user click login again , user will be redirected to the Google sign-in page .

Nan Yu
  • 26,101
  • 9
  • 68
  • 148
0

This is not a .NET issue but rather how Google works. It happens simply because there is only a single account logged into Google Accounts, which gets defaulted by the process. Either log out of your google account from google accounts or login with other accounts as well.

Be sure to do this from the browser you're using for development though.

Ashique Razak
  • 487
  • 3
  • 8