asp.net-core - 声明身份验证 ASP.NET vNext

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

最佳答案

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

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

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

请参阅 Sample 的链接

关于asp.net-core - 声明身份验证 ASP.NET vNext,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26978158/

相关文章:

c# - 自定义 UserManager 总是返回 null

c# - 在 Asp Net Core 6 中使用 Github 进行身份验证

sql-server - .NET Core 中错误 "Must declare the scalar variable @ "的含义是什么

c# - .Net Core 3.1 将 Serilog 与 Microsoft.Extensions.Logger 结合使用

http - 使用中间件仅处理 Controller 请求

c# - 如何从 Asp.Net Core View 组件返回错误的 HTTP 状态代码

security - 我可以在 TokenValidationParameters 的哪里指定 JWT token 中的算法应该匹配 HS256?

c# - 如何禁用所有 WebApi 响应的缓存以避免 IE 使用(来自缓存)响应

c# - 多层架构和身份。为什么要使用UserManager和RoleManager?

entity-framework - 未找到与命令 "dotnet-ef"匹配的可执行文件