Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

OWIN cookie authentication without ASP.NET Identity

I'm new to ASP.NET MVC 5 and I'm finding very uncomfortable with Identity authentication + authorization framework. I know this is a new feature of the ASP.NET MVC framework, so I'd like to apply an alternative way to implement authentication in m y application.

Is it possible? I read I could use the FormsAuthenticationModule. Is this a good alternative? How can I use it in a MVC 5 based application?

like image 760
davioooh Avatar asked Jul 20 '15 07:07

davioooh


People also ask

Does ASP.NET Core identity use cookies?

ASP.NET Core provides a cookie authentication mechanism which on login serializes the user details in form of claims into an encrypted cookie and then sends this cookie back to the server on subsequent requests which gets validated to recreate the user object from claims and sets this user object in the HttpContext so ...

Which authentication uses cookies for user authentication?

Cookie authentication uses HTTP cookies to authenticate client requests and maintain session information. It works as follows: The client sends a login request to the server.


2 Answers

I felt the same way when taking a look at Identity. It adds lots of unnecessary abstractions and does not suit with my case that I have legacy system which implemented customised authentication work-flow.

Tons of examples out there about OWIN authentication using Identity and EF by default which makes developers confused that OWIN has to go with Identity and Entity Framework.

But technically, you are able to strip out Identity to use only OWIN cookie authentication (Microsoft.Owin.Security.Cookies). The code turns out very simple, below is example I got from my code which eliminates trivial things:

[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"); } 
like image 71
cuongle Avatar answered Sep 17 '22 12:09

cuongle


Without Using Owin Security Methods: 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");         }     } } 

View:

<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> 
like image 40
Jegadeesh Waran Avatar answered Sep 18 '22 12:09

Jegadeesh Waran