Today in this article we will discuss about the general concepts of authentication and authorisation in asp.net mvc. We will try to include all the concepts related to authentication and authorisation using Identity. Not let us first discuss about the concept of authentication and authorisation. Basically Authentication is all about verifying your identity using your credential like Username and Password, Based on the security level user authentication may be single-factor authentication, two-factor authentication or multi-factor authentication. Whereas Authorisation is all about deciding if you have permission to access certain resources. e.g General Employee in an organisation may not have access to manage organisation or view other employee performance and so on. These are all dealt with Authorisation. Authorisation in Identity can be performed by using Roles.
Now, moving forward lets understand about the Identity System provided by Entity Framework. Identity is basically an authentication system which provides various functionality like login functionality, login using external login providers like facebook, google, microsoft and so on. Basically these are the stuffs that most modern websites, with functionality of user registration needs. So, Identity does all the hard stuffs like hashing our passwords, providing security etc so that we do not have to code these from scratch. According the the oficial documentation ASP.NET membership system was introduced with asp.net 2.0 back in 2005, and since then there has been many changes in the ways web application typically handle authentication and authorisation. Considering various changes in web application development, ASP.NET Identity was developed with the following goals:
1) One ASP.NET Identity System
2) Ease of plugging in profile data about the user.
3) Persistence Control.
4) Unit Testability
5) Role Provider
6) Claims Based
7) Social Login Provider
8) Azure Active Directory
9) OWIN Integration
Moving on, We need some packages to be installed for using Identity System. Packages can be installed using Nuget Package Manager or using Package Manaer Console. Here is the list of packages that we need:
1) Microsoft.ASPNET.Identity.EntityFramework
2) Microsoft.ASPNET.Identity.Core
3) Microsoft.ASPNET.Identity.OWIN
With assumption of all the package installed and all the Model Class Created, Lets create a new Repository named AuthRepository and perform some of the basic things in our identity system.
public class AuthRepository
{
private ApplicationDbContext _context;
private UserManager<ApplicationUser> _userManager;
private RoleManager<IdentityRole> _roleManager;
public AuthRepository()
{
_context = new ApplicationDbContext();
_userManager=new UserManager<ApplicationUser>(new UserStore<ApplicationUser>(_context));
_roleManager=new RoleManager<IdentityRole>(new RoleStore<IdentityRole>(_context));
}
public IdentityResult ChangePassword(ChangePasswordModel model)
{
string userName=HttpContext.Current.User.Identity.Name;
string userId=_userManager.findByName(userName).Id;
return _userManager.changePassword(userId, model.OldPassword, model.Password);
}
public ApplicationUser GetUserByUserName(string userName)
{
return _userManager.findByName(userName);
}
public async Task<IdentityResult> DeleteUser(ApplicationUser user)
{
return await _userManager.DeleteAsync(user);
}
public void CreateRole(string roleName)
{
if(!_roleManager.RoleExists(roleName))
{
_roleManager.Create(new IdentityRole(roleName));
}
}
public list<RegisterViewModel> GetAllUsers()
{
List<RegisterUserModel> registerUserModels = new List<RegisterUserModel>();
var users=_userManager.Users.ToList();
foreach(var item in users)
{
RegisterUserModel registerUserModel=new RegisterUserModel();
registerUserModel.Id=item.Id;
registerUserModel.Name=item.Name;
registerUserModel.UserName=item.UserName;
registerUserModel.Email=item.Email;
registerUserModels.Add(registerUserModel);
}
return registerUserModels;
}
public async Task<IdentityResult> RegisterUser(RegisterUserModel user)
{
var theUser=_userManager.FindByName(user.UserName);
if(theUser != null)
{
throw new Exception(String.Format("The Username {0} is already taken !",user.UserName));
}
var applicationUser=new ApplicationUser()
{
Name=user.Name,
UserName=user.UserName,
Email=user.Email,
PhoneNumber=user.PhoneNumber
}
var result=await _userManager.CreateAsync(applicationUser,user.Password);
await AddRoleToUser(user.UserName,"Admin");
return result;
}
public async Task<IdentityResult> AddRoleToUser(string userName, string role)
{
var theUser=_userManager.FindByName(userName);
if(theUser==null)
{
throw new Exception("The User do not exists");
}
var result=await _userManager.AddToRoleAsync(theUser.Id,role);
return result;
}
}
Thankyou for reading this article. Please do comment and share what you think about identity system. Any Comments and suggestions are highly appreciated.