11

I have searched many posts here regarding custom user authentication but none have addressed all of my concerns

I am new to ASP.NET MVC and have used traditional ASP.NET (WebForms) but don't know how build a login / authentication mechanism for a user using ASP.NET MVC.

protected void Login1_Authenticate(object sender, AuthenticateEventArgs e)
{
    string userName = Login1.UserName;
    string password = Login1.Password;
    bool rememberUserName = Login1.RememberMeSet;

    if (validateuser(userName, password))
    {
        //Fetch the role
        Database db = DatabaseFactory.CreateDatabase();


        //Create Command object
        System.Data.Common.DbCommand cmd = db.GetStoredProcCommand("sp_RolesForUser");
        db.AddInParameter(cmd, "@Uid", System.Data.DbType.String, 15);
        db.SetParameterValue(cmd, "@Uid", Login1.UserName);
        System.Data.IDataReader reader = db.ExecuteReader(cmd);
        System.Collections.ArrayList roleList = new System.Collections.ArrayList();
        if (reader.Read())
        {
            roleList.Add(reader[0]);
            string myRoles = (string)roleList[0];

            //Create Form Authentication ticket
            //Parameter(1) = Ticket version
            //Parameter(2) = User ID
            //Parameter(3) = Ticket Current Date and Time
            //Parameter(4) = Ticket Expiry
            //Parameter(5) = Remember me check
            //Parameter(6) = User Associated Roles in this ticket
            //Parameter(7) = Cookie Path (if any)
            FormsAuthenticationTicket ticket = new FormsAuthenticationTicket(1, userName, DateTime.Now,
            DateTime.Now.AddMinutes(20), rememberUserName, myRoles, FormsAuthentication.FormsCookiePath);

            //For security reasons we may hash the cookies
            string hashCookies = FormsAuthentication.Encrypt(ticket);
            HttpCookie cookie = new HttpCookie(FormsAuthentication.FormsCookieName, hashCookies);

            // add the cookie to user browser
            Response.Cookies.Add(cookie);

            if (HttpContext.Current.User.IsInRole("Administrators"))
            {
                Response.Redirect("~/Admin/Default.aspx");
            }
            else
            {
                string returnURL = "~/Default.aspx";

                // get the requested page
                //string returnUrl = Request.QueryString["ReturnUrl"];
                //if (returnUrl == null)
                //   returnUrl = "~/Default.aspx";
                Response.Redirect(returnURL);
            }
        }
    }
}

  protected bool validateuser(string UserName, string Password)
  {
    Boolean boolReturnValue = false;

    //Create Connection using Enterprise Library Database Factory
    Database db = DatabaseFactory.CreateDatabase();

    //Create Command object
    DbCommand cmd = db.GetStoredProcCommand("sp_ValidateUser");

    db.AddInParameter(cmd, "@userid", DbType.String, 15);
    db.SetParameterValue(cmd, "@userid", Login1.UserName);

    db.AddInParameter(cmd, "@password", DbType.String, 15);
    db.SetParameterValue(cmd, "@password", Login1.Password);

    db.AddOutParameter(cmd, "@retval", DbType.Int16, 2);
    db.ExecuteNonQuery(cmd);

    int theStatus = (System.Int16)db.GetParameterValue(cmd, "@retval");

    if (theStatus > 0)  //Authenticated user
        boolReturnValue = true;
    else  //UnAuthorized...
        boolReturnValue = false;

    return boolReturnValue;
}

I don't really know how to translate that ASP.NET code into MVC-esque architecture; and I'm still at a loss on how to implement authentication in ASP.NET MVC.

What do I need to do? How do I implement the above code in ASP.NET MVC? What am I missing from that code?

George Stocker
  • 57,289
  • 29
  • 176
  • 237
user239684
  • 349
  • 1
  • 5
  • 16
  • 4
    Aspnet mvc ships with a full blown membership component, what features does it mess? You may read http://www.codeplex.com/MvcMembership to get started – Jay Zeng Dec 28 '09 at 17:54
  • Strongly agree with Jay Zeng. Don't (incorrectly) reinvent membership: http://blogs.teamb.com/craigstuntz/2009/09/09/38390/ – Craig Stuntz Dec 28 '09 at 17:59
  • Well can it be as customizable as I want? as my user table and roles table is different because I am tying to develop a HELP DESK application and the registration is not for the public as only administrator can create the users. Can I customize this way? – user239684 Dec 28 '09 at 18:36
  • Yes. Out of the box membership allows for limiting actions (like registration) by username or role. In fact, our shipping applications do exactly what you describe. – Craig Stuntz Dec 28 '09 at 18:53
  • any good video or tutorial available so I can take a speedy start and can implement using SqlServer 2008? Care to share the links? – user239684 Dec 28 '09 at 18:56

4 Answers4

32

You can write your authentication service by yourself. Here is a short story:

Your user model class(i.e.)

public class User
    {
        public int UserId { get; set; }
        public string Name { get; set; }
        public string Username { get; set; }
        public string Password { get; set; }
        public string Email { get; set; }
        public bool IsAdmin { get; set; }
    }

Your Context class(i.e.)

public class Context : DbContext
{
    public Context()
    {
        base.Configuration.LazyLoadingEnabled = false;
    }
    protected override void OnModelCreating(DbModelBuilder modelBuilder)
    {
        Database.SetInitializer<Context>(null);
        base.OnModelCreating(modelBuilder);
        modelBuilder.Conventions.Remove<PluralizingTableNameConvention>();
    }
    public DbSet<User> Users { get; set; }
}

Your user repository class(i.e.)

 public class UserRepository
    {
        Context context = new Context();       
        public User GetByUsernameAndPassword(User user)
        {
            return context.Users.Where(u => u.Username==user.Username & u.Password==user.Password).FirstOrDefault();
        }
    }

And your user application class(i.e.)

public class UserApplication
    {
        UserRepository userRepo = new UserRepository();     
        public User GetByUsernameAndPassword(User user)
        {
            return userRepo.GetByUsernameAndPassword(user);
        }
    }

Here is your account controller(i.e.)

public class AccountController : Controller
    {
        UserApplication userApp = new UserApplication();
        SessionContext context = new SessionContext();

        public ActionResult Login()
        {
            return View();
        }
        [HttpPost]
        public ActionResult Login(User user)
        {
            var authenticatedUser = userApp.GetByUsernameAndPassword(user);
            if (authenticatedUser != null)
            {
                context.SetAuthenticationToken(authenticatedUser.UserId.ToString(),false, authenticatedUser);
                return RedirectToAction("Index", "Home");
            }
           
            return View();
        }

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

And your SessionContext class(i.e.)

public class SessionContext
    {
        public void SetAuthenticationToken(string name, bool isPersistant, User userData)
        {
            string data = null;
            if (userData != null)
                data = new JavaScriptSerializer().Serialize(userData);

            FormsAuthenticationTicket ticket = new FormsAuthenticationTicket(1, name, DateTime.Now, DateTime.Now.AddYears(1), isPersistant, userData.UserId.ToString());

            string cookieData = FormsAuthentication.Encrypt(ticket);
            HttpCookie cookie = new HttpCookie(FormsAuthentication.FormsCookieName, cookieData)
            {
                HttpOnly = true,
                Expires = ticket.Expiration
            };

            HttpContext.Current.Response.Cookies.Add(cookie);
        }

        public User GetUserData()
        {
            User userData = null;

            try
            {
                HttpCookie cookie = HttpContext.Current.Request.Cookies[FormsAuthentication.FormsCookieName];
                if (cookie != null)
                {
                    FormsAuthenticationTicket ticket = FormsAuthentication.Decrypt(cookie.Value);

                    userData = new JavaScriptSerializer().Deserialize(ticket.UserData, typeof(User)) as User;
                }
            }
            catch (Exception ex)
            {
            }

            return userData;
        }
    }

And finally add the following tag to your <system.web> tag in web.config file:

<authentication mode="Forms">
  <forms loginUrl="~/Account/Login" timeout="2880" />
</authentication>

And now you just need to insert [Authorize] attribute on the head of each controller that needs authentication.like this:

[Authorize]
public class ClassController : Controller
{
   ...
}
Hamid Reza
  • 2,913
  • 9
  • 49
  • 76
5

Given your comments regarding tutorials, please see the asp.net/mvc learning section on security.

In particular, this tutorial on creating a secure ASP.NET MVC 5 web app with log in, email confirmation and password reset.

Dan Atkinson
  • 11,391
  • 14
  • 81
  • 114
0

1-Add This Code To WebConfig

<system.web>

       <authentication mode="Forms">
       <forms loginUrl="/Log/Login" timeout="20"></forms>
       </authentication>

</system.web>

2-To Action Use This code

[HttpPost]
public async Task<ActionResult> Login(string UserName,string Password)
{
    var q = await userpro.Login(UserName, Password);
    if (q.Resalt)
    {

        //Add User To Cookie
        Response.Cookies.Add(FormsAuthentication.GetAuthCookie(UserName, false));

        return RedirectToAction("ShowUsers", "User");
    }
    else
    {
        ViewBag.Message = q.Message;
        return View();
    }

}

3-You Should Add This Attribute To Your Action [Authorize]

4-To This Code You Can Get UserName In Cookie

public async Task<ActionResult> ShowUsers(int Page = 0)
{
    string UserName= User.Identity.Name;
    return View(await user.GetAllUser(Page));
}
Diako Hasani
  • 1,384
  • 13
  • 14
-1

Code:

using Microsoft.AspNet.Identity;


if (Request.IsAuthenticated)
{
    return View();
}
RBT
  • 24,161
  • 21
  • 159
  • 240
Zeeshan
  • 17
  • 1
  • 10
    Please edit with more information. Code-only and "try this" answers are discouraged, because they contain no searchable content, and don't explain why someone should "try this". We make an effort here to be a resource for knowledge. – abarisone Jun 22 '16 at 11:59