ASP.NET Core 2.1 - Authentication cookie deleted but the user could still login without being redirected to...











up vote
0
down vote

favorite












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!










share|improve this question









New contributor




Samuel Cheah is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.
















  • 2




    possible duplicate: stackoverflow.com/questions/33083824/…
    – JohnB
    Nov 5 at 3:45















up vote
0
down vote

favorite












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!










share|improve this question









New contributor




Samuel Cheah is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.
















  • 2




    possible duplicate: stackoverflow.com/questions/33083824/…
    – JohnB
    Nov 5 at 3:45













up vote
0
down vote

favorite









up vote
0
down vote

favorite











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!










share|improve this question









New contributor




Samuel Cheah is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.











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!







c# authentication asp.net-core asp.net-core-mvc google-authentication






share|improve this question









New contributor




Samuel Cheah is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.











share|improve this question









New contributor




Samuel Cheah is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.









share|improve this question




share|improve this question








edited Nov 5 at 13:51









JohnB

880715




880715






New contributor




Samuel Cheah is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.









asked Nov 5 at 3:38









Samuel Cheah

11




11




New contributor




Samuel Cheah is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.





New contributor





Samuel Cheah is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.






Samuel Cheah is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.








  • 2




    possible duplicate: stackoverflow.com/questions/33083824/…
    – JohnB
    Nov 5 at 3:45














  • 2




    possible duplicate: stackoverflow.com/questions/33083824/…
    – JohnB
    Nov 5 at 3:45








2




2




possible duplicate: stackoverflow.com/questions/33083824/…
– JohnB
Nov 5 at 3:45




possible duplicate: stackoverflow.com/questions/33083824/…
– JohnB
Nov 5 at 3:45












2 Answers
2






active

oldest

votes

















up vote
1
down vote













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





share|improve this answer





















  • 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 5 at 4:24




















up vote
1
down vote













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 .






share|improve this answer





















    Your Answer






    StackExchange.ifUsing("editor", function () {
    StackExchange.using("externalEditor", function () {
    StackExchange.using("snippets", function () {
    StackExchange.snippets.init();
    });
    });
    }, "code-snippets");

    StackExchange.ready(function() {
    var channelOptions = {
    tags: "".split(" "),
    id: "1"
    };
    initTagRenderer("".split(" "), "".split(" "), channelOptions);

    StackExchange.using("externalEditor", function() {
    // Have to fire editor after snippets, if snippets enabled
    if (StackExchange.settings.snippets.snippetsEnabled) {
    StackExchange.using("snippets", function() {
    createEditor();
    });
    }
    else {
    createEditor();
    }
    });

    function createEditor() {
    StackExchange.prepareEditor({
    heartbeatType: 'answer',
    convertImagesToLinks: true,
    noModals: true,
    showLowRepImageUploadWarning: true,
    reputationToPostImages: 10,
    bindNavPrevention: true,
    postfix: "",
    imageUploader: {
    brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
    contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
    allowUrls: true
    },
    onDemand: true,
    discardSelector: ".discard-answer"
    ,immediatelyShowMarkdownHelp:true
    });


    }
    });






    Samuel Cheah is a new contributor. Be nice, and check out our Code of Conduct.










     

    draft saved


    draft discarded


















    StackExchange.ready(
    function () {
    StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53147993%2fasp-net-core-2-1-authentication-cookie-deleted-but-the-user-could-still-login%23new-answer', 'question_page');
    }
    );

    Post as a guest
































    2 Answers
    2






    active

    oldest

    votes








    2 Answers
    2






    active

    oldest

    votes









    active

    oldest

    votes






    active

    oldest

    votes








    up vote
    1
    down vote













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





    share|improve this answer





















    • 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 5 at 4:24

















    up vote
    1
    down vote













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





    share|improve this answer





















    • 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 5 at 4:24















    up vote
    1
    down vote










    up vote
    1
    down vote









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





    share|improve this answer












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






    share|improve this answer












    share|improve this answer



    share|improve this answer










    answered Nov 5 at 3:57









    JohnB

    880715




    880715












    • 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 5 at 4:24




















    • 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 5 at 4:24


















    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 5 at 4:24






    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 5 at 4:24














    up vote
    1
    down vote













    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 .






    share|improve this answer

























      up vote
      1
      down vote













      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 .






      share|improve this answer























        up vote
        1
        down vote










        up vote
        1
        down vote









        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 .






        share|improve this answer












        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 .







        share|improve this answer












        share|improve this answer



        share|improve this answer










        answered Nov 6 at 6:04









        Nan Yu

        5,6252646




        5,6252646






















            Samuel Cheah is a new contributor. Be nice, and check out our Code of Conduct.










             

            draft saved


            draft discarded


















            Samuel Cheah is a new contributor. Be nice, and check out our Code of Conduct.













            Samuel Cheah is a new contributor. Be nice, and check out our Code of Conduct.












            Samuel Cheah is a new contributor. Be nice, and check out our Code of Conduct.















             


            draft saved


            draft discarded














            StackExchange.ready(
            function () {
            StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53147993%2fasp-net-core-2-1-authentication-cookie-deleted-but-the-user-could-still-login%23new-answer', 'question_page');
            }
            );

            Post as a guest




















































































            這個網誌中的熱門文章

            Xamarin.form Move up view when keyboard appear

            Post-Redirect-Get with Spring WebFlux and Thymeleaf

            Anylogic : not able to use stopDelay()