Аутентификация (login/register/logout) в приложении "Планирование дел, задач" | ASP.NET MVC | Visual Studio 2017
last updated: 15 January 2019
Шаг 1. В web.config включаем аутентификацию форм
Внутри секции <system.web> добавим
<authentication mode="Forms">
<forms name="cookies" timeout="2880" loginUrl="~/Authentication/Login" ></forms>
</authentication>
Файл web.config
<?xml version="1.0" encoding="utf-8" ?>
<!--
For more information on how to configure your ASP.NET application, please visit
https://go.microsoft.com/fwlink/?LinkId=301880
-->
<configuration>
<configSections>
<!-- For more information on Entity Framework configuration, visit http://go.microsoft.com/fwlink/?LinkID=237468 -->
<section name="entityFramework" type="System.Data.Entity.Internal.ConfigFile.EntityFrameworkSection, EntityFramework, Version=6.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" requirePermission="false" />
</configSections>
<appSettings>
<add key="webpages:Version" value="3.0.0.0" />
<add key="webpages:Enabled" value="false" />
<add key="ClientValidationEnabled" value="true" />
<add key="UnobtrusiveJavaScriptEnabled" value="true" />
</appSettings>
<system.web>
<compilation debug="true" targetFramework="4.6.1" />
<httpRuntime targetFramework="4.6.1" />
<authentication mode="Forms" >
<forms name="cookies" timeout="2880" loginUrl="~/Authentication/Login" ></forms>
</authentication>
</system.web>
<runtime>
<assemblyBinding xmlns="urn:schemas-microsoft-com:asm.v1" >
<dependentAssembly>
<assemblyIdentity name="System.Web.Helpers" publicKeyToken="31bf3856ad364e35" />
<bindingRedirect oldVersion="1.0.0.0-3.0.0.0" newVersion="3.0.0.0" />
</dependentAssembly>
<dependentAssembly>
<assemblyIdentity name="System.Web.WebPages" publicKeyToken="31bf3856ad364e35" />
<bindingRedirect oldVersion="1.0.0.0-3.0.0.0" newVersion="3.0.0.0" />
</dependentAssembly>
<dependentAssembly>
<assemblyIdentity name="System.Web.Mvc" publicKeyToken="31bf3856ad364e35" />
<bindingRedirect oldVersion="1.0.0.0-5.2.4.0" newVersion="5.2.4.0" />
</dependentAssembly>
</assemblyBinding>
</runtime>
<system.codedom>
<compilers>
<compiler language="c#;cs;csharp" extension=".cs" type="Microsoft.CodeDom.Providers.DotNetCompilerPlatform.CSharpCodeProvider, Microsoft.CodeDom.Providers.DotNetCompilerPlatform, Version=2.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35" warningLevel="4" compilerOptions="/langversion:default /nowarn:1659;1699;1701" />
<compiler language="vb;vbs;visualbasic;vbscript" extension=".vb" type="Microsoft.CodeDom.Providers.DotNetCompilerPlatform.VBCodeProvider, Microsoft.CodeDom.Providers.DotNetCompilerPlatform, Version=2.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35" warningLevel="4" compilerOptions="/langversion:default /nowarn:41008 /define:_MYTYPE=\"Web\" /optionInfer+" />
</compilers>
</system.codedom>
<connectionStrings>
<add name="MyConnection1" connectionString="Data Source=EVGEN\SQLEXPRESS;Initial Catalog=MyDatabase1;Integrated Security=True;" providerName="System.Data.SqlClient" />
</connectionStrings>
<entityFramework>
<defaultConnectionFactory type="System.Data.Entity.Infrastructure.SqlConnectionFactory, EntityFramework" />
<providers>
<provider invariantName="System.Data.SqlClient" type="System.Data.Entity.SqlServer.SqlProviderServices, EntityFramework.SqlServer" />
</providers>
</entityFramework>
</configuration>
Шаг 2. Добавим файл UserContext.cs в папку Models (класс User и класс UserContext для работы с Базой данных)
Нажмем правой клавишей мыши на папку "Models" → Add → New Item
C#
В файле UserContext.cs напишем код
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Data.Entity;
namespace Plan.Models
{
public class UserContext : DbContext
{
// MyConnection1 это соединение с базой данных описанное в файле web.config
public UserContext() : base("MyConnection1" )
{
}
public DbSet<User> Users { get; set; }
}
public class User
{
public int Id { get; set; }
public string Email { get; set; }
public string Password { get; set; }
}
}
Шаг 3. Добавим файл UserLoginRegister.cs в папку Models (класс UserLogin и класс UserRegister)
При логине в форме мы будем использовать
класс UserLogin
При регистрации в форме мы будем использовать
класс UserRegister
Добавим файл UserLoginRegister.cs в папку Models
C#
В файле UserLoginRegister.cs напишем код
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.ComponentModel.DataAnnotations;
namespace Plan.Models
{
public class UserLogin
{
[Required ]
public string Name { get; set; }
[Required ]
[DataType(DataType.Password)]
public string Password { get; set; }
}
public class UserRegister
{
[Required ]
public string Name { get; set; }
[Required ]
[DataType(DataType.Password)]
public string Password { get; set; }
[Required ]
[DataType(DataType.Password)]
[Compare("Password" , ErrorMessage = "Пароли не совпадают" )]
public string ConfirmPassword { get; set; }
[Required ]
public int Age { get; set; }
}
}
Шаг 4. Добавляем AuthenticationController
Чтобы добавить контроллер в наш проект в окне Solution Explorer нажимаем правой клавишей мыши на
Controllers → Add → Controller
C#
В файле AuthenticationController.cs напишем код
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using System.Web.Security;
using Plan.Models;
namespace Plan.Controllers
{
public class AuthenticationController : Controller
{
public ActionResult Login()
{
return View();
}
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Login(UserLogin model)
{
if (ModelState.IsValid)
{
// поиск пользователя в базе данных
User user = null;
using (UserContext db = new UserContext())
{
user = db.Users.FirstOrDefault(u => u.Email == model.Name && u.Password == model.Password);
}
// нашли пользователя
if (user != null)
{
// устанавливаем cookie
FormsAuthentication.SetAuthCookie(model.Name, true);
// переходим
return RedirectToAction("Index" , "Home" );
}
else
{
// выводим ошибку
ModelState.AddModelError("", "Пользователя с таким логином и паролем нет" );
}
}
return View(model);
}
public ActionResult Register()
{
return View();
}
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Register(UserRegister model)
{
if (ModelState.IsValid)
{
// ищем пользователя в базе данных
User user = null;
using (UserContext db = new UserContext())
{
user = db.Users.FirstOrDefault(u => u.Email == model.Name);
}
// пользователя нет базе данных
if (user == null)
{
// создаем нового пользователя
using (UserContext db = new UserContext())
{
db.Users.Add(new User { Email = model.Name, Password = model.Password});
db.SaveChanges();
user = db.Users.Where(u => u.Email == model.Name && u.Password == model.Password).FirstOrDefault();
}
// пользователь добавлен в базу данных
if (user != null)
{
// устанавливаем cookie
FormsAuthentication.SetAuthCookie(model.Name, true);
// переходим
return RedirectToAction("Index" , "Home" );
}
}
else
{
// выводим ошибку
ModelState.AddModelError("", "Пользователь с таким логином уже существует" );
}
}
return View(model);
}
public ActionResult Logoff()
{
FormsAuthentication.SignOut();
return RedirectToAction("Index" , "Home" );
}
}
}
Шаг 5. Добавляем View с названием Login
Нажимаем правой клавишей мыши по методу Login в файле AuthenticationController.cs и нажимаем на Add View ...
В файле Login.cshtml напишем код
@model Plan.Models.UserLogin
<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="width=device-width" />
<title> Вход</title>
</head>
<body>
<!-- подключаем файлы Bootstrap -->
<link href='@Url.Content("~/Content/bootstrap.min.css" )' rel="stylesheet" type="text/css" />
<script src='@Url.Content("~/Scripts/bootstrap.min.js" )'></script>
@using (Html.BeginForm())
{
@Html.AntiForgeryToken()
<div class="pl-4" >
@Html.ValidationSummary(true)
<!-- заголовок -->
<div class="form-group" >
<h2> Вход</h2>
</div>
<!-- login -->
<div class="form-group" >
@Html.LabelFor(model => model.Name, new { @class = "control-label" })
<div>
@Html.EditorFor(model => model.Name, new { @class = "form-control" })
@Html.ValidationMessageFor(model => model.Name)
</div>
</div>
<!-- password -->
<div class="form-group" >
@Html.LabelFor(model => model.Password, new { @class = "control-label" })
<div>
@Html.EditorFor(model => model.Password, new { @class = "form-control" })
@Html.ValidationMessageFor(model => model.Password)
</div>
</div>
<!-- Войти -->
<div class="form-group" >
<input type="submit" value="Войти" class="btn btn-info" />
</div>
</div>
}
</body>
</html>
Шаг 6. Добавляем View с названием Register
Нажимаем правой клавишей мыши по методу Register в файле AuthenticationController.cs и нажимаем на Add View ...
В файле Register.cshtml напишем код
@model Plan.Models.UserRegister
<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="width=device-width" />
<title> Регистрация</title>
</head>
<body>
<!-- подключаем файлы Bootstrap -->
<link href='@Url.Content("~/Content/bootstrap.min.css" )' rel="stylesheet" type="text/css" />
<script src='@Url.Content("~/Scripts/bootstrap.min.js" )'></script>
@using (Html.BeginForm())
{
@Html.AntiForgeryToken()
<div class="pl-4" >
@Html.ValidationSummary(true)
<!-- Заголовок -->
<div class="form-group" >
<h2> Регистрация</h2>
</div>
<!-- login -->
<div class="form-group" >
@Html.LabelFor(model => model.Name, new { @class = "control-label" })
<div>
@Html.EditorFor(model => model.Name, new { @class = "form-control" })
@Html.ValidationMessageFor(model => model.Name)
</div>
</div>
<!-- password -->
<div class="form-group" >
@Html.LabelFor(model => model.Password, new { @class = "control-label" })
<div>
@Html.EditorFor(model => model.Password, new { @class = "form-control" })
@Html.ValidationMessageFor(model => model.Password)
</div>
</div>
<!-- confirm password -->
<div class="form-group" >
@Html.LabelFor(model => model.ConfirmPassword, new { @class = "control-label" })
<div>
@Html.EditorFor(model => model.ConfirmPassword, new { @class = "form-control" })
@Html.ValidationMessageFor(model => model.ConfirmPassword)
</div>
</div>
<!-- Сохранить -->
<div class="form-group" >
<input type="submit" value="Сохранить" class="btn btn-info" />
</div>
</div>
}
</body>
</html>
Шаг 7. В файле Views/MasterTemplate.cshtml напишем код
cshtml
@{
Layout = null;
}
@{
// переменные чтобы выставить активность или не активность в кнопках меню
string MenuActiveList = "active" ;
string MenuActiveReport = "";
string MenuActiveChange = "";
int ImgVersionToRefresh = 8;
}
<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="width=device-width" />
<title> MasterTemplate</title>
</head>
<body>
<!-- подключаем файлы jQuery -->
<script src='@Url.Content("~/Scripts/jquery-3.0.0.min.js" )'></script>
<!-- подключаем файлы Bootstrap -->
<link href='@Url.Content("~/Content/bootstrap.min.css" )' rel="stylesheet" type="text/css" />
<script src='@Url.Content("~/Scripts/bootstrap.min.js" )'></script>
<!-- HTML элементы -->
<div class="container" >
<div class="row" >
<div class="col-md-12" style="">
<!-- верхнее меню1 -->
<nav class="navbar navbar-expand-sm bg-light navbar-light" >
<ul class="navbar-nav mr-auto" >
<li class="nav-item" >
@Html.Label("Планирование дел, задач" , new { @class = "" })
</li>
</ul>
<!-- кнопки в меню "Выйти" , "Войти" , "Регистрация" -->
<!-- Эти кнопки с правой стороны потому что в предыдущем ul стоит class='... mr-auto' -->
<ul class="navbar-nav" >
<!-- проверяем пользователь залогинен? -->
@if (User.Identity.IsAuthenticated)
{
<!-- имя пользователя -->
<li class="nav-item" >
<span class="navbar-text" >
[ @User.Identity.Name ]
</span>
</li>
<!-- кнопка 'Выйти' -->
<li class="nav-item" >
<a class="nav-link" href='@Url.Action("Logoff" , "Authentication" )'> Выйти... </a>
</li>
}
else
{
<!-- кнопка 'Войти' -->
<li class="nav-item" >
<a class="nav-link" href='@Url.Action("Login" , "Authentication" )'> Войти... </a>
</li>
<!-- мой разделитель -->
<li class="nav-item" >
<span class="navbar-text" >
|
</span>
</li>
<!-- Регистрация -->
<li class="nav-item" >
<a class="nav-link" href='@Url.Action("Register" , "Authentication" )'> Регистрация... </a>
</li>
}
</ul>
</nav>
</div>
</div>
<div class="row" >
<div class="col-md-12" style="min-height:600px; padding-left:0px; padding-right:0px; border:3px solid gray; background-repeat:repeat-y; background-image:url(@Url.Content(" ~/Content/Images/PageBorder.png?version=" + ImgVersionToRefresh));" >
<!-- верхнее меню2 -->
<nav class="navbar navbar-expand-sm bg-info navbar-info" >
<!-- кнопки в меню "Список дел" , "Отчеты" , "Управление (поменять, добавить, удалить)" -->
<ul class="navbar-nav mr-auto" >
<!-- кнопка "Список дел" -->
<li class="nav-item ml-5" >
<a class="btn btn-info @MenuActiveList" href='@Url.Action("Index" )'>Список дел</a>
</li>
<!-- кнопка "Отчеты" -->
<li class="nav-item ml-5" >
<a class="btn btn-info @MenuActiveReport" href='@Url.Action("Report" )'>Отчеты</a>
</li>
<!-- кнопка "Управление" -->
<li class="nav-item ml-5" >
<a class="btn btn-info @MenuActiveChange" href='@Url.Action("Change" )'>Управление (поменять, добавить, удалить)</a>
</li>
</ul>
</nav>
<!-- тут вставится содержимое обычного представления -->
<div style="padding-left:60px; padding-top:20px;" >
@RenderBody()
</div>
</div>
</div>
</div>
</body>
</html>
Шаг 8. Запустим ASP.NET MVC приложение
Нажимаем Регистрация
При входе вводим логин и пароль
Когда вошли , мы видим имя залогиненного пользователя.