Cookie身份验证在.Net Core 2.1中不起作用调用HttpContext.SignInAsync不会设置身份。 [英] Cookie Authentication Not working in .Net Core 2.1 Call to HttpContext.SignInAsync doesn't set the identity.

查看:1068
本文介绍了Cookie身份验证在.Net Core 2.1中不起作用调用HttpContext.SignInAsync不会设置身份。的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

开始将我们的项目从.Net 4.6移植到.Net Core 2.1。 我在某些时候获得了cookie身份验证。我升级了我的库并更改了一些配置,现在只有拥有cookie的用户才能登录。没有新用户可以登录。
呼叫   HttpContext.SignInAsync不设置身份。 

Starting to Porting our project from .Net 4.6 to .Net Core 2.1.  I got cookie Authentication working at some point. I've upgraded my libraries and changed some configuration and now only the users that have a cookie can login. No new users can login. Calling  HttpContext.SignInAsync doesn't set the identity. 

在我的启动中,我有以下代码来构建中间件以支持cookie身份验证:

In my startup I have the following code to build the middle ware to support cookie authentication:

public void ConfigureServices(IServiceCollection services)
{


services.Configure<CookiePolicyOptions>(options =>
            {
                options.CheckConsentNeeded = context => true;
                options.MinimumSameSitePolicy = SameSiteMode.None;
            });
          
...


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

            services.AddAuthentication(options =>
                {
                    options.DefaultScheme = CookieAuthenticationDefaults.AuthenticationScheme;
                    options.DefaultChallengeScheme = CookieAuthenticationDefaults.AuthenticationScheme;
                    options.DefaultScheme = CookieAuthenticationDefaults.AuthenticationScheme;
                })
                .AddCookie(CookieAuthenticationDefaults.AuthenticationScheme, options =>
                {                 
                    options.Cookie.Name = "researchCookie";
                    options.AccessDeniedPath = new PathString("/account/create");
                    options.LoginPath = new PathString("/account/create");
                    options.Cookie.HttpOnly = true;
                    options.ExpireTimeSpan = TimeSpan.FromDays(365);
                    options.ReturnUrlParameter = CookieAuthenticationDefaults.ReturnUrlParameter;
                    options.SlidingExpiration = true;
                });

}





public void Configure(IApplicationBuilder app, IHostingEnvironment env)
{


...

 app.UseAuthentication();

...

 app.UseCookiePolicy(new CookiePolicyOptions
            {
                HttpOnly = HttpOnlyPolicy.Always,
                MinimumSameSitePolicy = SameSiteMode.Lax,
                Secure = CookieSecurePolicy.Always,
});

...

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

}

当我验证这是我的代码时:

When I authenticate this is the code I have:

 List<Claim> claims = new List<Claim>
                {
                    new Claim(ClaimTypes.Name, loginResult.AccessData.FirstName + " " + loginResult.AccessData.LastName),
                    new Claim(ClaimTypes.Email, loginResult.AccessData.Email),
                    new Claim(ClaimTypes.GivenName, loginResult.AccessData.FirstName),
                    new Claim(ClaimTypes.Surname, loginResult.AccessData.LastName),
                    new Claim(ClaimTypes.NameIdentifier, loginResult.AccessData.AccessID.ToString())
                };
             
                ClaimsIdentity identity = new ClaimsIdentity(claims, CookieAuthenticationDefaults.AuthenticationScheme);

                var authProperties = new AuthenticationProperties
                {
                    AllowRefresh = true,
                    // Refreshing the authentication session should be allowed.

                    ExpiresUtc = DateTimeOffset.UtcNow.AddYears(2),
                    // The time at which the authentication ticket expires. A 
                    // value set here overrides the ExpireTimeSpan option of 
                    // CookieAuthenticationOptions set with AddCookie.

                    IsPersistent = true,
                    // Whether the authentication session is persisted across 
                    // multiple requests. Required when setting the 
                    // ExpireTimeSpan option of CookieAuthenticationOptions 
                    // set with AddCookie. Also required when setting 
                    // ExpiresUtc.

                    IssuedUtc = DateTime.Now.ToUniversalTime(),
                    // The time at which the authentication ticket was issued.

                    //RedirectUri = <string>
                    // The full path or absolute URI to be used as an http 
                    // redirect response value.
                };


                await HttpContext.SignInAsync(CookieAuthenticationDefaults.AuthenticationScheme, new ClaimsPrincipal(identity), authProperties);




<我必须做错事或者库更新中的某些内容已经破坏了这一点。但就像我说的那样,只有之前登录的人才能登录。如果您删除了Cookie,那么身份永远不会被设置。 

I must be doing something wrong or something in the library updates has broken this. But Like I said only people who previously logged in can login. If you delete the cookies then the identity never gets set. 

我们将非常感谢任何建议。 

Any suggestions would be greatly appreciated. 

推荐答案

RodneyHickman,

Hi RodneyHickman,

感谢您在此发帖。

您是否在配置中设置身份验证?据我所知,它适用于.net core1。您可以查看以下关于.net core2的
Cookie身份验证的链接。

Do you set the Authentication in configuration? As I know, it works well for .net core1. You could check the link below about Cookie Authentication for .net core2.

https://dotnetcoretutorials.com/2017/09/16/cookie-authentication-asp-net-core-2-0/

https://www.cnblogs .com / tdfblog / p / aspnet-core-security-authentication-cookie.html

https://www.codeproject.com/Articles/1205161/ASP-NET-Core-Cookie-Authentication

最好的问候,

Wendy

注意:此响应包含对第三方万维网站点的引用。 Microsoft提供此信息是为了方便您。


Microsoft不控制这些网站,也没有测试在这些网站上找到的任何软件或信息;因此,Microsoft不能就其中发现的任何软件或信息的质量,安全性或适用性做出任何陈述。

使用互联网上的任何软件都存在固有的危险,微软提醒您在从Internet检索任何软件之前确保您完全了解风险。


Note: This response contains a reference to a third-party World Wide Web site. Microsoft is providing this information as a convenience to you.
Microsoft does not control these sites and has not tested any software or information found on these sites; Therefore, Microsoft cannot make any representations regarding the quality, safety, or suitability of any software or information found there.
There are inherent dangers in the use of any software found on the Internet, and Microsoft cautions you to make sure that you completely understand the risk before retrieving any software from the Internet.


这篇关于Cookie身份验证在.Net Core 2.1中不起作用调用HttpContext.SignInAsync不会设置身份。的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆