jnemecz
jnemecz

Reputation: 3608

How to create user authentication in .NET web application?

I am creating ASP.NET MVC web application. I have data model User:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;

namespace Knihovna.Models
{
    public class User
    {
        public int UserId { get; set; }
        public string Name { get; set; }
        public string Login { get; set; }
        public string Password { get; set; }
        public List<Book> Books { get; set; }
    }
}

and I need to create user registration and user login. Application needs to know If user is logged in.

Is there some best practises how to do it? Save logged in user in session?

Upvotes: 2

Views: 833

Answers (2)

Leniel Maccaferri
Leniel Maccaferri

Reputation: 102408

There's no need to mess up with the Session object.

As you're already working with ASP.NET MVC, you probably have an AccountController in your Controllers folder. This controller has the basic authentication methods in place.

I suggest you take a look at this tutorial by the ASP.NET team that explains and then shows you how to use Authentication + Authorization in ASP.NET MVC.

The default Visual Studio project template for ASP.NET MVC automatically enables forms authentication when new ASP.NET MVC applications are created. It also automatically adds a pre-built account login page implementation to the project – which makes it really easy to integrate security within a site.

NerdDinner Step 9: Authentication and Authorization

Upvotes: 2

nerdybeardo
nerdybeardo

Reputation: 4675

I would use the ASP.NET membership and role provider model. If you would like to do it with your custom tables you can create a class that inherits from Membership Provider. There are a number of methods you can implement to support things like changing passwords, forgot password etc... but the one for logging in would be ValidateUser

public sealed class MyMembershipProvider : MembershipProvider
{
    public override bool ValidateUser(string username, string password)
    {
        bool isValid = false;
        // your authentication logic here
        var ticket = new FormsAuthenticationTicket(
                    1,
                    YOUR_USER_ID_HERE,
                    DateTime.Now,
                    DateTime.Now.AddMinutes(30),
                    false,
                    name,
                    FormsAuthentication.FormsCookiePath);

                var authCookie = new HttpCookie(FormsAuthentication.FormsCookieName, FormsAuthentication.Encrypt(ticket));
                HttpContext.Current.Response.Cookies.Add(authCookie);

        return isValid;
    }
}

You will also need to create a role provider if you would like there to be different levels of users. To do so you will inherit from the RoleProvider class.

public sealed class MyRoleProvider : RoleProvider
{
   // Implement logic here
}

To authorize certain areas of your application you would use the Authorize attribute.

public class MyController : Controller
{
     [Authorize(Roles="Role1,Role2")]
     public ActionResult Index()
     {
         // Implement your code
     }
}

Finally there is some configuration in the web.config you have to do to get it to use your providers.

<authentication mode="Forms">
  <forms loginUrl="~/Login" timeout="2880"/>
</authentication>
<membership defaultProvider="MyMembershipProvider" userIsOnlineTimeWindow="20">
  <providers>
    <clear/>
    <add name="MyMembershipProvider" type="Your.NameSpace.MyMembershipProvider" enablePasswordRetrieval="false" enablePasswordReset="false" requiresQuestionAndAnswer="false" writeExceptionsToEventLog="false"/>
  </providers>
</membership>
<roleManager enabled="true" defaultProvider="MyRoleProvider" cacheRolesInCookie="true">
  <providers>
    <clear/>
    <add name="MyRoleProvider" type="Your.NameSpace.MyRoleProvider"/>
  </providers>
</roleManager>

You can find more information about the memberhsip and role providers on MSDN

Upvotes: 2

Related Questions