search
HomeBackend DevelopmentC#.Net TutorialExample of implementing Forms authentication authentication process in asp.net mvc

This article mainly introduces the Forms authentication authentication process in asp.net MVC. The editor thinks it is quite good. Now I will share it with you and give you a reference. Let’s follow the editor and take a look.

Verification process

1. User login

1. Verification Form: ModelState.IsValid
2. Verify username and password: Verify by querying the database
3. If the username and password are correct, save the cookie on the client to save the user login status: SetAuthCookie
1): From Find the username and some necessary information in the database, and save the additional information to UserData
 2): Save the username and UserData to the FormsAuthenticationTicket ticket
3): Encrypt the ticket Encrypt
4) : Save the encrypted ticket in Cookie and send it to the client
4. Jump to the page before login
5. If login fails, return to the current view

2 , Verify login

1. Register the PostAuthenticateRequest event function in Global to parse the Cookie data sent by the client
1): Judge by HttpContext.Current.User.Identity Whether the user is logged in (FormsIdentity, IsAuthenticated, AuthenticationType)
2): Parse the Value from the cookie of the Request of the HttpContext, decrypt it to get the FormsAuthenticationTicket and get the UserData
2, role verification
1): Add the Authorize feature to the Action , role verification can be performed
 2): Perform role authentication in the IsInRole method of HttpContext.Current.User (needs to be rewritten)

1. User login

1. Set web.config

Set redirect login page

<system.web>
<authentication mode="Forms">
  <forms name="loginName" loginUrl="/UserInfo/login" cookieless="UseCookies" path="/" protection="All" timeout="30"></forms>
</authentication>
</system.web>

Comment out

<modules>
  <!--<remove name="FormsAuthentication" />-->
</modules>

2. Login verification controller

Methods modified with "[Authorize]" in the controller reject anonymity.

 public class UserInfoController : Controller //控制器
 {
 //身份验证过滤器
  [Authorize]
  public ActionResult Index()
  {
   return View();
  }
 }

Login in the controller

   /// <summary>
  /// 用户登录
  /// </summary>
  /// <returns></returns>
  public ActionResult login()
  {
   return View();
  }  
  [HttpPost]
  public ActionResult login(loginModels login) {
   if (ModelState.IsValid)
   {
    var model = db.Admininfo.FirstOrDefault(a => a.AdminAccount == login.AdminAccount && a.AdminPwd == login.AdminPwd);
    if (model != null)
    {
     //存入票据(用户登录的时候去存信息,如果有信息直接去登录)
     var dtoModel = new Users
     {
      id = model.id,
      AdminPwd = model.AdminPwd,
      AdminAccount=model.AdminAccount
     };
     //调用
     SetAuthCookie(dtoModel);
     //获取登录地址
     var returnUrl = Request["ReturnUrl"];
     //判断登录地址是不是空值
     if (!string.IsNullOrWhiteSpace(returnUrl))
     {      
      return Redirect(returnUrl);
     }
     else
     {
      //return RedirectiToAction
      return Redirect("/Home/index");
     }

    }
    else
    {
     ModelState.AddModelError("", "账号密码不对");
     return View(login);
    }
   }
   else
   {
    ModelState.AddModelError("", "输入的信息有误");
    return View(login);

   }

Cookie the login account

  /// <summary>
  /// 对登录账号进行cookie
  /// </summary>
  /// <param name="model"></param>
  public void SetAuthCookie(Users loginModel) {
   //1、将对象转换成json
   var userdata = loginModel.ToJson();
   //2、创建票据FormsAuthenticationTicket
   FormsAuthenticationTicket ticket = new FormsAuthenticationTicket(2,"loginUser",DateTime.Now,DateTime.Now.AddDays(1), false, userdata);
   //对票据进行加密 
   var tickeEncrypt = FormsAuthentication.Encrypt(ticket);
   //创建Cookie,定义
   HttpCookie cookie = new HttpCookie(FormsAuthentication.FormsCookieName, tickeEncrypt);
   cookie.HttpOnly = true;
   cookie.Secure = FormsAuthentication.RequireSSL;
   cookie.Domain = FormsAuthentication.CookieDomain;
   cookie.Path = FormsAuthentication.FormsCookiePath;
   cookie.Expires = DateTime.Now.Add(FormsAuthentication.Timeout);
   //先移除cookie,在添加cookie
   Response.Cookies.Remove(FormsAuthentication.FormsCookieName);
   Response.Cookies.Add(cookie);
  }

3. Add model files to Models

 public class loginModels
 {
  /// <summary>
  /// 账号
  /// </summary>
  [DisplayName("账号")]
  [Required(ErrorMessage = "账号不能为空")] 
  public string AdminAccount { get; set; }
  /// <summary>
  /// 密码
  /// </summary>
  [DisplayName("密码")]
  [Required(ErrorMessage = "密码不能为空")]
  public string AdminPwd { get; set; }
 }

4. Login code in Views:

Copy code The code is as follows:

@using (Html.BeginForm("Login", "Account", new { ReturnUrl = ViewBag.ReturnUrl }, FormMethod.Post, new { 
@class = "form-horizontal", role = "form" }))

5.Global settings

protected void Application_AuthenticateRequest(object sender, EventArgs e)
  {
   //1、通过sender获取http请求
   // HttpApplication app = new HttpApplication();//实例化
   HttpApplication app = sender as HttpApplication;
   //2、拿到http上下文
   HttpContext context = app.Context;
   //3、根据FormsAuthe,来获取cookie
   var cookie = context.Request.Cookies[FormsAuthentication.FormsCookieName];
   if (cookie != null)
   {
    //获取cookie的值
    var ticket = FormsAuthentication.Decrypt(cookie.Value);
    if (!string.IsNullOrWhiteSpace(ticket.UserData))
    {
     //把一个字符串类别变成实体模型
     var model = ticket.UserData.ToObject<AdmininfoViewModel>();
     //var acount = model.AdminAccount; //获取账号
     context.User = new MyFormsPrincipal<AdmininfoViewModel>(ticket, model);
     //MyFormsPrincipal.Identity = new FormsIdentity(ticket);
     // MyFormsPrincipal.userdata;

    }
   }
  }

6. Log out

In the controller

  /// <summary>
  /// 退出登录
  /// </summary>
  public ActionResult loginout()
  {
   //删除票据
   FormsAuthentication.SignOut();
   //清除cookie
   Response.Cookies[FormsAuthentication.FormsCookieName].Expires = DateTime.Now.AddDays(-1);
   Response.Cookies.Remove(FormsAuthentication.FormsCookieName);
   return RedirectToAction("Index", "Home");
 
  }

View jump link

@Html.ActionLink("安全退出","loginout","Users")

The above is the detailed content of Example of implementing Forms authentication authentication process in asp.net mvc. For more information, please follow other related articles on the PHP Chinese website!

Statement
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Mastering C# .NET Design Patterns: From Singleton to Dependency InjectionMastering C# .NET Design Patterns: From Singleton to Dependency InjectionMay 09, 2025 am 12:15 AM

Design patterns in C#.NET include Singleton patterns and dependency injection. 1.Singleton mode ensures that there is only one instance of the class, which is suitable for scenarios where global access points are required, but attention should be paid to thread safety and abuse issues. 2. Dependency injection improves code flexibility and testability by injecting dependencies. It is often used for constructor injection, but it is necessary to avoid excessive use to increase complexity.

C# .NET in the Modern World: Applications and IndustriesC# .NET in the Modern World: Applications and IndustriesMay 08, 2025 am 12:08 AM

C#.NET is widely used in the modern world in the fields of game development, financial services, the Internet of Things and cloud computing. 1) In game development, use C# to program through the Unity engine. 2) In the field of financial services, C#.NET is used to develop high-performance trading systems and data analysis tools. 3) In terms of IoT and cloud computing, C#.NET provides support through Azure services to develop device control logic and data processing.

C# .NET Framework vs. .NET Core/5/6: What's the Difference?C# .NET Framework vs. .NET Core/5/6: What's the Difference?May 07, 2025 am 12:06 AM

.NETFrameworkisWindows-centric,while.NETCore/5/6supportscross-platformdevelopment.1).NETFramework,since2002,isidealforWindowsapplicationsbutlimitedincross-platformcapabilities.2).NETCore,from2016,anditsevolutions(.NET5/6)offerbetterperformance,cross-

The Community of C# .NET Developers: Resources and SupportThe Community of C# .NET Developers: Resources and SupportMay 06, 2025 am 12:11 AM

The C#.NET developer community provides rich resources and support, including: 1. Microsoft's official documents, 2. Community forums such as StackOverflow and Reddit, and 3. Open source projects on GitHub. These resources help developers improve their programming skills from basic learning to advanced applications.

The C# .NET Advantage: Features, Benefits, and Use CasesThe C# .NET Advantage: Features, Benefits, and Use CasesMay 05, 2025 am 12:01 AM

The advantages of C#.NET include: 1) Language features, such as asynchronous programming simplifies development; 2) Performance and reliability, improving efficiency through JIT compilation and garbage collection mechanisms; 3) Cross-platform support, .NETCore expands application scenarios; 4) A wide range of practical applications, with outstanding performance from the Web to desktop and game development.

Is C# Always Associated with .NET? Exploring AlternativesIs C# Always Associated with .NET? Exploring AlternativesMay 04, 2025 am 12:06 AM

C# is not always tied to .NET. 1) C# can run in the Mono runtime environment and is suitable for Linux and macOS. 2) In the Unity game engine, C# is used for scripting and does not rely on the .NET framework. 3) C# can also be used for embedded system development, such as .NETMicroFramework.

The .NET Ecosystem: C#'s Role and BeyondThe .NET Ecosystem: C#'s Role and BeyondMay 03, 2025 am 12:04 AM

C# plays a core role in the .NET ecosystem and is the preferred language for developers. 1) C# provides efficient and easy-to-use programming methods, combining the advantages of C, C and Java. 2) Execute through .NET runtime (CLR) to ensure efficient cross-platform operation. 3) C# supports basic to advanced usage, such as LINQ and asynchronous programming. 4) Optimization and best practices include using StringBuilder and asynchronous programming to improve performance and maintainability.

C# as a .NET Language: The Foundation of the EcosystemC# as a .NET Language: The Foundation of the EcosystemMay 02, 2025 am 12:01 AM

C# is a programming language released by Microsoft in 2000, aiming to combine the power of C and the simplicity of Java. 1.C# is a type-safe, object-oriented programming language that supports encapsulation, inheritance and polymorphism. 2. The compilation process of C# converts the code into an intermediate language (IL), and then compiles it into machine code execution in the .NET runtime environment (CLR). 3. The basic usage of C# includes variable declarations, control flows and function definitions, while advanced usages cover asynchronous programming, LINQ and delegates, etc. 4. Common errors include type mismatch and null reference exceptions, which can be debugged through debugger, exception handling and logging. 5. Performance optimization suggestions include the use of LINQ, asynchronous programming, and improving code readability.

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Atom editor mac version download

Atom editor mac version download

The most popular open source editor

SecLists

SecLists

SecLists is the ultimate security tester's companion. It is a collection of various types of lists that are frequently used during security assessments, all in one place. SecLists helps make security testing more efficient and productive by conveniently providing all the lists a security tester might need. List types include usernames, passwords, URLs, fuzzing payloads, sensitive data patterns, web shells, and more. The tester can simply pull this repository onto a new test machine and he will have access to every type of list he needs.

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

DVWA

DVWA

Damn Vulnerable Web App (DVWA) is a PHP/MySQL web application that is very vulnerable. Its main goals are to be an aid for security professionals to test their skills and tools in a legal environment, to help web developers better understand the process of securing web applications, and to help teachers/students teach/learn in a classroom environment Web application security. The goal of DVWA is to practice some of the most common web vulnerabilities through a simple and straightforward interface, with varying degrees of difficulty. Please note that this software