不带ASP的OWIN cookie认证.净的身份

本文关键字:身份 认证 OWIN ASP 不带 cookie | 更新日期: 2023-09-27 18:03:36

我是ASP新手。. NET MVC 5和我发现身份验证+授权框架非常不舒服。我知道这是ASP的一个新特性。因此,我想在我的应用程序中应用另一种方法来实现身份验证。

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

不带ASP的OWIN cookie认证.净的身份

我在看Identity时也有同样的感觉。它增加了许多不必要的抽象,并且不适合我的情况,因为我有实现自定义身份验证工作流的遗留系统。

有很多关于OWIN认证默认使用Identity和EF的例子,这让开发人员感到困惑,认为OWIN必须使用Identity和Entity Framework。

但是从技术上讲,您可以去掉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");
}

不使用自己的安全方法:我的控制器编码

[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>