当前位置: 首页 > 编程语言 > C#

ASP.NETMVC和登录认证分享

时间:2023-04-11 01:11:51 C#

ASP.NETMVC和登录认证我在这里搜索了很多关于自定义用户认证的帖子,但都没有解决我所有的问题我是ASP.NETMVC新手并使用传统的ASP.NET(WebForms),但不知道如何为使用ASP.NETMVC的用户构建登录/身份验证机制。protectedvoidLogin1_Authenticate(objectsender,AuthenticateEventArgse){stringuserName=Login1.UserName;字符串密码=Login1.Password;boolrememberUserName=Login1.RememberMeSet;if(validateuser(userName,password)){//获取角色Databasedb=DatabaseFactory.CreateDatabase();//创建命令对象System.Data.Common.DbCommandcmd=db.GetStoredProcCommand("sp_RolesForUser");db.AddInParameter(cmd,"@Uid",System.Data.DbType.String,15);db.SetParameterValue(cmd,"@Uid",Login1.UserName);System.Data.IDataReaderreader=db.ExecuteReader(cmd);System.Collections.ArrayListroleList=newSystem.Collections.ArrayList();如果(reader.Read()){roleList.Add(reader[0]);字符串myRoles=(字符串)roleList[0];//CreateFormAuthenticationticket//Parameter(1)=Ticketversion//Parameter(2)=UserID//Parameter(3)=TicketCurrentDateandTime//Parameter(4)=TicketExpiry//Parameter(5))=记住我检查//Parameter(6)=UserAssociatedRolesinthisticket//Parameter(7)=CookiePath(ifany)FormsAuthenticationTicketticket=newFormsAuthenticationTicket(1,userName,DateTime.Now,DateTime.Now.AddMinutes(20),rememberUserName,myRoles,FormsAuthentication.FormsCookiePath);//出于安全原因,我们可能会散列cookiesstringhashCookies=FormsAuthentication.Encrypt(ticket);HttpCookiecookie=newHttpCookie(FormsAuthentication.FormsCookieName,hashCookies);//将cookie添加到用户浏览器Response.Cookies.Add(cookie);如果(HttpContext.Current.User.IsInRole("Administrators")){Response.Redirect("~/Admin/Default.aspx");}else{stringreturnURL="~/Default.aspx";//获取请求的页面//stringreturnUrl=Request.QueryString["ReturnUrl"];//if(returnUrl==null)//returnUrl="~/Default.aspx";Response.Redirect(returnURL);}}}}protectedboolvalidateuser(stringUserName,stringPassword){BooleanboolReturnValue=false;//使用E创建连接企业库数据库工厂数据库db=DatabaseFactory.CreateDatabase();//创建命令对象DbCommandcmd=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);inttheStatus=(System.Int16)db.GetParameterValue(cmd,"@retval");if(theStatus>0)//认证用户boolReturnValue=true;else//未授权...boolReturnValue=false;返回布尔返回值;我真的不知道如何将ASP.NET代码转换为MVC式架构;我仍然对如何在ASP.NETMVC中执行此操作感到困惑不知所措,无法实现身份验证我需要做什么?上面的代码如何在ASP.NETMVC中实现呢?我从该代码中遗漏了什么?您可以自己编写身份验证服务。这是简短的故事:您的用户模型类(即)公共类用户{publicintUserId{get;放;}公共字符串名称{得到;放;}publicstring用户名{get;放;}公共字符串密码{得到;放;}公共字符串电子邮件{得到;放;}publicboolIsAdmin{得到;放;}}您的用户存储库类(即)publicclassUserRepository{Contextcontext=newContext();publicUserGetByUsernameAndPassword(Useruser){returncontext.Users.Where(u=>u.Username==user.Username&u.Password==user.Password).FirstOrDefault();}}和您的用户应用程序类(即)publicclassUserApplication{UserRepositoryuserRepo=newUserRepository();publicUserGetByUsernameAndPassword(用户用户){returnuserRepo.GetByUsernameAndPassword(用户);}}这是您的帐户控制器(即)publicclassAccountController:Controller{UserApplicationuserApp=newUserApplication();SessionContextcontext=newSessionContext();publicActionResultLogin(){returnView();}[HttpPost]publicActionResultLogin(Useruser){varauthenticatedUser=userApp.GetByUsernameAndPassword(用户);if(authenticatedUser!=null){context.SetAuthenticationToken(authenticatedUser.UserId.ToString(),false,authenticatedUser);返回RedirectToAction("索引","主页");}返回视图();}publicActionResultLogout(){FormsAuthentication.SignOut();返回RedirectToAction("索引","主页");}和你的SessionContext类(即)publicclassSessionContext{publicvoidSetAuthenticationToken(stringname,boolisPersistant,UseruserData){stringdata=null;if(userData!=null)data=newJavaScriptSerializer().Serialize(userData);FormsAuthenticationTicketticket=newFormsAuthenticationTicket(1,name,DateTime.Now,DateTime.Now.AddYears(1),isPersistant,userData.UserId.ToString());字符串cookieData=FormsAuthentication.Encrypt(ticket);HttpCookiecookie=newHttpCookie(FormsAuthentication.FormsCookieName,cookieData){HttpOnly=true,Expires=ticket.Expiration};HttpContext.Current.Response.Cookies.Add(cookie);}publicUserGetUserData(){用户userData=null;尝试{HttpCookiecookie=HttpContext.Current.Request.Cookies[FormsAuthentication.FormsCookieName];如果(cookie!=null){FormsAuthenticationTicketticket=FormsAuthentication。解密(cookie.Value);userData=newJavaScriptSerializer().Deserialize(ticket.UserData,typeof(User))作为用户;}}catch(Exceptionex){}返回用户数据;最后将以下标记添加到web.配置文件中的标记:现在您只需在每个需要身份验证的控制器的头部插入[Autorize]属性,如下所示:[Authorize]publicclassClassController:Controller{...}鉴于您对教程的评论,请参阅有关安全的asp.net/mvc学习部分。特别是,本教程将创建一个安全的ASP.NETMVC5Web应用程序,其中包含登录、电子邮件确认和密码重置。代码:以上就是《C#学习教程:ASP.NETMVC与登录认证》的全部内容。如果对大家有用,需要详细了解C#学习教程,希望大家多多关注——使用Microsoft.AspNet.Identity;如果(Request.IsAuthenticated){返回视图();}本文收集自网络,不代表立场。如涉及侵权,请点击右侧联系管理员删除。如需转载请注明出处: