【问题标题】:How to store cookies in asp.net identity (web api)如何在 asp.net 身份中存储 cookie (web api)
【发布时间】:2019-09-05 06:53:30
【问题描述】:

我有带有 WebApi 和个人用户帐户的 Asp.net Web 应用程序项目。 我实现了注册和登录,前端使用了angularjs。

现在,我需要在浏览器中存储 cookie。

如果基于 cookie 的身份验证将 cookie 存储在浏览器中,我感到很困惑?

在我的项目中,我根据令牌对用户进行身份验证。

我进行了研究,但它让我感到困惑,我没有找到使用 Asp.Net Identity webApi 存储 cookie 的明确指南。

这是用户身份验证的位置:

  public override async Task GrantResourceOwnerCredentials(OAuthGrantResourceOwnerCredentialsContext context)
    {
        var userManager = context.OwinContext.GetUserManager<ApplicationUserManager>();

        ApplicationUser user = await userManager.FindAsync(context.UserName, context.Password);

        if (user == null)
        {
            context.SetError("invalid_grant", "The user name or password is incorrect.");
            return;
        }
       /* 
   I tried the following but I get an error that Request doesn't exist

 var claims = new List<Claim>();
        claims.Add(new Claim(ClaimTypes.Name, context.UserName));
        var id = new ClaimsIdentity(claims, DefaultAuthenticationTypes.ApplicationCookie);

        var ctx = Request.GetOwinContext();
        var authenticationManager = ctx.Authentication;
        authenticationManager.SignIn(id);

                 */

        ClaimsIdentity oAuthIdentity = await user.GenerateUserIdentityAsync(userManager);
        ClaimsIdentity cookiesIdentity = await user.GenerateUserIdentityAsync(userManager);

        AuthenticationProperties properties = CreateProperties(user.UserName);
        AuthenticationTicket ticket = new AuthenticationTicket(oAuthIdentity, properties);
        context.Validated(ticket);
        context.Request.Context.Authentication.SignIn(cookiesIdentity);
    }

对不起,我是 Asp.net Identity 的新手。

如果在 WebApi (不是 MVC) 中的 Asp.Net Identity 中有明确的指南?

注意:我没有 LoginPath。

【问题讨论】:

标签: asp.net asp.net-web-api cookies


【解决方案1】:

所以你有一个 webApi 用于验证你的用户,当你的用户通过身份验证时,你会得到一个 jwt 令牌,对吧?并且您需要将该令牌保存在 cookie 中,以便您的前端用于发出请求。

所以这是我写的一个示例代码,它就是 asp core api 在我的 aspcore API AccountsController => 登录操作:

    [HttpPost]
    public async Task<IActionResult> Login([FromBody] LoginViewModel vm)
    {
        if (ModelState.IsValid)
        {
            var token = await _authenticationService.GenerateToken(vm);
            if (token != null)
            {
                return Ok(new
                {
                    token = new JwtSecurityTokenHandler().WriteToken(token),
                    expiration = token.ValidTo
                });
            }
            return Unauthorized();
        }
        return StatusCode(StatusCodes.Status403Forbidden, new { ErrorMessage = "wrong Email or password" });
    }

_authenticationService 是我编写的用于生成 jwt 令牌的类:

 public async Task<JwtSecurityToken> GenerateToken(LoginViewModel vm)
    {
        if (!string.IsNullOrEmpty(vm.Email) && !string.IsNullOrEmpty(vm.Password))
        {
            var user = await _userManager.FindByEmailAsync(vm.Email);
            var userRoles = await _userManager.GetRolesAsync(user);


            var signingKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(_configuration.GetSection("Secrets:SigningKey").Value));
            var claims = new List<Claim>
            {
                 new Claim(JwtRegisteredClaimNames.Sub, vm.Email)
            };

            foreach (var roleName in userRoles)
            {
                claims.Add(new Claim(ClaimsIdentity.DefaultRoleClaimType, roleName));
            };


            if (user != null && await _userManager.CheckPasswordAsync(user, vm.Password))
            {
                var token = new JwtSecurityToken(
                        issuer: _configuration.GetSection("Secrets:issuer").Value,
                        audience: _configuration.GetSection("Secrets:audience").Value,
                        expires: DateTime.UtcNow.AddDays(20),
                        signingCredentials: new SigningCredentials(signingKey, SecurityAlgorithms.HmacSha256),
                        claims: claims);

                return token;
            }
            return null;
        }
        return null;
    }

所以在你上面的代码中,如果你向你的 api 发送一个好的凭据,你会得到一个 jwt 令牌。 现在您需要将该令牌保存在 cookie 中,为此您需要在前端而不是 Web api 中创建 cookie。

所以你可能会在angular-university看到这个链接

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2013-09-28
    • 1970-01-01
    • 1970-01-01
    • 2017-01-26
    • 2011-11-29
    • 2017-10-22
    • 2019-08-23
    • 2012-06-16
    相关资源
    最近更新 更多