HttpContext.SigninAsync成功后找不到声明

时间:2019-12-19 06:45:04

标签: c# .net-core cookie-authentication

重新定义它。

我有一个asp.net核心(api)解决方案a.sln,其中包含accountcontroller.cs,该帐户允许用户登录到该应用程序。这是具有Login方法的AccountController.cs代码。

    /// <summary>
    /// Handle postback from username/password login
    /// </summary>
    [HttpPost]
    [ValidateAntiForgeryToken]
    public async Task<IActionResult> Login(LoginInputModel model, string button)
    {
       if (button != "login")
        {
            var context = await _interaction.GetAuthorizationContextAsync(model.ReturnUrl);
            if (context != null)
            {
                await _interaction.GrantConsentAsync(context, ConsentResponse.Denied);
                return Redirect(model.ReturnUrl);
            }
            else
            {
                return Redirect("~/");
            }
        }

       if (ModelState.IsValid)
        {
            var user = await _userManager.FindByNameOrEmailAsync(model.Username);

            if (user != null)
            {
                if (await _userManager.CheckPasswordAsync(user, model.Password) && !await _userManager.IsEmailConfirmedAsync(user))
                {
                    ModelState.AddModelError("", Messages.UserEmailUnverified(_httpContextAccessor));
                }
                else if (await _userManager.CheckPasswordAsync(user, model.Password) && !(await _userManager.IsLockedOutAsync(user)))
                {
                    var userRoles = await _userManager.GetRolesAsync(user);
                    var userClaims = userRoles.Select(x => new Claim(ClaimTypes.Role, x)).ToList();

                    await _events.RaiseAsync(
                        new UserLoginSuccessEvent(user.UserName, user.Id, user.UserName));

                    var rememberMe = _accountOptions.AllowRememberLogin && model.RememberLogin;

                    var props = new AuthenticationProperties()
                    {
                        IsPersistent = rememberMe,
                        ExpiresUtc = DateTimeOffset.UtcNow.Add(rememberMe ? TimeSpan.FromDays(_accountOptions.RememberMeLoginDurationDays)
                                        : TimeSpan.FromMinutes(_accountOptions.StandardLoginDurationMinutes))
                    };

                    userClaims.Add(new Claim("remember_me", model.RememberLogin.ToString()));

                    var appIdentity = new ClaimsIdentity(userClaims, CookieAuthenticationDefaults.AuthenticationScheme);
                    HttpContext.User.AddIdentity(appIdentity);

                    await HttpContext.SignInAsync(user.Id, user.UserName, props, userClaims.ToArray());

                    //after successful login reset lockout count
                    await _userManager.ResetAccessFailedCountAsync(user);

                    bool isAllowedUrl = !_middlewareConf.ClientRedirectUrls.Where(urlToCheck => model.ReturnUrl.Contains(urlToCheck)).IsNullOrEmpty();

                    if (_interaction.IsValidReturnUrl(model.ReturnUrl) || isAllowedUrl)
                    {
                        return Redirect(model.ReturnUrl);
                    }

                    return Redirect(_loginConfiguration.DefaultRedirectUrl);
                }
                else
                {
                    var error = await _accountManager.HandleLockout(user);
                    ModelState.AddModelError("", error);
                }
            }
            else
            {
                await _events.RaiseAsync(new UserLoginFailureEvent(model.Username, $"Invalid credentials."));
                ModelState.AddModelError("", _accountOptions.InvalidCredentialsErrorMessage);
            }
        }

        var vm = await _account.BuildLoginViewModelAsync(model);
        return View(vm);
    }

在上述Login方法中,我们明确添加了Claim“ remember_me”。

成功登录后,我被定向到另一个asp.net核心解决方案,其中在start.cs上我试图找到相同的要求。这是start.cs的代码。

  public void Configuration(IAppBuilder app)
    {
        var idConfig = IdentityConfiguration.Configuration;
        JwtSecurityTokenHandler.DefaultInboundClaimTypeMap.Clear();
        app.UseKentorOwinCookieSaver();

        //tell app to use Cookies as the default
        app.SetDefaultSignInAsAuthenticationType(CookieAuthenticationDefaults.AuthenticationType);

        // Use cookie authentication
        app.UseCookieAuthentication(new CookieAuthenticationOptions()
        {
            AuthenticationType = "Cookies",
            ExpireTimeSpan = TimeSpan.FromMinutes(idConfig.CookieExpiresMinutes ?? 60),
            SlidingExpiration = idConfig.CookieSlidingExpiration ?? false,
            Provider = new CookieAuthenticationProvider
            {
                OnResponseSignIn = signInContext =>
                {
                    var rememberMeClaim = signInContext.Identity.Claims.FirstOrDefault(c => c.Type == "remember_me");

                    if (bool.TryParse(rememberMeClaim?.Value, out var rememberMe))
                    {
                        if (rememberMe && idConfig.RememberCookieExpiresDays.HasValue)
                        {
                            signInContext.CookieOptions.Expires = DateTime.Now.AddDays(idConfig.RememberCookieExpiresDays.Value);
                        }
                    }
                }
            }
        });
   }

但是在上面的代码中,我找不到相同的声明“ remember_me”。

我想念什么吗?

1 个答案:

答案 0 :(得分:0)

与其添加诸如:-

之类的声明,
userClaims.Add(new Claim("remember_me", model.RememberLogin.ToString()));

添加声明,如下所示:-

 await _userManager.AddClaimAsync(user, new Claim("remember_me",model.RememberLogin.ToString()));

现在,我可以提出要求“ remember_me”。