使用身份验证 ASP.NET MVC 中的用户

Authenticate user in ASP.NET MVC with identities

我对实际身份验证的工作方式感到非常困惑,因此 [Authorize] 不会将我重定向到登录页面。

这是我的配置:

public class IdentityConfig
{
    public void Configuration(IAppBuilder app)
    {
        app.CreatePerOwinContext(() => new MyANTon.DataContext.AntContext());
        app.CreatePerOwinContext<UserManager>(UserManager.Create);
        app.CreatePerOwinContext<RoleManager<AppRole>>((options, context) =>
            new RoleManager<AppRole>(
                new RoleStore<AppRole>(context.Get<MyANTon.DataContext.AntContext>())));

        app.UseCookieAuthentication(new CookieAuthenticationOptions
        {
            AuthenticationType = DefaultAuthenticationTypes.ApplicationCookie,
            LoginPath = new PathString("/Home/Login"),
        });
    }
}

在控制器中,我想调用一个 Authenticate(string Email, String Password) 方法,验证用户和 return 一个布尔值。但是,我不知道实际的身份验证是如何工作的。 在 FormsAuthentication 我会创建一个工单,我要为身份做什么?

这是我拥有的:

public static async System.Threading.Tasks.Task<bool> AuthUserAsync(string Email, string Password)
    {
        using (var db = new AntContext())
        {

            string hashedPW = GetHash(Password);
            bool userValid = db.Users.Any(user => user.Email == Email && user.Password == hashedPW);
            if (userValid)
            {
                var actUser = db.Users.FirstOrDefault(u => u.Email == Email && u.Password == hashedPW);
                if (actUser != null && !actUser.IsLocked)                   
                {
                    /** What do I do here? **/
                }
                else if (actUser.IsLocked)
                {
                    LoggingServices.AuthLog(actUser.Email, "Hat versucht auf ein gesperrtes Konto zuzugreifen.");
                }
            }
            return false;
        }
    }

当你想要 Login 进入你的 web-site 时,你将你的 token 发送到 client 并且你可以使用它来请求和响应许多,在其他一句话,你必须用你的服务器端登录。

但是当你想从 web-sitelogout 时,你的客户端必须知道你想 logout 这不仅仅适用于服务器,客户端应该做这个问题用于注销。

我想建议你Token-JWT

如果您想了解 JWT,请点击 here

如果你愿意,我会为你创建一个示例。

您正朝着正确的方向前进,您正在做的是使用 OAuth 来促进令牌的映射并让 OWin 处理浏览器信息。那么,通过使用 [Authorize] 属性,就像您正在做的那样,您如何处理身份的签名?就像上面提到的 Forms 身份验证一样,您仍然必须创建 Identity/Claim 令牌。在我的项目中,我会做这样的事情,

   protected void IdentitySignin(IUserModel userModel, string providerKey = null, bool isPersistent = true)
        {
            var claims                                                         = new List<Claim>
            {
                new Claim(ClaimTypes.NameIdentifier, userModel.Id.ToString()),
                new Claim(ClaimTypes.Name, userModel.UserName),
                new Claim("UserContext", userModel.ToString())
            };
            var identity                                                       = new ClaimsIdentity(claims, DefaultAuthenticationTypes.ApplicationCookie);
            AuthenticationManager.SignIn(new AuthenticationProperties
            {
                IsPersistent                                                   = isPersistent,
                ExpiresUtc                                                     = DateTime.UtcNow.AddDays(7)
            }, identity);
        }

这会强制 OWIN/OAuth 登录用户,在我的 web.config 中,我有以下内容:

<system.webserver>
    <authentication mode="None" />
</system.webserver>

并注销我的用户,并强制浏览器获取新令牌:

 protected void IdentitySignout()
        {
            AuthenticationManager.SignOut(DefaultAuthenticationTypes.ApplicationCookie,
                                            DefaultAuthenticationTypes.ExternalCookie);
        }

我的 AuthenticationManager 是这样定义的:

   private IAuthenticationManager AuthenticationManager
        {
            get { return HttpContext.GetOwinContext().Authentication; }
        }

这是 Microsoft.OWin.IOwinContext 的一部分,如果不存在,您必须添加引用。

您可以通过 web.config 文件或基本控制器处理未经授权的用户,我选择了这样的基本控制器选项:

protected override void OnActionExecuting(ActionExecutingContext filterContext)
        {
            if (UserContext == null || UserContext.Id.Equals(Guid.Empty))
            {
                if (filterContext.Controller.GetType()     == typeof(AccountController) || filterContext.Controller.GetType() == typeof(HomeController)) return;
                filterContext.Result                       = new RedirectResult("/Home/Index");
                return;
            }
}

但如果需要,您也可以通过 AuthorizeAttribute 来完成。 link 将详细介绍处理 Oauth 和 Asp.Net MVC,乍一看可能令人望而生畏,但如果您决定将它们合并到发布版本中,它会为使用其他提供程序提供很好的布局。

https://www.codeproject.com/Articles/577384/Introduction-to-OAuth-in-ASP-NET-MVC