dir.by  
  Поиск  
Компьютер, программы
ASP.NET MVC (Model-View-Controller website)
 Что такое аутентификация (login/register/logout) в ASP.NET MVC ? 
посмотрели 9508 раз
обновлено: 13 January 2019
Аутентификация - процесс идентификации пользователя т.е. это login/register/logout
Аутентификация в ASP.NET сводится, по сути, к заполнению HttpContext.User.Identity

Для идентификации пользователя в ASP.NET 5 специально добавлен интерфейс IIdentity.
Этот интерфейс имеет три свойства (AuthenticationType, IsAuthenticated и Name),
Эти свойства должны быть реализованы в вашем классе.

Очень много самописанных способов для реализации IIdentity
Вы можете написать свой собственный способ.
Все в своих проектах используют IIdentity по своему.
Аутентификация в приложении ASP.NET MVC
Способ 1
Использовать класс WebSecurity
WebSecurity сохраняет информаию о пользователе в свои таблицы в базе данных.

Минусы:
WebSecurity может работать только с Microsoft SQL Server базами данных.
Он не может работать с MySQL, NoSQL, поскольку использует специфичные для MS SQL Server выражения SQL.
WebSecurity создает 5 таблиц в базе данных (мне кажется это излишне)
Способ 2
ASP.NET Forms Auth

Работает так:

• Вызов FormsAuthentication.SetAuthCookie или FormsAuthentication.RedirectFromLoginPage выставляет cookie, в котором лежит зашифрованный username.

• Глобальный HTTP Module просматривает все запросы и если види куку - аутентифицирует запрос.

Минусы:
• Подвержен атаке CSRF - любой левый сайт может отрендерить форму, которая сделает POST в ваше приложение, и этот POST пройдет. Для не-апи от этого спасает стандартный механизи Anti Forgery. Для API - не спасает ничего.

• Не дает сохранить в куку ничего, кроме username. Поэтому вы вынуждены или на каждом запросе вычитывать дополнительные данные для юзера из базы, или вписывать вместо username что-то свое.

• Не позволяет отзывать cookies. Нет механизма вылогинивания пользователя раз и навсегда.

Пример:
Аутентификация (login/register/logout) в ASP.NET MVC используя аутентификацию форм FormsAuthentication.SetAuthCookie(model.Name, true);
Способ 3
Cookie Authentication из ASP.NET Core Identity

По сути, исправленная версия Forms Auth. Несмотря на то, что является частью ASP.NET Identity, может быть использован и без него.

Работает по тому же принципу, что FormsAuth, но исправляет основную проблему:

Позволяет сохранять в cookie не просто username, а набор claims (утверждений, вида имя: а, роль: б, id пользователя: 5), что позволяет приложению не лезть в базу на каждом запросе и не использовать хитрые схемы сериализации JWT в username.

При этом cookie все равно вечные, неотзывные (валидация "отозвано/не отозвано" лежит на разработчике, через событие ValidatePrincipal).
Способ 4
OAuth Bearer Tokens

Механизим, позволяющий надежно аутентифицировать пользователя на основе заголовка Authentication: Bearer. Предназначен для API и для SPA приложений.

Решает проблемы CSRF и проблему отзыва.

CSRF: Вместо cookie используется http header, который клиентская часть должна сама добавлять в каждый запрос. Нет подставляемой автоматически cookie - нет CSRF.

Отзыв: токены разделяются на два вида:
access_token - короткоживущий, stateless, используется для аутентификации.
refresh_token - должгоживущий, обычно statefull, используется для выдачи новых access_token.
Минус - не применим в не-SPA приложении, т.к. браузер сам не шлет соответствующий заголовок.

Процесс подключения:

В качестве основы можно взять стандартный не-core шаблон ASP.NET Web App): Cоответствующий middleware уже будет подключен в самом шаблоне, вызовом app.UseOAuthBearerTokens(OAuthOptions).

Если у вас отдельная, не SPA страница логина, то со стороны бэкенда - все готово (наиболее вероятный случай)
• Редиректите всех подряд (до логина) на /Account/Authorize?client_id=web&response_type=token&state=
• Пользователю показывает страницу логина
• После логина - его редиректит на /#access_token=nRUQN1j-wVFoMQ....
• Берете токен и шлете его в заголовке вида Authentication: Bearer nRUQN1j-wVFoMQ....

И выставляете лайфтайм токена таким, чтобы он не заканчивался в течении одной пользовательской сессии (в смысле одного посещения приложения).

По сути вы получаете Cookies Auth для приложения + OAuth для API.

Если у вас интегрированная в SPA страница логина - вам придется получать токены ajax-запросом к '/token', предъявляя grant (в вашем случае - password):
• На сервере: переопределяете ApplicationOAuthProvider.GrantResourceOwnerCredentials так, чтобы он проверял имя и пароль, и пропускал тех, кого нужно.

• На клиенте: отправляете имя и пароль в виде
Content-Type: application/x-www-form-urlencoded
grant_type=password&username=johndoe&password=A3ddj3w

• Получаете токен, шлете его в каждом запросе.

Вывод: Сторонний SSO -по сути сводится к тому, что ваше приложение проверяет аутентификацию/авторизацию пользователя где-то на стороне, и по ее прохождению залогинивает пользователя в самого себя, используя механизи Cookie Auth. Т.е. случай "подключен SSO" с точки зрения работы с Web API сводится к случаю "Cookies Auth для приложения + OAuth для API" выше.
 
← Previous topic
Entity Framework in the ASP.NET MVC application. Using Code First (we write c# code, and the tables in the database are created by ourselves)
 
Next topic →
Example: Authentication (login/register/logout) in MVC ASP.NET using FormsAuthentication.SetAuthCookie(model. Name, true);
 
Your feedback ... Comments ...
   
Your Name
Your comment (www links can only be added by a logged-in user)

 
What is MVC in ASP.NET ?
Creating a new application ASP.NET MVC
Controller
Pass the data from the controller to the view in the MVC ASP.NET. Using ViewBag, ViewData, TempData, Model (strongly typed view)
View
What are Razor View and Operators in MVC ASP.NET
Create a variable and display it in View in the MVC ASP.NET
@using inside View in the MVC ASP.NET
@foreach(var item in arr) {...} inside the View in the MVC ASP.NET
@DateTime.Now inside the View in the MVC ASP.NET
How to find the name of the controller inside the View in the MVC ASP.NET
Display [DateTime | Date only | Time only] in the desired format in the MVC ASP.NET
Views
Strongly-typed-view in MVC ASP.NET
...
Master View using @RenderBody() in the MVC ASP.NET
Master View using @RenderBody() and additional sections @RenderSection in the MVC ASP.NET
...
Partial View in the MVC ASP.NET. Embed a partial representation @Html.Partial("My1") and @{ Html.RenderPartial("My1");}
When you click submit inside the partial view, the controller method is called ajax. The controller method should return PartialView(model) | ASP.NET MVC
...
Strongly-typed partial view in the MVC ASP.NET
Create the ViewModels folder. This is a good programming style for transferring data from the Controller to the View
Create the ViewModels folder. Create your class in the ViewModels folder. This is a good programming style for transferring data from the Controller to the View. Web Application ASP.NET MVC
Attributes. Use the attributes in the ViewModels (to show the combo buttons in the view). Using attributes in the Controller (to improve methods)
Attribute [Display(Name = "... ")] is described in the C# class and used in @Html.LabelFor, @Html.DisplayNameFor in the MVC ASP.NET
The attribute [Required(ErrorMessage = "Please enter a name")] is described for a property in the C# class and requires the property to be populated if the ErrorMessage error in the MVC ASP.NET is not filled in the screen
The attribute [Remote("IsValidAuthor", "Home", ErrorMessage = "Enter correct author of book")] is described for a property in a C# class and checks that property for correctness on the server via the IsValidAuthor method in conroller Home, if the method returns false, then there will be an ErrorMessage error on the screen in the MVC ASP.NET
The [HiddenInput(DisplayValue=false)] attribute is described in the C# class and is used in @Html.HiddenFor in the MVC ASP.NET
Routing
Links and redirects in the view
@Html.ActionLink inside the View in the MVC ASP.NET
@Html.RouteLink inside the View in the MVC ASP.NET
@Url.Action inside the View in the MVC ASP.NET
@Url.RouteUrl inside the View in the MVC ASP.NET
@Url.Content inside the View in the MVC ASP.NET
Bootstrap in MVC
Add and include Bootstrap (css, js files) to ASP.NET MVC project
JQuery in MVC
Connecting JQuery to ASP.NET MVC project
Using JQuery, we get the contents of the View in the MVC ASP.NET. Example: $.get("/Home/Index", function (data) {...}) ...
MVC AjaxExtensions class (asynchronous data retrieval)
Plugging jQuery & AJAX into ASP.NET MVC project
Using Ajax.ActionLink, get the contents of the View and insert it into the div in the MVC ASP.NET
Ajax object (this is the AjaxExtensions class) in MVC ASP.NET
Database (Entity Framework) in MVC ASP.NET
Entity Framework in the ASP.NET MVC application. Using Code First (we write c# code, and the tables in the database are created by ourselves)
Authentication (login/register/logout)
What is authentication (login/register/logout) in the MVC ASP.NET?
Example: Authentication (login/register/logout) in MVC ASP.NET using FormsAuthentication.SetAuthCookie(model. Name, true);
Authorization (admin/user/...)
What is authorization (admin/user/...) in the MVC ASP.NET?
Example: Authorization (admin/user/...) in MVC ASP.NET using the RoleProvider role provider
Writing the appendix "Planning tasks" in the MVC ASP.NET
Creating an empty application "Planning tasks, tasks" | ASP.NET MVC | Visual Studio 2017
Adding Bootstrap & jQuery libraries to the application "Scheduling tasks" | ASP.NET MVC | Visual Studio 2017
Create a master view (main menu & button login using Bootstrap) in the application "Planning tasks" | ASP.NET MVC | Visual Studio 2017
Add the "Home" controller and the "Index" view (the main page in the application "Planning tasks, tasks" | ASP.NET MVC | Visual Studio 2017
Add the Entity Framework library and create a connection to the Database in the application "Planning tasks" | ASP.NET MVC | Visual Studio 2017
Authentication (login/register/logout) in the application "Scheduling tasks" | ASP.NET MVC | Visual Studio 2017
Add the class "Task" to save tasks, tasks to the database in the application "Planning tasks, tasks" | ASP.NET MVC | Visual Studio 2017
Adding nUnit in the application "Planning tasks, tasks" | ASP.NET MVC | Visual Studio 2017
Additional topics, questions
Why is MVC ASP.NET better ASP.NET Web Forms?
Choosing between ASP.NET Core and ASP.NET?
How to choose an Internet browser to run a .NET project in it
How do I find the local address and port of your ASP.NET MVC application?
Scriptsindex.d.ts(8,1): error TS1008: Build:Unexpected token; "module, class, interface, enum, import or statement" expected. Scriptsindex.d.ts(8,13): error TS1005: Build:";" expected. in Visual Studio 2017 in the ASP.NET MVC app
Error "unable to connect to web server "iis express" | ASP.NET MVC | Visual Studio 2017
Error "This site can"t be reached" when run ASP.NET application | Solution: Recreate the Self-Signed HTTPS Certificate for localhost in IIS Express
WWW Sites to Learn ASP.NET MVC
Sites to learn ASP.NET MVC

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