简体   繁体   English

"ASP.NET Core 2.1 - 身份验证 cookie 已删除,但用户仍可以登录而不会被重定向到外部登录"

[英]ASP.NET Core 2.1 - Authentication cookie deleted but the user could still login without being redirected to external sign-in

Good day!再会! I am currently creating a website which utilises the Google authentication to enable content personalisation.我目前正在创建一个利用 Google 身份验证来启用内容个性化的网站。 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.我在登录和检索登录用户的信息方面没有问题,但是当我调用 SignOutAsync() 函数时,.NET 并没有完全注销用户,因为用户可以在再次单击登录按钮时立即登录。 Once I clear the browser cache, the user will be redirected to the Google sign-in page when clicking on the Login button.清除浏览器缓存后,单击登录按钮时,用户将被重定向到 Google 登录页面。

The services configuration at Startup.cs: 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: 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: UserController.cs 中的登录操作:

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

Logout action at the UserController.cs: 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!我是 ASP.NET Core 身份验证领域的新手,所以如果有人能在这个问题上帮助我,我将不胜感激,谢谢!

you need to loop thru the application cookies - here is a sample code snippet: 您需要遍历应用程序Cookie-这是一个示例代码片段:

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

You can redirect user to Google's logout endpoint to logout : 您可以将用户重定向到Google的注销端点以注销:

 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 . 用您自己的网站url替换“ https:// localhost:44310 ”。 After that , when user click login again , user will be redirected to the Google sign-in page . 之后,当用户再次单击登录时,用户将被重定向到Google登录页面。

This is not a .NET issue but rather how Google works.这不是 .NET 问题,而是 Google 的工作方式。 It happens simply because there is only a single account logged into Google Accounts, which gets defaulted by the process.发生这种情况的原因很简单,因为只有一个帐户登录到 Google 帐户,该过程会默认该帐户。 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.不过,请务必从您用于开发的浏览器中执行此操作。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 使用 ASP.NET Core 2.1 / 3+ 身份验证身份验证 cookie - Validate authentication cookie with ASP.NET Core 2.1 / 3+ Identity 更新ASP.NET Core 2.1身份验证Cookie中的声明 - Update a claim in an ASP.NET Core 2.1 Authentication Cookie ASP.Net Core 2.1 IdentityCore(在用户登录时未添加角色声明) - ASP.Net Core 2.1 IdentityCore (Role Claims not being added on user sign in) Asp.Net Core 3.1 Cookie 身份验证循环到登录页面 - Asp.Net Core 3.1 Cookie Authentication loop to login page 有没有办法使用 Windows 身份验证注销并以其他用户身份登录? [ASP.NET Core 3.1 MVC] - Is there a way to sign out and login as another user using Windows authentication? [ASP.NET Core 3.1 MVC] 如何最好地在ASP.NET Core中实现Google社交登录身份验证? - How best to implement Google social sign-in authentication in ASP.NET Core? ASP.NET Core:作为其他应用程序的外部身份验证源 - ASP.NET Core: Being an external authentication source for other applications 如何从 cookie asp.net 核心自动重定向的登录页面更改用户界面的语言 - How to change language from ui from login page redirected automatically by cookie asp.net core 针对身份验证类型自定义登录页面设计:个人用户帐户 ASP.NET core 2.1、MVC、c# - Customize Login Page design for Authentication type : Individual User account ASP.NET core 2.1, MVC, c# 没有ASP.NET标识的.NET核心外部身份验证 - .NET Core External Authentication without ASP.NET Identity
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM