ASP.NET Identity System

Slides:



Advertisements
Similar presentations
Forms Authentication, Users, Roles, Membership Ventsislav Popov Crossroad Ltd.
Advertisements

Software Quality Assurance QA Engineering, Testing, Bug Tracking, Test Automation Software University Technical Trainers SoftUni Team.
Forms Authentication, Users, Roles, Membership Svetlin Nakov Telerik Corporation
Creating Web Services with C#
AngularJS Routing Routes, Route Parameters, Templates, Location, Navigation SoftUni Team Technical Trainers Software University
AngularJS Services Built-in and Custom Services SoftUni Team Technical Trainers Software University
Software University Curriculum, Courses, Exams, Jobs SoftUni Team Technical Trainers Software University
Fundamentals SoftUni Welcome to Software University SoftUni Team Technical Trainers Software University
Project Tracking Tools Trello, Asana, Basecamp, GitHub Issue Tracker, TRAC SoftUni Team Technical Trainers Software University
AngularJS Directives Defining Custom Directives SoftUni Team Technical Trainers Software University
Software Testing Lifecycle Exit Criteria Evaluation, Continuous Integration Ivan Yonkov Technical Trainer Software University.
Fundamentals SoftUni Welcome to Software University SoftUni Team Technical Trainers Software University
Design Patterns: Structural Design Patterns
NoSQL Databases NoSQL Concepts SoftUni Team Technical Trainers Software University
Redis Key-Value Database: Practical Introduction
Composer packages Installing and Using Composer, Packagist, Packaging your code Mario Peshev Technical Trainer Software University
Consuming REST Services from C# SoftUni Team Technical Trainers Software University
Entity Framework Performance SoftUni Team Technical Trainers Software University
Microsoft Azure SoftUni Team Technical Trainers Software University
Build Processes and Continuous Integration Automating Build Processes Software University Technical Trainers SoftUni Team.
Processing Redis with.NET How to Operate with Redis Databases SoftUni Team Technical Trainers Software University
Multidimensional Arrays, Sets, Dictionaries Processing Matrices, Multidimensional Arrays, Dictionaries, Sets SoftUni Team Technical Trainers Software University.
Project Tracking Tools Trello, Asana, Basecamp, GitHub Issue Tracker, TRAC Angel Georgiev Part-time Trainer Software University
Test-Driven Development Learn the "Test First" Approach to Coding SoftUni Team Technical Trainers Software University
ASP.NET MVC Architecture Layouts, Filters, Sections, Helpers, Partial Views, Areas… SoftUni Team Technical Trainers Software University
AMD and RequireJS Splitting JavaScript Code into Dependent Modules Software University Technical Trainers SoftUni Team.
Asynchronous Web Services Writing Asynchronous Web Services SoftUni Team Technical Trainers Software University
Sessions and Cookies State Management, Cookies, Sessions, Hidden Fields SoftUni Team Technical Trainers Software University
Web Fundamentals (HTML and CSS) Course Introduction SoftUni Team Technical Trainers Software University
Controls, Widgets, Grid…
Jekyll Static Site Generator Template-Based Site Generation Svetlin Nakov Technical Trainer Software University
Forms Overview, Query string, Submitting arrays, PHP & HTML, Input types, Redirecting the user Mario Peshev Technical Trainer Software.
Web Fundamentals (HTML and CSS)
ASP.NET SignalR SoftUni Team Technical Trainers Software University
Responsive Design Design that Adapts to Different Devices SoftUni Team Technical Trainers Software University
Processing JSON in.NET JSON, JSON.NET LINQ-to-JSON and JSON to XML SoftUni Team Technical Trainers Software University
Design Patterns: Structural Design Patterns General and reusable solutions to common problems in software design Software University
Identity & Security Andres Käver, IT Kolledž 2015.
Events Event Handling in JavaScript SoftUni Team Technical Trainers Software University
Mocking with Moq Tools for Easier Unit Testing SoftUni Team Technical Trainers Software University
Mocking Unit Testing Methods with External Dependencies SoftUni Team Technical Trainers Software University
Mocking with Moq Mocking tools for easier unit testing Svetlin Nakov Technical Trainer Software University
JavaScript Tools Tools for Writing / Editing / Debugging JavaScript Code Svetlin Nakov Technical Trainer Software University
ORM Basics Repository Pattern, Models, Entity Manager Ivan Yonkov Technical Trainer Software University
Test-Driven Development Learn the "Test First" Approach to Coding Svetlin Nakov Technical Trainer Software University
Sets, Dictionaries SoftUni Team Technical Trainers Software University
Programming Fundamentals Course Introduction SoftUni Team Technical Trainers Software University
Doctrine The PHP ORM SoftUni Team Technical Trainers Software University
ASP.NET MVC Course Program, Trainers, Evaluation, Exams, Resources SoftUni Team Technical Trainers Software University
Web Storage and Cookies Cookies, Local and Session Storage SoftUni Team Technical Trainers Software University
Inheritance Class Hierarchies SoftUni Team Technical Trainers Software University
Stacks and Queues Processing Sequences of Elements SoftUni Team Technical Trainers Software University
C# MVC Frameworks – ASP.NET
Introduction to MVC SoftUni Team Introduction to MVC
Deploying Web Application
ASP.NET Integration Testing
Mocking tools for easier unit testing
State Management Cookies, Sessions SoftUni Team State Management
EF Code First (Advanced)
Entity Framework: Code First
Registration, Login, Thymeleaf
The Right Way Control Flow
MVC Architecture, Symfony Framework for PHP Web Apps
ASP.NET MVC Introduction
Best practices and architecture
Extending functionality using Collections
ASP.NET REST Services SoftUni Team ASP.NET REST Services
JavaScript: ExpressJS Overview
ASP.NET Authentication with Identity Jump Start
07 | Introduction to Authentication
Presentation transcript:

ASP.NET Identity System Users, Roles, Authorization, Registration, Login, Logout, … ASP.NET MVC SoftUni Team Technical Trainers Software University http://softuni.bg © Software University Foundation – http://softuni.org This work is licensed under the Creative Commons Attribution-NonCommercial-ShareAlike license.

Table of Contents Authentication and Authorization – Concepts ASP.NET Identity System – Overview Authorization and User Roles Remote Authentication Configuring External Login in ASP.NET MVC

Authentication and Authorization * Authentication and Authorization What's the Difference? (c) 2007 National Academy for Software Development - http://academy.devbg.org. All rights reserved. Unauthorized copying or re-distribution is strictly prohibited.*

Authentication vs. Authorization The process of verifying the identity of a user or computer Questions: Who are you? How you prove it? Credentials can be password, smart card, external token, etc. Authorization The process of determining what a user is permitted to do on a computer or network Questions: What are you allowed to do? Can you see this page?

ASP.NET Identity System Overview

ASP.NET Identity The ASP.NET Identity system Authentication and authorization system for ASP.NET Web apps Supports ASP.NET MVC, Web API, Web Forms, SignalR, Web Pages Handles users, user profiles, login / logout, roles, etc. Keeps the user accounts in local database or in external data store External login (through OAuth) Supports Facebook, Google, Microsoft, Twitter accounts Based on the OWIN middleware (can run outside of IIS) Available through the NuGet package manager

ASP.NET Identity and Entity Framework Typically, the ASP.NET identity data (users, passwords, roles) is stored in relational database through EF Code First You have some control over the internal database schema

Setup, Registration, Login, Logout ASP.NET Identity API Setup, Registration, Login, Logout

ASP.NET Identity System Setup Ways to setup ASP.NET Identity based authentication in MVC Using the ASP.NET project templates from Visual Studio By hand: install NuGet packages, manual configuration, create EF mappings (models), view models, controllers, views, etc. Required NuGet packages Microsoft.AspNet.Identity.Core Microsoft.AspNet.Identity.Owin Microsoft.AspNet.Identity.EntityFramework

ASP.NET Project Template Authentication IdentityConfig.cs – holds the user manager configuration ApplicationUserManager : UserManager<ApplicationUser> The main class for managing users in the ASP.NET Identity system Can define the user and password validation rules ApplicationSignInManager : SignInManager Implements the user login / logout Supports external login, e.g. Facebook login Two-factor authentication (email confirm)

ASP.NET Project Template Authentication (2) IndentityModels.cs – holds user class and EF DB context ApplicationUser : IdentityUser Holds the user information for the ASP.NET application Id (unique user ID, string holding a GUID) E.g. 313c241a-29ed-4398-b185-9a143bbd03ef Username (unique username), e.g. maria Email (email address – can be unique), e.g. mm@gmail.com May hold additional fields, e.g. first name, last name, date of birth

ASP.NET Project Template Authentication (3) ApplicationDbContext : IdentityDbContext<ApplicationUser> Holds the EF data context with all database mapped entities May define database initializer to specify DB migration strategy Startup.Auth.cs Configures OWIN to use identity authentication Usually enables cookie-based authentication May enable external login (e.g. Facebook login)

User Registration var newUser = new ApplicationUser { UserName = "maria", Email = "mm@gmail.com", PhoneNumber = "+359 2 981 981" }; var userManager = HttpContext.GetOwinContext(). GetUserManager<ApplicationUserManager>(); var result = userManager.Create(newUser, "S0m3@Pa$$"); if (result.Succeeded) // User registered else // result.Errors holds the error messages

User Login var signInManager = HttpContext.GetOwinContext(). Get<ApplicationSignInManager>(); bool rememberMe = true; bool shouldLockout = false; var signInStatus = signInManager.PasswordSignIn( "maria", "S0m3@Pa$$", rememberMe, shouldLockout); if (signInStatus == SignInStatus.Success) // Sucessfull login else // Login failed

User Logout Performs local / external logout logout (log off / sign out): Logging out clears the authentication cookies var authenticationManager = HttpContext.GetOwinContext().Authentication; authenticationManager.SignOut(); // Redirect to home screen or login screen

Change Password Logged-in user changes his password: Administrator resets some user's password: var currentUser = User.Identity.GetUserId(); var userManager = HttpContext.GetOwinContext(). GetUserManager<ApplicationUserManager>(); var result = userManager.ChangePassword( currentUser, "old pass", "new pass"); if (result.Succeeded) { … } string token = userManager.GeneratePasswordResetToken (userId); var result = userManager.ResetPassword( userId, token, "new password");

Extending the User Profile To extend the user profile Just add properties to ApplicationUser class Enable migrations for the project / data layer E.g. in Global.asax set the database initializer public class ApplicationUser : IdentityUser { [Required] public string Name { get; set; } … }

Authorization and User Roles

ASP.NET Authorization Use the [Authorize] and [AllowAnnonymous] attributes to configure authorized / anonymous access for controller / action [Authorize] public class AccountController : Controller { // GET: /Account/Login (annonymous) [AllowAnonymous] public ActionResult Login(string returnUrl) { … } // POST: /Account/LogOff (for logged-in users only) [HttpPost] public ActionResult LogOff() { … } }

Check the Currently Logged-In User // GET: /Account/Roles (for logged-in users only) [Authorize] public ActionResult Roles() { var currentUserId = this.User.Identity.GetUserId(); var userManager = HttpContext.GetOwinContext(). GetUserManager<ApplicationUserManager>(); var user = userManager.FindById(currentUserId); ViewBag.Roles = user.Roles; return this.View(); }

Create a New Role Identity roles group users to simplify managing permissions ASP.NET MVC controllers and actions could check the user role Creating a new role: var roleManager = new RoleManager<IdentityRole>( new RoleStore<IdentityRole>(new ApplicationDbContext())); var roleCreateResult = roleManager.Create(new IdentityRole("Administrator")); if (! roleCreateResult.Succeeded) { throw new Exception(string.Join("; ", roleCreateResult.Errors)); }

Add User to a Role Adding a user to existing role: var userManager = HttpContext.GetOwinContext(). GetUserManager<ApplicationUserManager>(); var addAdminRoleResult = userManager.AddToRole(adminUserId, "Administrator"); if (addAdminRoleResult.Succeeded) { // The user is now Administrator }

Require Logged-In User in Certain Role Give access only to users in role "Administrator": Give access if user's role is "User", "Student" or "Trainer": [Authorize(Roles="Administrator")] public class AdminController : Controller { … } [Authorize(Roles="User, Student, Trainer")] public ActionResult Roles() { … }

Check the Currently Logged-In User's Role // GET: /Home/Admin (for logged-in admins only) [Authorize] public ActionResult Admin() { if (this.User.IsInRole("Administrator")) ViewBag.Message = "Welcome to the admin area!"; return View(); } return this.View("Unauthorized");

Remote Authentication * Remote Authentication Claims-Based Authentication in ASP.NET (c) 2007 National Academy for Software Development - http://academy.devbg.org. All rights reserved. Unauthorized copying or re-distribution is strictly prohibited.*

Claims-Based Authentication (1) Piece of information identifying user Sent as key-value pairs Contains authentication token and/or signature Claims-based authentication Users authenticate on remote system Information is passed to the application User is authenticated and recognized © Software University Foundation – http://softuni.org This work is licensed under the Creative Commons Attribution-NonCommercial-ShareAlike license.

Claims-Based Authentication (2) Authentication flow User makes request to application System redirects to external page After authentication the external system returns back to the application with user information Application makes request to external system to validate user User gets access to the application

OAuth2 OAuth Steps Allows secure authentication Simple and standard protocol Can be used by web, desktop or mobile apps Steps Users tries to authenticate at application Application relies on remote service Application receives access token User gets access

OAuth2 Process

Configuring External Login OAuth and OWIN Authorization

Enable External Login in ASP.NET MVC public partial class Startup { public void ConfigureAuth(IAppBuilder app) … app.UseFacebookAuthentication( appId: "xxx", appSecret: "yyy"); app.UseGoogleAuthentication( new GoogleOAuth2AuthenticationOptions() { ClientId = "xxx", ClientSecret = "yyy" } ); }

Summary Authentication vs. Authorization ASP.NET Identity Custom users Registration, login, logout Change password User roles and role management External logins

ASP.NET Identity https://softuni.bg/trainings/1230/asp-net-mvc-october-2015 © Software University Foundation – http://softuni.org This work is licensed under the Creative Commons Attribution-NonCommercial-ShareAlike license.

SoftUni Diamond Partners

License This course (slides, examples, demos, videos, homework, etc.) is licensed under the "Creative Commons Attribution- NonCommercial-ShareAlike 4.0 International" license Attribution: this work may contain portions from "ASP.NET MVC" course by Telerik Academy under CC-BY-NC-SA license © Software University Foundation – http://softuni.org This work is licensed under the Creative Commons Attribution-NonCommercial-ShareAlike license.

Free Trainings @ Software University Software University Foundation – softuni.org Software University – High-Quality Education, Profession and Job for Software Developers softuni.bg Software University @ Facebook facebook.com/SoftwareUniversity Software University @ YouTube youtube.com/SoftwareUniversity Software University Forums – forum.softuni.bg © Software University Foundation – http://softuni.org This work is licensed under the Creative Commons Attribution-NonCommercial-ShareAlike license.