ASP身份访问值和重定向

时间:2019-03-06 10:14:05

标签: asp.net-core-mvc asp.net-core-2.0

理想的结果:

出于各种原因,我将旧的Web登录名移植到Identity,但是该应用程序只能由授权人员创建新用户。非常简单,只需使用[Authorize(Role =“ Admin”)]锁定注册页面。工作人员将使用任何密码创建用户,这无关紧要,这将触发向用户发送电子邮件确认链接。确认该电子邮件后,我想强制用户重置密码。

问题:

在.Net Core 2.2中使用asp身份,我试图检查用户(布尔)上的自定义属性的值,如果为false,请在浏览器上执行重定向。我似乎在访问Http Pipeline中的User属性时陷入困境。空对象等。

我尝试过的事情

到目前为止,我已经尝试使用资源过滤器,因为它会在身份验证过滤器之后触发,因此我应该能够通过HttpContext访问用户的属性,但没有任何乐趣。然后,我尝试实现一些中间件来执行相同的操作,但仍然没有任何乐趣。我只是想不通如何通过HttpContext获取此属性值,如果可能的话?

用户模型

public class ApplicationUser : IdentityUser
    {
        public int CustomerId { get; set; }

        //I want to get this property value
        public bool PasswordConfirmed { get; set; }
    }

我知道我可以使用动作过滤器来执行此操作,但是似乎有点晚了。

1 个答案:

答案 0 :(得分:0)

所以我得到了我的答案,很有趣,如何花点时间来解决问题更容易!

我只需要在中间件类中添加以下内容:

        public async Task Invoke(HttpContext httpContext, UserManager<ApplicationUser> userManager)
        {
            if (httpContext.User.Identity.IsAuthenticated)
            {
                ApplicationUser user = userManager.Users.Where(x => x.Id == httpContext.User.FindFirstValue(ClaimTypes.NameIdentifier)).SingleOrDefault();
                bool a = user.PasswordConfirmed;
                string b = httpContext.User.FindFirstValue(ClaimTypes.NameIdentifier);
                Debug.WriteLine("*****" + a + "*****");
                Debug.WriteLine("*****" + b + "*****");
                var code = await GetApplicationUserCode(user, userManager);
                String path = httpContext.Request.Path;
                if (!a && !path.Contains("/Identity/Account/ResetPassword"))
                {
                    httpContext.Response.Redirect("/Identity/Account/ResetPassword?code=" + HttpUtility.UrlEncode(code)
                    , false);
                }
            }

            await _next(httpContext);
        }

        private async Task<String> GetApplicationUserCode(ApplicationUser user, UserManager<ApplicationUser> userManager)
        {
            return await userManager.GeneratePasswordResetTokenAsync(user);
        }

因此,这里发生的是我们从httpContext中的UserId中获取用户。然后,这使我可以访问自定义属性。从那里开始非常简单,除了您需要生成用于密码重置的有效代码外,该代码需要正确编码到请求路径,否则会抱怨它无效。

最后,由于只有一种用于生成令牌的异步方法,因此我们必须将Invoke更改为异步方法,以便我们等待代码生成。经过测试并可以正常工作

相关问题