Подтвердить что ты не робот

Аутентификация cookie OWIN без идентификации ASP.NET

Я новичок в ASP.NET MVC 5, и мне очень неудобно использовать Identity authentication + authorization framework. Я знаю, что это новая функция структуры ASP.NET MVC, поэтому я хотел бы применить альтернативный способ реализации проверки подлинности в приложении m.

Возможно ли это? Я читал, что могу использовать FormsAuthenticationModule. Это хорошая альтернатива? Как я могу использовать его в приложении на основе MVC 5?

4b9b3361

Ответ 1

Я чувствовал то же самое, когда смотрел на Identity. Он добавляет много ненужных абстракций и не подходит в моем случае, что у меня есть устаревшая система, которая реализовала персонализированный процесс проверки подлинности.

Тонны примеров там об аутентификации OWIN с использованием Identity и EF по умолчанию, что заставляет разработчиков путать, что OWIN должен идти с Identity и Entity Framework.

Но технически вы можете лишить Identity использовать только аутентификацию cookie OWIN (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");
}

Ответ 2

Без использования методов безопасности Owin: Itz My Controller Coding

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