声明身份验证ASP.NET vNext

时间:2014-11-17 17:16:52

标签: asp.net-core

向用户添加声明时,声明信息不会在页面上记录为Cookie,并且所有其他请求的信息都会丢失。为什么会这样?

    public async Task<IActionResult> Login(LoginViewModel model, string returnUrl = null)
    {
        if (ModelState.IsValid)
        {
            try
            {
                var authReq = new AuthenticationViewModel() { password = model.Password, username = model.UserName };
                var userInfo = await _dataService.AuthenticateAsync(authReq);


                var claims = new List<Claim>();
                claims.Add(new Claim("username", userInfo.user.userName));
                claims.Add(new Claim("AddtionalData", userInfo.AddtionalData));

                var user = ClaimsPrincipal.Current;

                var identity = user.Identities.Where(x => x.AuthenticationType == "Custom").FirstOrDefault();

                if (identity == null)
                    identity = new ClaimsIdentity(claims.ToArray(), "Custom");

                user.AddIdentity(identity);


                return RedirectToAction("Users", "Index");
            }
            catch (Exception)
            {
                ModelState.AddModelError("", "Invalid username or password.");
            }

        }

        // If we got this far, something failed, redisplay form
        return View(model);
    }

1 个答案:

答案 0 :(得分:2)

我发现了这个问题,我需要添加以下代码:

context.Response.SignIn(new ClaimsIdentity(new[] { new Claim("name", "bob") }, CookieAuthenticationDefaults.AuthenticationType)); 

另外,我将AuthenticationType更改为CookieAuthenticationDefaults.AuthenticationType。

请参阅Sample

的链接