不使用ASP.NET身份验证的OWIN cookie身份验证

24

我对ASP.NET MVC 5还是新手,使用Identity身份验证和授权框架让我感到非常不适。我知道这是ASP.NET MVC框架的一个新功能,因此我想在我的应用程序中应用替代方法来实现身份验证。

这有可能吗?我读到可以使用FormsAuthenticationModule。这是一个好的选择吗?我该如何在基于MVC 5的应用程序中使用它?


OWin身份验证框架的重点在于它是完全模块化的。只需运行“Install-Package Microsoft.Owin.Security.Cookies”并将其安装到您的“IAppBuilder”上即可。 - Aron
为什么你不想使用Identity呢?OWIN是一种新的注入身份验证的方式。如果你不喜欢它,可以构建自己的OWIN模块并注入它。Identity是认证用户的新方法。如果你不喜欢整个社交认证部分,那就不要使用它。FormsAuthentication是一种旧的方式。 - LockTar
请检查我的答案:http://stackoverflow.com/questions/26485575/ 它可能会对你有所帮助。 - Monah
2个回答

41

看到Identity时,我有同样的感觉。它添加了很多不必要的抽象,不适合我这种已经实现了自定义身份验证工作流的旧系统。

有大量关于使用Identity和实体框架进行OWIN身份验证的示例,默认情况下会让开发人员感到困惑,认为OWIN必须与Identity和实体框架一起使用。

但从技术上讲,您可以剥离Identity,仅使用OWIN cookie身份验证 (Microsoft.Owin.Security.Cookies)。代码变得非常简单,下面是我从我的代码中获取的示例,消除了琐碎的东西:

[HttpPost]
public ActionResult Login(LoginViewModel model, string returnUrl)
{
    var user = _userService.GetByEmail(model.Email);

    //check username and password from database, naive checking: 
    //password should be in SHA
    if (user != null && (user.Password == model.Password)) 
    {
        var claims = new[] {
                new Claim(ClaimTypes.Name, user.Name),
                new Claim(ClaimTypes.Email, user.Email),
                // can add more claims
            };

        var identity = new ClaimsIdentity(claims, "ApplicationCookie");

        // Add roles into claims
        var roles = _roleService.GetByUserId(user.Id);
        if (roles.Any())
        {
            var roleClaims = roles.Select(r => new Claim(ClaimTypes.Role, r.Name));
            identity.AddClaims(roleClaims);
        }

        var context = Request.GetOwinContext();
        var authManager = context.Authentication;

        authManager.SignIn(new AuthenticationProperties 
               { IsPersistent = model.RememberMe }, identity);

        return RedirectToAction("Index", "Home");
    }
    // login failed.            
}

public ActionResult LogOut()
{
    var ctx = Request.GetOwinContext();
    var authManager = ctx.Authentication;

    authManager.SignOut("ApplicationCookie");
    return RedirectToAction("Login");
}

谢谢,这很完美!但是……我需要为用户处理角色,使用您的方法是否可行? - davioooh
@davioooh:是的,可以处理像表单认证这样的角色,我更新了我的代码以将更多角色添加到声明中。 - cuongle
1
完美!非常感谢你! - davioooh
1
简洁明了。 - Kai Hartmann
@cuongle 在上下文中找不到owin.Environment项,出现错误。有什么想法吗?我看了解决方法,但它们都没有起作用。 - user5871859

1

不使用 Owin 安全方法: 这是我的控制器编码

[HttpPost]
        [ValidateAntiForgeryToken]
        public ActionResult Login(Employee emp, string returnUrl)
           {
            using(AdaptiveProjectEntities db = new AdaptiveProjectEntities())
            {
                string email = emp.Email;
               // byte[] en = System.Text.Encoding.UTF8.GetBytes(emp.Password);
                //var ee = Convert.ToBase64String(en);
                string pass = emp.Password;

                bool userValid = db.Employees.Any(user => user.Email == email && user.Password == pass);
                    if(userValid)
                    {
                        FormsAuthentication.SetAuthCookie(email, false);



                         if (Url.IsLocalUrl(returnUrl) && returnUrl.Length > 1 && returnUrl.StartsWith("/")
                    && !returnUrl.StartsWith("//") && !returnUrl.StartsWith("/\\"))
                {
                    return Redirect(returnUrl);
                }
                else
                {

                    return RedirectToAction("Index", "Projects");
                }
            }
            else
            {
                ModelState.AddModelError("", "The user name or password provided is incorrect.");
            }
                    }



            return View(emp); 

       }
        public ActionResult Logout()
        {
            FormsAuthentication.SignOut();
            return RedirectToAction("Login", "Login");
        }
    }
}

查看:

<div class="container" style="margin-right:50%">
    <div class="row">
        <div class="col-md-12 col-md-offset-7" style="bottom:-250px">
           <div class="panel panel-default" style="margin-right:15%">
                <div class="panel-heading" style="padding-bottom:5%">

                    <center><h3 style="margin-right:80px">Login</h3></center>
                    @*</div>*@
                    @using (Html.BeginForm())
                    {
                        <div class="modal-body">

                            @Html.AntiForgeryToken()

                            <div class="form-horizontal" style="margin-right: 10%;">
                                @Html.ValidationSummary(true, "", new { @class = "text-danger" })


                                <div class="form-group">
                                    @Html.LabelFor(model => model.Email, htmlAttributes: new { @class = "control-label col-md-3" })
                                    <div class="col-md-9">
                                        @Html.EditorFor(model => model.Email, new { htmlAttributes = new { @class = "form-control", type = "email", required = "required" } })
                                        @Html.ValidationMessageFor(model => model.Email, "", new { @class = "text-danger" })
                                    </div>
                                </div>
                                <div class="form-group">
                                    @Html.LabelFor(model => model.Password, htmlAttributes: new { @class = "control-label col-md-3" })
                                    <div class="col-md-9">
                                        @Html.EditorFor(model => model.Password, new { htmlAttributes = new { @class = "form-control", type = "password", required = "required" } })
                                        @Html.ValidationMessageFor(model => model.Password, "", new { @class = "text-danger" })
                                    </div>
                                </div>

                            </div>
                            <div>
                                <input class="btn btn-primary pull-left col-lg-offset-1" type="submit" value="Login" style="margin-left:35%" />
                            </div>

                        </div>


                    }
                </div>
            </div>
        </div>
        </div>
    </div>
    </div>

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接