且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

ASP.NET MVC和登录认证

更新时间:2023-02-14 17:00:37

您可以自己写您的身份验证服务。
这里有一个小故事:

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 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");
        }

和您的SessionContext被类(即。)

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;
        }
    }

最后下列标记添加到您的标记在web.config文件:

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

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

而现在你只需要在每个需要authentication.like该控制器的头部插入[Autorize]属性:

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

[Authorize]
public class ClassController : Controller
{
   ...
}