I am working on a porject built on MVC5 and EF Code First.
I have multiple contexts, but the one I'm concered about here is the ApplicationDbContext which has the following configuration code:
namespace DX.DAL.Migrations.ApplicationDbMigrations
{
public class Configuration : DbMigrationsConfiguration<ApplicationDbContext>
{
public Configuration()
{
AutomaticMigrationsEnabled = false;
MigrationsDirectory = #"Migrations\ApplicationDbMigrations";
ContextKey = "DX.DAL.Context.ApplicationDbContext";
}
protected override void Seed(ApplicationDbContext context)
{
var roleManager = new RoleManager<IdentityRole>(new RoleStore<IdentityRole>(context));
var userManager = new UserManager<ApplicationUser>(new UserStore<ApplicationUser>(context));
if (!roleManager.RoleExists("Admin"))
{
roleManager.Create(new IdentityRole("Admin"));
}
var user = new ApplicationUser { UserName = "John", Email = "j.doe#world.com" };
if (userManager.FindByName("John") != null) return;
var result = userManager.Create(user, "Password123#");
if (result.Succeeded)
{
userManager.AddToRole(user.Id, "Admin");
}
}
}
}
When I try and login with the email and password seeded above, I get the error:
Invalid login attempt
I wrote the following SQL Query:
SELECT * FROM AspNetUsers
And I see the following:
So the seed has been created. But why can't I login?
Also, I know that if I change the Username to be the same as the email, then it works and I can login. Must the username and email be the same for ASP.NET Membership in MVC 5 to work?
After trying so many different things, I went with LukeP's solution here.
I left Identity as it is and just added a new property called DisplayUsername and allowed the user to set that up on registration.
Related
All I want is to give the permissions to the user from Entity Framework (using the code first approach) that is like DDL, DML commands to a certain user.
The steps below will help you create user, create roles, assign user to roles, and limit their access depending on their role.
Open your Solution in Visual Studio
Tools > Nuget Package Manager Console > Enter Enable-Migrations
Open Migrations > Configuration.cs
Use this as your seed method;
protected override void Seed(ISPRC.Models.ApplicationDbContext context)
{
var userStore = new UserStore<ApplicationUser>(context);
var userManager = new UserManager<ApplicationUser>(userStore);
userManager.UserValidator = new UserValidator<ApplicationUser>(userManager)
{
AllowOnlyAlphanumericUserNames = false,
};
var roleManager = new RoleManager<IdentityRole>(new RoleStore<IdentityRole>(new ApplicationDbContext()));
// Create a User Role
if (!roleManager.RoleExists("Admin"))
{
var role = new IdentityRole();
role.Name = "Admin";
roleManager.Create(role);
}
if (!context.Users.Any(u => u.UserName == "admin#mail.com"))
{
var user = new ApplicationUser
{
UserName = "admin#mail.com",
Email = "admin#mail.com",
EmailConfirmed = true,
};
// Create User
userManager.Create(user, "Password#777");
// Add User to Admin Role
userManager.AddToRole(user.Id, "Admin");
}
}
To limit certain roles in accessing your controllers or actions, add [Authorize] or [Authorize(Roles="Admin,User")]
The controller below will only allow Logged-in users that are of Admin role. If they're role does not match the requirement, they will be automatically redirected to login page.
[Authorize(Roles = "Admin")]
public class AdminController : Controller
{
private ApplicationDbContext db = new ApplicationDbContext();
public ActionResult Accounts()
{
return View();
}
}
Tools > Nuget Package Manager Console > Enter Update-Database
You can use Custom Migration Operations, or you can switch to a database-first workflow, and manage the database schema with another tool, and periodically reverse engineer the schema into a code-based model.
I have to change the existing (Windows) login for my ASP.NET MVC + Knockout application with Active Directory authentication.
It consists of mvc controllers and webapi controllers. Both have to be authenticated.
I thought I would do this by changing to forms authentication and create a login page and when the users clicks login, query Active Directory with the System.DirectoryServices.DirectoryEntry.
Then the other processes like change password, register etc. would also get a custom html page and do their actions via the System.DirectoryServices.DirectoryEntry on our Active Directory.
(that is, I could not find any other way that people would do it, and I did find some who would do it like this, and it sounds the same like previous forms authentications I've seen. In this case the user/passwords would not be in a database table but in Active Directory. Same idea, swap database table by active directory).
To see how this would be on a brandnew project, I created a new ASP.NET MVC project and choose 'work- or school acounts' (which says 'for applications that authenticate users with active directory) and choose 'on premise'.
However, then I have to provide these items:
on-premises authority
app Id url
I don't know what to do with that. The only thing I have is an active directory url like ldap://etc..
Is this another/newer/better way of doing active directory login? Or the only right one (is forms authentication wrong?) or the wrong one?
I'm confused.
You can use the following approach in order to implement Active Directory Authentication in ASP.NET MVC.
Step 1: Modify the Login methods in the AccountController as shown below (also add the necessary references):
[HttpPost]
[AllowAnonymous]
[ValidateAntiForgeryToken]
public async Task<ActionResult> Login(LoginViewModel model, string returnUrl)
{
try
{
if (!ModelState.IsValid)
{
return View(model);
}
// Check if the User exists in LDAP
if (Membership.GetUser(model.UserName) == null)
{
ModelState.AddModelError("", "Wrong username or password");
return this.View(model);
}
ApplicationGroupManager groupManager = new ApplicationGroupManager();
// Validate the user using LDAP
if (Membership.ValidateUser(model.UserName, model.Password))
{
FormsAuthentication.SetAuthCookie(model.UserName, model.RememberMe);
// FormsAuthentication.SetAuthCookie(model.UserName, false);
// Check if the User exists in the ASP.NET Identity table (AspNetUsers)
string userName = model.UserName.ToString().ToLower(new CultureInfo("en-US", false)); // When UserName is entered in uppercase containing "I", the user cannot be found in LDAP
//ApplicationUser user = UserManager.FindByName(userName);
ApplicationUser user = await UserManager.FindByNameAsync(userName); //Asynchronous method
if (user == null) // If the User DOES NOT exists in the ASP.NET Identity table (AspNetUsers)
{
// Create a new user using the User data retrieved from LDAP
// Create an array of properties that we would like and add them to the search object
string[] requiredProperties = new string[] { "samaccountname", "givenname", "sn", "mail", "physicalDeliveryOfficeName", "title" };
var userInfo = CreateDirectoryEntry(model.UserName, requiredProperties);
user = new ApplicationUser();
// For more information about "User Attributes - Inside Active Directory" : http://www.kouti.com/tables/userattributes.htm
user.UserName = userInfo.GetDirectoryEntry().Properties["samaccountname"].Value.ToString();
user.Name = userInfo.GetDirectoryEntry().Properties["givenname"].Value.ToString();
user.Surname = userInfo.GetDirectoryEntry().Properties["sn"].Value.ToString();
user.Email = userInfo.GetDirectoryEntry().Properties["mail"].Value.ToString();
user.EmailConfirmed = true;
//user.PasswordHash = null;
//user.Department = GetDepartmentId(userInfo.GetDirectoryEntry().Properties["physicalDeliveryOfficeName"].Value.ToString());
//await Register(user);
var result = await UserManager.CreateAsync(user); //Asynchronous method
//If the User has succesfully been created
//if (result.Succeeded)
//{
// //var code = await UserManager.GenerateEmailConfirmationTokenAsync(user.Id);
// //var callbackUrl = Url.Action("ConfirmEmail", "Account", new { userId = user.Id, code = code }, protocol: Request.Url.Scheme);
// //await UserManager.SendEmailAsync(user.Id, "Confirm your account", "Please confirm your account by clicking this link: link");
// //ViewBag.Link = callbackUrl;
// //return View("DisplayEmail");
//}
// Define user group (and roles)
var defaultGroup = "751b30d7-80be-4b3e-bfdb-3ff8c13be05e"; // Id of the ApplicationGroup for the Default roles
//groupManager.SetUserGroups(newUser.Id, new string[] { defaultGroup });
await groupManager.SetUserGroupsAsync(user.Id, new string[] { defaultGroup }); //Asynchronous method
//groupManager.SetGroupRoles(newGroup.Id, new string[] { role.Name });
}
// !!! THERE IS NO NEED TO ASSIGN ROLES AS IT IS ASSIGNED AUTOMATICALLY IN ASP.NET Identity 2.0
//else // If the User exists in the ASP.NET Identity table (AspNetUsers)
//{
// //##################### Some useful ASP.NET Identity 2.0 methods (for Info) #####################
// //ApplicationGroupManager gm = new ApplicationGroupManager();
// //string roleName = RoleManager.FindById("").Name; // Returns Role Name by using Role Id parameter
// //var userGroupRoles = gm.GetUserGroupRoles(""); // Returns Group Id and Role Id by using User Id parameter
// //var groupRoles = gm.GetGroupRoles(""); // Returns Group Roles by using Group Id parameter
// //string[] groupRoleNames = groupRoles.Select(p => p.Name).ToArray(); // Assing Group Role Names to a string array
// //###############################################################################################
// // Assign Default ApplicationGroupRoles to the User
// // As the default roles are already defined to the User after the first login to the system, there is no need to check if the role is NULL (otherwise it must be checked!!!)
// //var groupRoles = groupManager.GetGroupRoles("751b30d7-80be-4b3e-bfdb-3ff8c13be05e"); // Returns Group Roles by using Group Id parameter
// var groupRoles = await groupManager.GetGroupRolesAsync("751b30d7-80be-4b3e-bfdb-3ff8c13be05e"); // Returns Group Roles by using Group Id parameter (Asynchronous method)
// foreach (var role in groupRoles)
// {
// //Assign ApplicationGroupRoles to the User
// string roleName = RoleManager.FindById(role.Id).Name;
// UserManager.AddToRole(user.Id, roleName);
// }
//}
//Sign in the user
await SignInAsync(user, model.RememberMe);
if (this.Url.IsLocalUrl(returnUrl) && returnUrl.Length > 1 && returnUrl.StartsWith("/")
&& !returnUrl.StartsWith("//") && !returnUrl.StartsWith("/\\"))
{
return this.Redirect(returnUrl);
//return RedirectToLocal(returnUrl);
}
return this.RedirectToAction("Index", "Home");
}
else
{
ModelState.AddModelError("", "Wrong username or password");
return this.View(model);
}
}
catch (Exception ex)
{
TempData["ErrorMessage"] = ex.Message.ToString();
return View("Error", TempData["ErrorMessage"]);
}
}
/* Since ASP.NET Identity and OWIN Cookie Authentication are claims-based system, the framework requires the app to generate a ClaimsIdentity for the user.
ClaimsIdentity has information about all the claims for the user, such as what roles the user belongs to. You can also add more claims for the user at this stage.
The highlighted code below in the SignInAsync method signs in the user by using the AuthenticationManager from OWIN and calling SignIn and passing in the ClaimsIdentity. */
private async Task SignInAsync(ApplicationUser user, bool isPersistent)
{
AuthenticationManager.SignOut(DefaultAuthenticationTypes.ExternalCookie);
var identity = await UserManager.CreateIdentityAsync(user, DefaultAuthenticationTypes.ApplicationCookie);
AuthenticationManager.SignIn(new AuthenticationProperties() { IsPersistent = isPersistent }, identity);
}
static SearchResult CreateDirectoryEntry(string sAMAccountName, string[] requiredProperties)
{
DirectoryEntry ldapConnection = null;
try
{
// Create LDAP connection object
//ldapConnection = new DirectoryEntry("alpha.company.com");
ldapConnection = new DirectoryEntry("LDAP://OU=Company_Infrastructure, DC=company, DC=mydomain", "******", "******");
//ldapConnection.Path = connectionPath;
ldapConnection.AuthenticationType = AuthenticationTypes.Secure;
DirectorySearcher search = new DirectorySearcher(ldapConnection);
search.Filter = String.Format("(sAMAccountName={0})", sAMAccountName);
foreach (String property in requiredProperties)
search.PropertiesToLoad.Add(property);
SearchResult result = search.FindOne();
//SearchResultCollection searchResultCollection = search.FindAll();
if (result != null)
{
//foreach (String property in requiredProperties)
// foreach (Object myCollection in result.Properties[property])
// Console.WriteLine(String.Format("{0,-20} : {1}",
// property, myCollection.ToString()));
// return searchResultCollection;
return result;
}
else
{
return null;
//Console.WriteLine("User not found!");
}
//return ldapConnection;
}
catch (Exception e)
{
Console.WriteLine("Exception caught:\n\n" + e.ToString());
}
return null;
}
Note: In order to force signout in LDAP authentication, add FormsAuthentication.SignOut() line to the LogOff() method as shown below:
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult LogOff()
{
AuthenticationManager.SignOut();
FormsAuthentication.SignOut(); //In order to force logout in LDAP authentication
return RedirectToAction("Login", "Account");
}
Step 2: Update your LoginViewModel (or whatever your Account model class is named) to contain only this LoginModel class:
public class LoginViewModel
{
[Required]
public string UserName { get; set; }
[Required]
[EmailAddress]
public string Email { get; set; }
[Required]
[DataType(DataType.Password)]
public string Password { get; set; }
public bool RememberMe { get; set; }
}
On the other hand, add the custom properties i.e. Name, Surname, UserName, Department, etc. to the necessary model i.e. ApplicationUser, RegisterViewModel.
Step 3: Finally, update your Web.config file to include these elements:
<connectionStrings>
<!-- for LDAP -->
<add name="ADConnectionString" connectionString="LDAP://**.**.***:000/DC=abc,DC=xyz" />
</connectionStrings>
<system.web>
<!-- For LDAP -->
<httpCookies httpOnlyCookies="true" />
<authentication mode="Forms">
<forms name=".ADAuthCookie" loginUrl="~/Account/Login" timeout="30" slidingExpiration="true" protection="All" />
</authentication>
<membership defaultProvider="ADMembershipProvider">
<providers>
<clear />
<add name="ADMembershipProvider" type="System.Web.Security.ActiveDirectoryMembershipProvider" connectionStringName="ADConnectionString" attributeMapUsername="sAMAccountName" connectionUsername="******" connectionPassword="******" />
</providers>
</membership>
...
</system.web>
Update: Here is the ApplicationUser class used in the example:
// Must be expressed in terms of our custom Role and other types:
public class ApplicationUser : IdentityUser<int, ApplicationUserLogin,
ApplicationUserRole, ApplicationUserClaim>, IUser<int>
{
public string Name { get; set; }
public string Surname { get; set; }
public async Task<ClaimsIdentity>
GenerateUserIdentityAsync(UserManager<ApplicationUser, int> manager)
{
var userIdentity = await manager
.CreateIdentityAsync(this, DefaultAuthenticationTypes.ApplicationCookie);
return userIdentity;
}
}
I have used Active Directory Authetication at work.
I created application MVC with Windows Authetication and it was done. Application automatically displays AD login with domain.
Choose membership: [Authorize(Roles=#"DomainName\GroupName")]
Ye can see domain and groups in cmd: net user Username /domain
You haven't to use LDAP.
With LDAP see:
see here
i have a mixed system running. Users from a Database (external users) mixed with AD users (internal users) that can login to our system. to communicate with the AD i use a nuget package called LinqToLdap (https://github.com/madhatter22/LinqToLdap). this uses the LDAP protocol so it can be used for authenticating against Unix Ldap servers also.
this is the Authentication method
public bool AuthenticateUser(string userName, string password)
{
InitConfig();
using (var context = new DirectoryContext(_config))
{
var user = context.Query<LdapUserInfo>().FirstOrDefault(x => x.UserPrincipalName.Equals(userName));
var dn = user?.DistinguishedName;
if (string.IsNullOrWhiteSpace(dn))
return false;
using (var ldap = new LdapConnection(new LdapDirectoryIdentifier(_myConfig.Server)))
{
ldap.SessionOptions.ProtocolVersion = 3;
ldap.AuthType = AuthType.Basic;
ldap.Credential = _credentials;
ldap.Bind();
try
{
ldap.AuthType = AuthType.Basic;
ldap.Bind(new NetworkCredential(dn, password));
return true;
}
catch (DirectoryOperationException)
{ }
catch (LdapException)
{ }
}
return false;
}
}
private void InitConfig()
{
if (_config != null)
return;
_config = new LdapConfiguration();
_credentials = new NetworkCredential(_myConfig.Username, _myConfig.Password, _myConfig.Domain);
_config.AddMapping(new AutoClassMap<LdapGroupInfo>(), _myConfig.NamingContext, new[] { "*" });
_config.AddMapping(new AutoClassMap<LdapUserInfo>(), _myConfig.NamingContext, new[] { "*" });
_config.ConfigureFactory(_myConfig.Server).AuthenticateAs(_credentials).AuthenticateBy(AuthType.Basic);
}
I have added a migration to create a user but the code hangs when it hits userRepo.Create(...) and within this method at _userManager.Create(...)
using (UserRepository userRepo = new UserRepository())
{
User adminUser = new User() { IsActive = true, UserName =
"admin#testing.com", CompanyId = 1, Password =
"admintesting" };
adminUser.Role = new Models.Security.Role() { Id = 2 };
userRepo.Create(adminUser);
}
Create method is below
public IdentityResult Create(Model.User user)
{
var userEntity = Mapper.Map<Entity.Security.User>(user);
_dbContext.Set<Entity.Security.User>().Add(userEntity);
var result = _userManager.Create(userEntity, userEntity.Password);
DetachAllEntities();
return result;
}
_dbContext is inherited from IdentityDbContext and instantiated accordingly
UserManager<Entity.Security.User, int> _userManager = new UserManager<Entity.Security.User, int>(new UserStore<Entity.Security.User, Entity.Security.Role, int, Entity.Security.UserLogin, Entity.Security.UserRole, Entity.Security.UserClaim>(_dbContext));
The equivalent async method works elsewhere in the application but I would like the non-async for the migration sake. Any help is highly appreciated.
I know that we can initialise the database when doing a Entity Framework migration using the Seed method, as below.
protected override void Seed(CraigSheppardSoftware.Models.ApplicationDbContext context)
{
context.Users.AddOrUpdate(p => p.UserName,
new ApplicationUser { FullName = "System Admin", UserName="CssOp", UserRole = UserType.SystemAdmin,
LandlinePhone=new ComplexDataTypes.PhoneNumber(), MobilePhone= new ComplexDataTypes.PhoneNumber()
} );
context.SaveChanges();
}
The problem is that the when I try to use that user to login with, I can't as I dont know what the password is.
There is no password field on the database. I notice that there is a PasswordHash field and suspect that this is an encrypted password. How do I create a password hash ?
Use UserManager to create / update the user.
var manager = new UserManager<ApplicationUser>(
new UserStore<ApplicationUser>(context));
var user = manager.Find("CssOp", "ThePassword");
if (user == null)
{
user = new ApplicationUser { UserName = "CssOp", Email = "email#mail.com" };
manager.Create(user, "ThePassword");
}
else
{
user.Email = "newemail#mail.com";
manager.Update(user);
}
I'm developing a complex website with users having multiple roles. The users are also coupled on other items in the DB which, together with their roles, will define what they can see and do on the website.
Now, some users have more than 1 role, but the website can only handle 1 role at a time because of the complex structure.
the idea is that a user logs in and has a dropdown in the corner of the website where he can select one of his roles. if he has only 1 role there is no dropdown.
Now I store the last-selected role value in the DB with the user his other settings. When he returns, this way the role is still remembered.
The value of the dropdown should be accessible throughout the whole website.
I want to do 2 things:
Store the current role in a Session.
Override the IsInRole method or write a IsCurrentlyInRole method to check all access to the currently selected Role, and not all roles, as does the original IsInRole method
For the Storing in session part I thought it'd be good to do that in Global.asax
protected void Application_AuthenticateRequest(Object sender, EventArgs e) {
if (User != null && User.Identity.IsAuthenticated) {
//check for roles session.
if (Session["CurrentRole"] == null) {
NASDataContext _db = new NASDataContext();
var userparams = _db.aspnet_Users.First(q => q.LoweredUserName == User.Identity.Name).UserParam;
if (userparams.US_HuidigeRol.HasValue) {
var role = userparams.aspnet_Role;
if (User.IsInRole(role.LoweredRoleName)) {
//safe
Session["CurrentRole"] = role.LoweredRoleName;
} else {
userparams.US_HuidigeRol = null;
_db.SubmitChanges();
}
} else {
//no value
//check amount of roles
string[] roles = Roles.GetRolesForUser(userparams.aspnet_User.UserName);
if (roles.Length > 0) {
var role = _db.aspnet_Roles.First(q => q.LoweredRoleName == roles[0].ToLower());
userparams.US_HuidigeRol = role.RoleId;
Session["CurrentRole"] = role.LoweredRoleName;
}
}
}
}
}
but apparently this gives runtime errors. Session state is not available in this context.
How do I fix this, and is this
really the best place to put this
code?
How do I extend the user (IPrincipal?) with IsCurrentlyInRole without losing all other functionality
Maybe i'm doing this all wrong and there is a better way to do this?
Any help is greatly appreciated.
Yes, you can't access session in Application_AuthenticateRequest.
I've created my own CustomPrincipal. I'll show you an example of what I've done recently:
public class CustomPrincipal: IPrincipal
{
public CustomPrincipal(IIdentity identity, string[] roles, string ActiveRole)
{
this.Identity = identity;
this.Roles = roles;
this.Code = code;
}
public IIdentity Identity
{
get;
private set;
}
public string ActiveRole
{
get;
private set;
}
public string[] Roles
{
get;
private set;
}
public string ExtendedName { get; set; }
// you can add your IsCurrentlyInRole
public bool IsInRole(string role)
{
return (Array.BinarySearch(this.Roles, role) >= 0 ? true : false);
}
}
My Application_AuthenticateRequest reads the cookie if there's an authentication ticket (user has logged in):
protected void Application_AuthenticateRequest(Object sender, EventArgs e)
{
HttpCookie authCookie = Request.Cookies[My.Application.FORMS_COOKIE_NAME];
if ((authCookie != null) && (authCookie.Value != null))
{
Context.User = Cookie.GetPrincipal(authCookie);
}
}
public class Cookie
{
public static IPrincipal GetPrincipal(HttpCookie authCookie)
{
FormsAuthenticationTicket authTicket = FormsAuthentication.Decrypt(authCookie.Value);
if (authTicket != null)
{
string ActiveRole = "";
string[] Roles = { "" };
if ((authTicket.UserData != null) && (!String.IsNullOrEmpty(authTicket.UserData)))
{
// you have to parse the string and get the ActiveRole and Roles.
ActiveRole = authTicket.UserData.ToString();
Roles = authTicket.UserData.ToString();
}
var identity = new GenericIdentity(authTicket.Name, "FormAuthentication");
var principal = new CustomPrincipal(identity, Roles, ActiveRole );
principal.ExtendedName = ExtendedName;
return (principal);
}
return (null);
}
}
I've extended my cookie adding the UserData of the Authentication Ticket. I've put extra-info here:
This is the function which creates the cookie after the loging:
public static bool Create(string Username, bool Persistent, HttpContext currentContext, string ActiveRole , string[] Groups)
{
string userData = "";
// You can store your infos
userData = ActiveRole + "#" string.Join("|", Groups);
FormsAuthenticationTicket authTicket =
new FormsAuthenticationTicket(
1, // version
Username,
DateTime.Now, // creation
DateTime.Now.AddMinutes(My.Application.COOKIE_PERSISTENCE), // Expiration
Persistent, // Persistent
userData); // Additional informations
string encryptedTicket = System.Web.Security.FormsAuthentication.Encrypt(authTicket);
HttpCookie authCookie = new HttpCookie(My.Application.FORMS_COOKIE_NAME, encryptedTicket);
if (Persistent)
{
authCookie.Expires = authTicket.Expiration;
authCookie.Path = FormsAuthentication.FormsCookiePath;
}
currentContext.Response.Cookies.Add(authCookie);
return (true);
}
now you can access your infos everywhere in your app:
CustomPrincipal currentPrincipal = (CustomPrincipal)HttpContext.User;
so you can access your custom principal members: currentPrincipal.ActiveRole
When the user Changes it's role (active role) you can rewrite the cookie.
I've forgot to say that I store in the authTicket.UserData a JSON-serialized class, so it's easy to deserialize and parse.
You can find more infos here
If you truly want the user to only have 1 active role at a time (as implied by wanting to override IsInRole), maybe it would be easiest to store all of a user's "potential" roles in a separate place, but only actually allow them to be in 1 ASP.NET authentication role at a time. When they select a new role use the built-in methods to remove them from their current role and add them to the new one.