ASP.net custom login
create ASP.net MVC framework web application
select individual accounts in Authentication
create project
change connectionString to
Rename table names
goto IdentityModels.cs file
paste below code in ApplicationDbContext class
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
base.OnModelCreating(modelBuilder);
modelBuilder.Entity().ToTable("Users");
modelBuilder.Entity().ToTable("Roles");
modelBuilder.Entity().ToTable("UserLogins");
modelBuilder.Entity().ToTable("UserClaims");
modelBuilder.Entity().ToTable("UserRoles");
}
Now open packageManagerConsole and run these 3 commands
Enable-Migrations
add-migration init
update-database
it will create all user and auth related tables without ASPNET prefix
Now lets add Custom Fields to Users Table
goto IdentityModels.cs file
type properties in ApplicationUser class as below
public string MobileNumber { get; set; }
public string EmployeeNumber { get; set; }
Add new migration and update database by running below commands in Package Manager Console
add-migration mobileEmpFieldsAdded
update-database
You will be able to see these fields in database Users table
now lets add these fields in RegisterViewModel and Register form
Goto AccountViewModels.cs in Models folder
and type new fields as properties in RegisterViewModel class as below (same as we added in ApplicationUser class
public string MobileNumber { get; set; }
public string EmployeeNumber { get; set; }
now open AccountController goto Register postback method
add new properties in ApplicationUser new object as shown below before and after
//Before
var user = new ApplicationUser { UserName = model.Email, Email = model.Email };
//After
var user = new ApplicationUser { UserName = model.Email, Email = model.Email
,MobileNumber = model.MobileNumber,EmployeeNumber=model.EmployeeNumber };
Now Goto Register view page and add these inputs as
@Html.LabelFor(m => m.MobileNumber, new { @class = "col-md-2 control-label" })
@Html.TextBoxFor(m => m.MobileNumber, new { @class = "form-control" })
@Html.LabelFor(m => m.EmployeeNumber, new { @class = "col-md-2 control-label" })
@Html.TextBoxFor(m => m.EmployeeNumber, new { @class = "form-control" })
Now build your project, run it and try to register new user
new fields data (mobile & empno) will also be inserted in users table
now lets get these custom fields data from Identity object after login
for we have to make claims and extensions means our own functions like Identity.getMobile() and Identity.getEmpno()
to make claims go to IdentityModel.cs inside ApplicationUser class there is GenerateUserIdentityAsync method
before return there also a comment to add claims here
add below code there
userIdentity.AddClaim(new Claim("MobileNumber", MobileNumber));
userIdentity.AddClaim(new Claim("EmployeeNumber", EmployeeNumber));
Now create a new class and name it IdentityExtensions
and add below code in this class
//using System.Security.Claims;
//using System.Security.Principal;
//make the class static
public static class IdentityExtensions
{
public static string GetMobile(this IIdentity identity)
{
var claim = ((ClaimsIdentity)identity).FindFirst("MobileNumber");
// Test for null to avoid issues during local testing
return (claim != null) ? claim.Value : string.Empty;
}
public static string GetEmployee(this IIdentity identity)
{
var claim = ((ClaimsIdentity)identity).FindFirst("EmployeeNumber");
// Test for null to avoid issues during local testing
return (claim != null) ? claim.Value : string.Empty;
}
}
now go to views->shared->loginPartial.cshtml and at to write this
@using customAuth.Models //replace customAuth with your project name
and now in content of page replaceUser.Identity.GetUserName() with User.Identity.GetMobile() or User.Identity.GetEmployee() and then run application login and see at top it will be showing hello your-mobile-number!
Now lets do manual login that is for lets say authenticate user with Active Directory and the authenticate that user without password
go to AccountController and then go to Login postback method and add below code
//comment below lines which is authenticating user with password
//var result = await SignInManager.PasswordSignInAsync(model.Email, model.Password, model.RememberMe, shouldLockout: false);
//switch (result)
//{
// case SignInStatus.Success:
// return RedirectToLocal(returnUrl);
// case SignInStatus.LockedOut:
// return View("Lockout");
// case SignInStatus.RequiresVerification:
// return RedirectToAction("SendCode", new { ReturnUrl = returnUrl, RememberMe = model.RememberMe });
// case SignInStatus.Failure:
// default:
// ModelState.AddModelError("", "Invalid login attempt.");
// return View(model);
//}
//instead of above lines write below code
/*authgentication user with Active directory then with that email find a record in this site db and log him in manually
consider we already authenticated with AD
*/
var user = UserManager.FindByEmail(model.Email);
if (user == null)
{
ModelState.AddModelError("", "Invalid login attempt.");
return View(model);
}
else if (user.LockoutEnabled == false)
{
return View("Lockout");
}
await SignInManager.SignInAsync(user, false, false);
return RedirectToLocal(returnUrl);
source code avaible at https://github.com/alamnaryab/asp.net-framework-cutom-auth.git .net Framework 4.7.2






Visit Today : 91
Total Visit : 964994
Total Hits : 3547781011
Comments