首页 新闻 会员 周边

.net core cookie的问题

0
[已解决问题] 解决于 2017-12-13 14:24

我注册了cookie

ClaimsIdentity identity = new ClaimsIdentity(CookieAuthenticationDefaults.AuthenticationScheme);
identity.AddClaim(new Claim(ClaimTypes.Name, usersModel.name));
identity.AddClaim(new Claim(ClaimTypes.GroupSid, usersModel.group.ToString()));
identity.AddClaim(new Claim(ClaimTypes.Email, usersModel.email));

//设置有效期
HttpContext.SignInAsync(CookieAuthenticationDefaults.AuthenticationScheme, new ClaimsPrincipal(identity), new AuthenticationProperties
{
// 持久保存
IsPersistent = true,

// 指定过期时间AddMinutes 添加天
ExpiresUtc = DateTime.UtcNow.AddDays(7)
});

 

然后获取cookie

//不加这个验证代码 取不到cookies
[Authorize(AuthenticationSchemes = CookieAuthenticationDefaults.AuthenticationScheme)]
public IActionResult Forbidden()
{
//获取cookie信息
string strName = User.FindFirstValue(ClaimTypes.Name);
string strGroup = User.FindFirstValue(ClaimTypes.GroupSid);
string strEmail = User.FindFirstValue(ClaimTypes.Email);
ViewData["strName"] = strName;
ViewData["strGroup"] = strGroup;
ViewData["strEmail"] = strEmail;
return View();
}

 

---------------------------------------

[Authorize(AuthenticationSchemes = CookieAuthenticationDefaults.AuthenticationScheme)]

想请教一下如何在不加过滤器的情况下取cookie

87Super的主页 87Super | 初学一级 | 园豆:107
提问于:2017-12-12 14:54
< >
分享
最佳答案
1

Startup.cs 中添加以下代码了吗?

services.AddAuthentication(options =>
{
    options.DefaultAuthenticateScheme = CookieAuthenticationDefaults.AuthenticationScheme;
    options.DefaultChallengeScheme = CookieAuthenticationDefaults.AuthenticationScheme;
})
.AddCookie();
奖励园豆:5
dudu | 高人七级 |园豆:31003 | 2017-12-12 15:17

加了不添加过滤器用User.FindFirstValue(ClaimTypes.Name);也取不到。

87Super | 园豆:107 (初学一级) | 2017-12-12 15:37

@87Super: 试试把

ClaimsIdentity identity = new ClaimsIdentity(CookieAuthenticationDefaults.AuthenticationScheme);

改为

ClaimsIdentity identity = new ClaimsIdentity();

我们是这样使用的

var claimsIdentity = new ClaimsIdentity(new Claim[] { new Claim(ClaimTypes.Name, loginName) }, "Basic");
var claimsPrincipal = new ClaimsPrincipal(claimsIdentity);
await context.SignInAsync(CookieAuthenticationDefaults.AuthenticationScheme,
    claimsPrincipal,
    new AuthenticationProperties
    {
        IsPersistent = isPersistent,
        ExpiresUtc = DateTimeOffset.Now.Add(_cookieAuthOptions.ExpireTimeSpan)
    });
dudu | 园豆:31003 (高人七级) | 2017-12-12 15:47

@dudu: 

不行唉,不带参数创建运行报错的,你们的不使用[Authorize(AuthenticationSchemes = CookieAuthenticationDefaults.AuthenticationScheme)]的时候也能取到cookie么,如果可以 我就照抄吧。

87Super | 园豆:107 (初学一级) | 2017-12-12 16:03

@dudu: 代码

services.AddAuthentication(options =>
{
options.DefaultAuthenticateScheme = CookieAuthenticationDefaults.AuthenticationScheme;
options.DefaultChallengeScheme = CookieAuthenticationDefaults.AuthenticationScheme;
}).AddCookie(
CookieAuthenticationDefaults.AuthenticationScheme, o =>
{
o.LoginPath = new PathString("/Account/Login");
o.AccessDeniedPath = new PathString("/Account/Forbidden");
});

87Super | 园豆:107 (初学一级) | 2017-12-12 16:06

@87Super: 我们的项目中即使不加Authorize,只要用户登录了,就能督导cookie

dudu | 园豆:31003 (高人七级) | 2017-12-12 18:05

@dudu: 站长 你也是这种方式读的吗User.FindFirstValue(ClaimTypes.Name);

87Super | 园豆:107 (初学一级) | 2017-12-12 20:52

@87Super: 是这样读的:User.Identity.Name

dudu | 园豆:31003 (高人七级) | 2017-12-12 21:15

@dudu: 也是一样的null,我贴完整代码,站长帮看看,搞了一天了也读不到。

注册服务的代码

-------------------------------------------------

services.AddAuthentication(options =>
{
options.DefaultAuthenticateScheme = CookieAuthenticationDefaults.AuthenticationScheme;
options.DefaultChallengeScheme = CookieAuthenticationDefaults.AuthenticationScheme;
}).AddCookie(
CookieAuthenticationDefaults.AuthenticationScheme, o =>
{
o.LoginPath = new PathString("/Account/Login");
o.AccessDeniedPath = new PathString("/Account/Forbidden");
});

 

注册授权中间件的代码

--------------------------------------------

app.UseAuthentication();

 

发放cookie的代码

-------------------------------------

ClaimsIdentity identity = new ClaimsIdentity(CookieAuthenticationDefaults.AuthenticationScheme);

identity.AddClaim(new Claim(ClaimTypes.Name, usersModel.name));
identity.AddClaim(new Claim(ClaimTypes.GroupSid, usersModel.group.ToString()));
identity.AddClaim(new Claim(ClaimTypes.Email, usersModel.email));
HttpContext.SignInAsync(CookieAuthenticationDefaults.AuthenticationScheme, new ClaimsPrincipal(identity), new AuthenticationProperties
{
IsPersistent = true,
ExpiresUtc = DateTime.UtcNow.AddDays(7)
});
 
 
读取cookie的代码
------------------------------------

string strName = User.FindFirstValue(ClaimTypes.Name);
string strGroup = User.FindFirstValue(ClaimTypes.GroupSid);
string strEmail = User.FindFirstValue(ClaimTypes.Email);

 
87Super | 园豆:107 (初学一级) | 2017-12-12 21:24

@87Super: 问题出在.AddCookie部分,去掉CookieAuthenticationDefaults.AuthenticationScheme,改为

services.AddAuthentication(options =>
{
options.DefaultAuthenticateScheme = CookieAuthenticationDefaults.AuthenticationScheme;
options.DefaultChallengeScheme = CookieAuthenticationDefaults.AuthenticationScheme;
}).AddCookie(o =>
{
o.LoginPath = new PathString("/Account/Login");
o.AccessDeniedPath = new PathString("/Account/Forbidden");
});
dudu | 园豆:31003 (高人七级) | 2017-12-12 21:38

@87Super: 你要是代码加高亮的话,估计早就看出来了

dudu | 园豆:31003 (高人七级) | 2017-12-12 21:41

@dudu: 还是取不到null。

刚才查资料查到一点有用的

// 1. 在Startup.cs的Configure方法中加上  
app.UseCookieAuthentication(new CookieAuthenticationOptions  
{  
 AuthenticationScheme = "UserAuth",  // Cookie 验证方案名称,在写cookie时会用到。  
 AutomaticAuthenticate = true,     // 是否自动启用验证,如果不启用,则即便客服端传输了Cookie信息,服务端也不会主动解析。除了明确配置了 [Authorize(ActiveAuthenticationSchemes = "上面的方案名")] 属性的地方,才会解析,此功能一般用在需要在同一应用中启用多种验证方案的时候。比如分Area.  
 LoginPath = "/User/Index"     // 登录页  
});  
 AutomaticAuthenticate = true,     // 是否自动启用验证,如果不启用,则即便客服端传输了Cookie信息,服务端也不会主动解析。除了明确配置了 [Authorize(ActiveAuthenticationSchemes = "上面的方案名")] 属性的地方,才会解析,此功能一般用在需要在同一应用中启用多种验证方案的时候。比如分Area.  

这个属性,但是这个属性在2.0中弃用了,在2.0我不知道该怎么办。

87Super | 园豆:107 (初学一级) | 2017-12-12 22:02

@dudu: 

services.AddAuthentication(options =>
            {
                options.DefaultScheme = CookieAuthenticationDefaults.AuthenticationScheme; //加了这个
                options.DefaultAuthenticateScheme = CookieAuthenticationDefaults.AuthenticationScheme;
                options.DefaultChallengeScheme = CookieAuthenticationDefaults.AuthenticationScheme;
            }).AddCookie(
                o =>
                {
                    o.LoginPath = new PathString("/Account/Login");
                    o.AccessDeniedPath = new PathString("/Account/Forbidden");
                });

options.DefaultScheme = CookieAuthenticationDefaults.AuthenticationScheme;

加了这个还是取不到。要哭了。

87Super | 园豆:107 (初学一级) | 2017-12-12 22:24

@87Super: 下面是我们实际使用的代码,已在多个实际运行的ASP.NET Core 2.0项目中使用,比如博问

services.AddAuthentication(options =>
{
    options.DefaultAuthenticateScheme = CookieAuthenticationDefaults.AuthenticationScheme;
    options.DefaultChallengeScheme = CookieAuthenticationDefaults.AuthenticationScheme;
})
.AddCookie(options =>
{
    options.ExpireTimeSpan = TimeSpan.FromMinutes(xxx);
    options.Cookie.HttpOnly = true;
    options.LoginPath = "/account/signin";
    options.LogoutPath = "/account/signout";
});
dudu | 园豆:31003 (高人七级) | 2017-12-12 22:31

@dudu: 

嘟嘟我的站长大大。问题解决了,你可能没想到,代码没问题。

问题在下面。

        public void Configure(IApplicationBuilder app, IHostingEnvironment env)
        {
            if (env.IsDevelopment())
            {
                app.UseDeveloperExceptionPage();
            }

            //添加 app.UseAuthentication(),使用授权中间件:
            app.UseAuthentication();

            //启动默认路由 默认路由: Home控制器 Index方法
            //app.UseMvcWithDefaultRoute();

            //添加自定义路由
            app.UseMvc(routes =>
            {
                //defatul路由名称 控制器名称Home  方法名称 Index
                routes.MapRoute("defatul", "{controller=Home}/{action=Index}");
            });

            //启用默认静态文件中间件 默认wwwroot底下的静态文件
            app.UseStaticFiles();

            //自定义静态文件目录
            app.UseStaticFiles(new StaticFileOptions()
            {
                FileProvider = new PhysicalFileProvider(
                    Path.Combine(Directory.GetCurrentDirectory(), @"StaticFiles")), //文件夹名称
                    RequestPath = new PathString("/StaticFiles") //请求目录名称
            });



            
        }

我一开始是把app.UseAuthentication(); 授权中间件放到了最后,就是静态目录的后面,把授权中间件放到上面就能取到了。。

87Super | 园豆:107 (初学一级) | 2017-12-12 23:08

@87Super: 汗,中间件的先后顺序容易被忽略

dudu | 园豆:31003 (高人七级) | 2017-12-13 10:01

@87Super: 你好,我现在也遇到这个问题,但按照你的解决方法还是不行,请问能否帮我看一下,谢谢

jobroon | 园豆:157 (初学一级) | 2018-05-26 16:19
清除回答草稿
   您需要登录以后才能回答,未注册用户请先注册