Thanks to visit codestin.com
Credit goes to www.scribd.com

0% found this document useful (0 votes)
39 views18 pages

AWD-lecture06 ASP - Net Identity

INDENTITY

Uploaded by

hayatsafi077
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
39 views18 pages

AWD-lecture06 ASP - Net Identity

INDENTITY

Uploaded by

hayatsafi077
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 18

Asp.

Net Core Identity

Nangarhar University Computer Science Faculty –(NUCSF) 1401/12/17


Outlines
1. What is Asp.net core Identity?
2. Packages used for Identity
3. Configuring IdentityDbContext
4. Adding Identity to Dependency injection
5. Adding authentication and authorization to request pipeline
6. Migrating the identity models
7. User Management
1. Registring new user
2. Loged in a user
What is Asp.net core Identity?

❑ ASP.NET Core Identity is an API from Microsoft to manage users in


ASP.NET Core applications and includes support for integrating
authentication and authorization into the request pipeline.
❑ ASP.NET Core Identity is a toolkit with which you create the
authorization and authentication features an application requires.
❑ There are endless integration options for features such as two-
factor authentication, single sign-on, and account self-service.
❑ ASP.NET Core Identity API to create tools to perform basic user and
role management.
Packages used for Identity

➢Install the following package via Nuget package manager tool.


➢Microsoft.AspNetCore.Identity.EntityFrameworkCore

➢By installing this package the application can get all features of
asp.net core identity framework which can be used in an application
for authentication and authorization.
Configuring IdentityDbContext
For configuring dbconext for database connection used
IdentityDbContext instead of DbContext and passing IdentityUser class.
• public class CourseMISDBConnection :IdentityDbContext<IdentityUser>
• {
• public CourseMISDBConnection(DbContextOptions<CourseMISDBConnection> options)
• :base(options)
• {

• }
• }
Adding Identity to Dependency injection

➢ In order to use the services of asp.net identity we must add the


identity to the dependency services container as :

• builder.Services.AddIdentity<IdentityUser, IdentityRole>()
• .AddEntityFrameworkStores<CourseMISDBConnection>();
Configuring the request pipeline
for identity.
In order to have the authentication and authorization middleware in
the request pipeline we must add them first to the pipeline.
• app.UseStaticFiles();
• app.UseRouting();
• app.UseAuthentication();
• app.UseAuthorization();
• app.MapControllerRoute(
• name: "default",
• pattern: "{controller=Home}/{action=Index}/{id?}");
Migrating the IdentityDbContext

• To the AspNetCore Identity database table we need to migrate it first


and then update the database;
• Add-migration addingidentity
• Update-database
User Management

➢Users are managed through the UserManager<T> class, where T is the


class chosen to represent users in the database.
➢When I created the Entity Framework Core context class, I specified
IdentityUser as the class to represent users in the database.
➢ This is the built-in class that is provided by ASP.NET Core Identity, and it
provides the core features that are required by most applications.
➢Useful IdentityUser Properties
Name Description
Id This property contains the unique ID for the user.
UserName This property returns the user’s username.
Email This property contains the user’s e-mail address.
cont…
Useful UserManager<T> Members
Name Description
Users This property returns a sequence containing the users stored in
the database.
FindByIdAsync(id) This method queries the database for the user
object with the specified ID.
CreateAsync(user, password)
This method stores a new user in the database using the
specified password.
UpdateAsync(user)
This method modifies an existing user in the database.
DeleteAsync(user)
This method removes the specified user from the database.
Registring new user
• public async Task<IActionResult> Register(RegisterViewModel registerViewModel)
• {
• if(ModelState.IsValid) {
• var user = await
_userManager.FindByEmailAsync(registerViewModel.Email);
• if(user != null)
• {
• TempData["error"] = "This is email is already in use";
• return View();
• }
cont…
• var newuser = new ApplicationUser
• {
• Email= registerViewModel.Email,
• UserName = registerViewModel.Email
• };
var newUserResponse = await
_userManager.CreateAsync(newuser, registerViewModel.Password);
if(newUserResponse.Succeeded)
• {
• return View("RegisterationComplete");
• }

• }
• return View();
• }
Register view Model
• public class RegisterViewModel
• {
• [Required]
• [EmailAddress]
• public string Email { get; set; }
• [Required]
• [DataType(DataType.Password)]
• public string Password { get; set; }
• [Required]
• [DataType(DataType.Password)]
• [Compare("Password")]
• public string ConfirmPassword { get; set; }

• }
Implementing user Login

• public async Task<IActionResult> Login(LoginViewModel loginViewModel)


• {
• if(ModelState.IsValid)
• {
var user = await _userManager.FindByEmailAsync(loginViewModel.EmailAddress);
• if (user != null)
• {
var passwordCheck = await _userManager.CheckPasswordAsync(user,
loginViewModel.Password);
if (passwordCheck)
{
var result = await _signInManager.PasswordSignInAsync(user,
loginViewModel.Password, false, false);
cont…
• if (result.Succeeded)
• {
• return RedirectToAction("Index", "Home");
• }
}
• ViewData["error"] = "Invalid Credentials";
}
ViewData["error"] = "Invalid Credentials";
}
• return View();
• }
Log in view model

• public class LoginViewModel


• {
• [DisplayName("Email Address")]
• [Required(ErrorMessage = "Email Address is required")]
• [EmailAddress]
• public string EmailAddress { get; set; }
• [Required]
• [DataType(DataType.Password)]
• public string Password { get; set; }

• }
Identity menu rendering

• @using Microsoft.AspNetCore.Identity;
• @inject UserManager<ApplicationUser> userManager;

@if (!User.Identity.IsAuthenticated)

• @userManager.GetUserName(User)
Its your turn to ask about today’s lecture

You might also like