ASP.NET MVC 和登录身份验证

问题描述 投票:0回答:5

我在这里搜索了许多有关自定义用户身份验证的帖子,但没有一个能够解决我所有的问题

我是 ASP.NET MVC 新手,并且使用过传统的 ASP.NET (WebForms),但不知道如何使用 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;
}

我真的不知道如何将 ASP.NET 代码转换为 MVC 式架构;我仍然不知道如何在 ASP.NET MVC 中实现身份验证。

我需要做什么?如何在 ASP.NET MVC 中实现上述代码?我从该代码中缺少什么?

c# .net asp.net asp.net-mvc
5个回答
32
投票

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

您的用户模型类(即)

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

你的 Context 类(即)

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

您的用户存储库类(即)

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

以及您的用户应用程序类(即)

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

这是您的帐户控制器(即)

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 类(即)

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 文件中的 标签中:

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

现在你只需要在每个需要认证的控制器的头部插入

[Authorize]
属性即可。就像这样:

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

5
投票

鉴于您对教程的评论,请参阅asp.net/mvc学习安全部分

特别是,这个关于创建具有登录、电子邮件确认和密码重置功能的安全 ASP.NET MVC 5 Web 应用程序的教程。


0
投票

1-将此代码添加到

WebConfig

<system.web>

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

</system.web>

2-操作使用此代码

[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-您应该将此属性添加到您的操作中

[Authorize]

4-通过这段代码你可以在Cookie中获取用户名

public async Task<ActionResult> ShowUsers(int Page = 0)
{
    string UserName= User.Identity.Name;
    return View(await user.GetAllUser(Page));
}

0
投票

命名空间 sss.Controllers { 公共类 AccountController(UserManager _userManager, SignInManager _signInManager, RoleManager _roleManager,ProniaContext _context) : 控制器 { 公共 IActionResult 注册() { 返回视图(); } [http邮报] 公共异步任务寄存器(RegisterVM vm) {

        if (!ModelState.IsValid) return View(vm);
        AppUser user = new AppUser
        {
            Email = vm.Email,
            Name = vm.Name,
            Surname = vm.Surname,
            UserName = vm.Username
            
        };
        
        IdentityResult result = await _userManager.CreateAsync(user, vm.Password);
        if (!result.Succeeded)
        {
            foreach (var error in result.Errors)
            {
                ModelState.AddModelError("",error.Description);
            }
            return View(vm);
        }
        await //_userManager.AddToRoleAsync(user,UserRole.Member.ToString());

        return RedirectToAction(nameof(Index), "Home");
    }
    public IActionResult Login()
    {
        return View();
    }
    [HttpPost]
    public async Task<IActionResult> Login(LoginVM vm)
    {
        if (!ModelState.IsValid) return View(vm);
        AppUser? user = await _userManager.FindByNameAsync(vm.UserNameOrEmail);
        if (user == null)
        {
            user = await _userManager.FindByEmailAsync(vm.UserNameOrEmail);
            if (user == null)
            {
                ModelState.AddModelError("","incorreckted password and email");
                return View(vm);
            }
        }
        //await _signInManager.CheckPasswordSignInAsync(user, vm.Password, true);

        var result = await _signInManager.PasswordSignInAsync(user,vm.Password,vm.RememberMe,true);
        if (result.IsLockedOut)
        {
            ModelState.AddModelError("","3 time incorect password - " + user.LockoutEnd.Value.ToString("HH:mm:ss"));
            return View(vm);
        }
        return RedirectToAction("Index", "Home");
    }
    public async Task<IActionResult> Logout()
    {
        await _signInManager.SignOutAsync();
        return RedirectToAction(nameof(Login));
    }

    public async Task<IActionResult> CreateRoles()
    {
        foreach (UserRole role in Enum.GetValues(typeof(UserRole)))
        {
            if (!await _roleManager.RoleExistsAsync(role.ToString()))
            {
                await _roleManager.CreateAsync(new IdentityRole
                {
                    Name = role.ToString()
                });
            }
           
        }

        return Content("ok");

    }
}

-1
投票

代码:

using Microsoft.AspNet.Identity;


if (Request.IsAuthenticated)
{
    return View();
}
© www.soinside.com 2019 - 2024. All rights reserved.