【问题标题】:Authenticate user in ASP.NET MVC with identities使用身份验证 ASP.NET MVC 中的用户
【发布时间】:2019-03-04 15:29:35
【问题描述】:

我对实际身份验证的工作方式非常困惑,因此[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) 方法,对用户进行身份验证并返回一个布尔值。但是,我不知道实际的身份验证是如何工作的。 在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;
        }
    }

【问题讨论】:

    标签: c# authentication asp.net-mvc-5 asp.net-identity


    【解决方案1】:

    当您希望Login 进入您的web-site 时,您将您的token 发送到client,您可以使用它来请求和响应很多,换句话说,您必须使用您的服务器端登录.

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

    我想建议你Token-JWT

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

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

    【讨论】:

    • 您能看看我在 Smart way for User Authorization (without creating table, etc.) in ASP.NET MVC 上的问题吗?如果它适合我​​的情况,我想使用它。谢谢...
    • 你好,你知道授权属性吗?
    • 是的,我使用了 ASP.NET Identity。
    • 你使用了JWT令牌吗?还是使用不同的?
    • 我没有使用JWT令牌,但如果它更合适我想使用它(必须适用于MVC而不是Core)。
    【解决方案2】:

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

       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 来实现。此链接将详细介绍如何处理 Oauth 和 Asp.Net MVC,起初可能看起来令人生畏,但如果您决定将其他提供程序合并到发布版本中,它提供了一个很好的布局。

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

    【讨论】:

    • 谢谢,我接受了你的回答。为了让它工作,我不得不改变一些事情。我做了大多数方法static(不是绝对必要的),而不是写HttpContext.GetOwinContext().Authentication;我不得不写HttpContext.Current.GetOwinContext().Authentication;。除此之外,就我现在所看到的而言,它运行良好。
    • 快速跟进问题:我是否不能在剃须刀页面上使用基于角色的授权,例如 [Authorize (Roles = "admin")]
    • 我会在这里查看这两个站点,stackoverflow.com/questions/13264496/…dougrathbone.com/blog/2011/07/24/…。授权属性是令人难以置信的模块化,几乎可以帮助您完成任何任务。我什至有一个,它将用户的 IP 地址与全球数据库进行比较,以根据他们的原籍国重定向他们。
    • @KevinBBurns 保持会话 2 分钟怎么样?我们可以用这种方法设置会话过期时间吗?
    • @hexadecimal 我认为您正在寻找的是滑动到期,oauth.com/oauth2-servers/access-tokens/access-token-lifetime
    猜你喜欢
    • 2013-08-29
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-04-27
    • 1970-01-01
    • 2012-06-17
    • 2010-09-16
    • 1970-01-01
    相关资源
    最近更新 更多