dir.by  
  Поиск  
Компьютер, программы
.NET Core
 Аутентификация (authentication) это login/register/logout в приложении ASP.NET Core MVC 
посмотрели 5720 раз
обновлено: 28 March 2021
Аутентификация - процесс идентификации пользователя т.е. это login/register/logout

Аутентификация в ASP.NET Core делается так:
register
1) пользователь открывает register web page и в форме вводит ноый login, password

2) Вызывается метод Register в AuthenticationController и внутри сохраняем в базу данных такой login и password

Вот код программы:

  C#  
public class AuthenticationController : Controller
{
     ...
     [HttpPost]
     [ValidateAntiForgeryToken]
     public ActionResult Register(UserRegisterViewModel model)
     {
          if (ModelState.IsValid)
          {
               User user = _myDbContext.Users.FirstOrDefault(u => u.LoginEmail == model.LoginEmail);

               if (user == null)
               {
                    // use Automapper to convert ViewModel to database model
                    user = _mapper.Map<User>(model);

                    // add logn, password to database
                    _myDbContext.Users.Add(user);
                    _myDbContext.SaveChanges();

                    // redirect to home page
                    return RedirectToAction("Index", "Home");
               }
               else
               {
                    ModelState.AddModelError("", "Error! User with this Email already exists");
               }
          }

          return View(model);
     }
}


Смотреть всю программу на GitHub.com: WebCoreBookLibrary с использованием login/register/logout
login
1) пользователь открывает login web page и в форме вводит login, password

2) Вызывается метод Login в AuthenticationController и внутри проверяем есть ли в базе данных такой login и password

Если login и password соответствует это значит настоящий пользователь и мы заполняем C# класс ClaimsIdentity

Вот код программы:

  C#  
public class AuthenticationController : Controller
{
     ...
     [HttpPost]
     [ValidateAntiForgeryToken]
     public ActionResult Login(UserLoginViewModel model)
     {
          if (ModelState.IsValid)
          {
               User user = _myDbContext.Users.FirstOrDefault(u => u.LoginEmail == model.LoginEmail && u.Password == model.Password);

               if (user != null)
               {
                    // create Identity
                    ClaimsIdentity identity = new ClaimsIdentity("My");

                    // add Claims
                    identity.AddClaims(new List<Claim>
                    {
                         new Claim(ClaimTypes.Name, user.UserName),
                         new Claim(ClaimTypes.Email, user.LoginEmail)
                    });

                    // create Principal
                    ClaimsPrincipal principal = new ClaimsPrincipal(identity);

                    // set to cookie
                    HttpContext.SignInAsync(principal, new AuthenticationProperties { IsPersistent = true, ExpiresUtc = (DateTime.Now.AddHours(8)) });

                    // set identity to HttpContext.User (will use in HttpContext.User in any method in Controller)
                    HttpContext.User = new ClaimsPrincipal(identity);


                    // теперь в любом методе Contoller мы всегда получим HttpContext.User и на View отобразим соответствующую информацию о пользователе (залогинен или нет, графики таблицы будем рисовать в зависимоти от пользователя)

                    return RedirectToAction("Index", "Home");
               }

               ModelState.AddModelError("", "Error! User not exist with this email and password");
          }

          return View(model);
     }
}


Смотреть всю программу на GitHub.com: WebCoreBookLibrary с использованием login/register/logout
logout
1) пользователь на web page нажимает на logout

2) Вызывается метод Logoff() в AuthenticationController и мы очищаем Cookie

Вот код программы:

  C#  
public class AuthenticationController : Controller
{
     ...
     public ActionResult Logoff()
     {
          // clear Cookie
          HttpContext.SignOutAsync();

          // redirect to home page
          return RedirectToAction("Index", "Home");
     }
}


Смотреть всю программу на GitHub.com: WebCoreBookLibrary с использованием login/register/logout
 
← Previous topic
Telerik (Kendo UI) in ASP.NET Core MVC (connect Kendo js files using NPM and Webpack)
 
Next topic →
Install a new version (.NET 9) for Visual Studio 2022 | Error: NETSDK1 The current .NET SDK does not support targeting .NET 9.0. Either target .NET 7.0 or lower, or use a version of the .NET SDK that supports .NET 9.0.
 
Your feedback ... Comments ...
   
Your Name
Your comment (www links can only be added by a logged-in user)

 
What is .NET Core?
Creating a New .NET Core Console App
ASP.NET Core
What is ASP.NET Core?
Creating a new application ASP.NET Core
ASP.NET Core MVC
Creating a new application ASP.NET Core MVC
Built-in IoC container in ASP.NET Core
<BR>
Database (Entity Framework) in ASP.NET Core MVC
Entity Framework in the ASP.NET Core MVC application. Using Code First (we write c# code, and the tables in the database are created by ourselves)
<BR>
Telerik (Kendo UI) in ASP.NET Core MVC
Telerik (Kendo UI) in ASP.NET Core MVC (connect Kendo js files using NPM and Webpack)
<BR>
Authentication (login/register/logout) in the ASP.NET Core MVC application
Authentication is login/register/logout in the ASP.NET Core MVC application
Additional topics, questions
Install a new version (.NET 9) for Visual Studio 2022 | Error: NETSDK1 The current .NET SDK does not support targeting .NET 9.0. Either target .NET 7.0 or lower, or use a version of the .NET SDK that supports .NET 9.0.
Install the new version (.NET 6.0) for Visual Studio 2022. Note! .NET 6.0 is not installed and does not work for Visual Studio 2019
Installing a new version (.NET Core 2.2) for Visual Studio 2019
Choosing between ASP.NET Core and ASP.NET?
Porting code to .NET Core from the .NET Framework
Error "unable to connect to web server "iis express" | ASP.NET Core | Visual Studio 2017
Error "This site can"t be reached" when run ASP.NET Core application | Solution: Recreate the Self-Signed HTTPS Certificate for localhost in IIS Express
WWW sites for learning
Sites to learn ASP.NET Core

  Ваши вопросы присылайте по почте: info@dir.by