I have installed asp.net identity sample https://www.nuget.org/packages/Microsoft.AspNet.Identity.Samples and trying to create a new role "SAdmin" with the user "Sadmin#example.com". The user is created but "Sadmin" gets the same role as "Admin"
I have modified IdentityConfig.cs to
//Create User=Admin#Admin.com with password=Admin#123456 in the Admin role
public static void InitializeIdentityForEF(ApplicationDbContext db) {
var userManager = HttpContext.Current.GetOwinContext().GetUserManager<ApplicationUserManager>();
var roleManager = HttpContext.Current.GetOwinContext().Get<ApplicationRoleManager>();
const string name = "admin#example.com";
const string password = "Admin#123456";
const string roleName = "Admin";
const string Sname = "Sadmin#example.com";
const string Spassword = "SAdmin#123456";
const string SroleName = "SAdmin";
//Create Super if it does not exist
var Srole = roleManager.FindByName(SroleName);
if (Srole == null)
{
Srole = new IdentityRole(roleName);
var roleresult = roleManager.Create(Srole);
}
var Suser = userManager.FindByName(Sname);
if (Suser == null)
{
Suser = new ApplicationUser { UserName = Sname, Email = Sname };
var result = userManager.Create(Suser, Spassword);
result = userManager.SetLockoutEnabled(Suser.Id, false);
}
// Add Suser to Role Admin if not already added
var SrolesForUser = userManager.GetRoles(Suser.Id);
if (!SrolesForUser.Contains(Srole.Name))
{
var result = userManager.AddToRole(Suser.Id, Srole.Name);
}
//Create Role Admin if it does not exist
var role = roleManager.FindByName(roleName);
if (role == null) {
role = new IdentityRole(roleName);
var roleresult = roleManager.Create(role);
}
var user = userManager.FindByName(name);
if (user == null) {
user = new ApplicationUser { UserName = name, Email = name };
var result = userManager.Create(user, password);
result = userManager.SetLockoutEnabled(user.Id, false);
}
// Add user admin to Role Admin if not already added
var rolesForUser = userManager.GetRoles(user.Id);
if (!rolesForUser.Contains(role.Name)) {
var result = userManager.AddToRole(user.Id, role.Name);
}
}
The problem is in the code... The following code block is responsible
if (Srole == null)
{
**Srole = new IdentityRole(roleName);**
var roleresult = roleManager.Create(Srole);
}
Change the highlighted line to
**Srole = new IdentityRole(SroleName);**
That should solve it
Related
I currently am using an IdentityServer4.
Authentication provider is AD.
I implemented the IResourceOwnerPasswordValidator interface, consequently its method ValidateAsync was implemented.
public Task ValidateAsync(ResourceOwnerPasswordValidationContext context)
{
var username = context.UserName;
var password = context.Password;
var validation = adAuthProvider.Validate(username, password);
if (validation.Valid)
{
username = Utilities.TrimDomain(username);
context.Result = new GrantValidationResult(username, "pwd");
}
else
{
if (validation.ValidationResponseType == ValidationResponseType.Unauthorized)
{
context.Result = new GrantValidationResult(username, "pwd");
}
else
{
context.Result.IsError = validation.ValidationResponseType == ValidationResponseType.Error;
}
}
context.Result.CustomResponse = new Dictionary<string, object>();
context.Result.CustomResponse.Add("ValidationResponse", validation);
return Task.CompletedTask;
}
An implementation of Validate method in AdAuthProvider class
public ValidationResponse Validate(string username, string password)
{
var validation = new ValidationResponse { Valid = false };
var ad = GetActiveDirectoryConfiguration(username);
using (var connection = ldapProvider.Connect(ad.Url, ad.Port))
{
username = username;
var userLoginWithDomainFromConfig = $"{ ad.DistinguishedName }#{ ad.Url }";
connection.Login(userLoginWithDomainFromConfig, ad.Password);
//try to login
connection.Login($"{username}#{ad.Url}", password);
validation.Valid = true;
}
return validation;
}
How to change password policy by allowing Non-alphanumeric characters in the password?
I am trying to create a user for a mixed authentication project. I am using MixedAuthExtension.cs.
I encounter a problem when I reach this line
IdentityResult result = await UserManager.CreateAsync(user,model.Password);
but the system user is created and the AspNetUser.
Thanks in advance for your help
The current code creates both the system user and ASP.NET user but it fails to sync identity
[ValidateAntiForgeryToken]
[HttpPost]
public async Task<ActionResult> CreateSystemUser(RegisterViewModel model, string key)
{
var _context = new RequestToFillDbContext();
#region Initialise
Initialise(_context);
var password = SecurityHelper.GeneratePassword();
UserStore<ApplicationUser> store = new UserStore<ApplicationUser>(_context);
UserManager<ApplicationUser> UserManager = new UserManager<ApplicationUser>(store);
UserManager.UserValidator = new UserValidator<ApplicationUser>(UserManager) { AllowOnlyAlphanumericUserNames = false };
model.Password = password;
model.ConfirmPassword = password;
ModelState.Clear();
#endregion
string serviveNumber = model.ServiceNumber;
if (!_context.SystemUsers.Any(s => s.EmailAddress == model.EmailAddress)
&& !_context.SystemUsers.Any(s => s.UserName == model.UserName))
{
if (ModelState.IsValid)
{
var emp = new RequestToFillApplicationHelper().GetEmployeeByServiceNumber(serviveNumber);
model.Designation = emp.Designation;
//TODO: Query Db for Id
//var identityManager = new IdentityManager();
var user = new ApplicationUser
{
UserName = model.UserName,
Email = model.EmailAddress,
EmailConfirmed = true,
SystemUser = new SystemUser()
{
FirstName = model.FirstName,
LastName = model.LastName,
UserName = model.UserName,
CompanyName = model.CompanyName,
Designation = model.Designation,
EmailAddress = model.EmailAddress,
IsTemporaryPassword = true,
//TempPasswordExpiryDateTime = DateTime.Now.AddHours(24),
SystemUserTypeId = model.SystemUserTypeId,
ServiceNumber = model.ServiceNumber,
IsActive = true,
IsDeleted = false,
IsLocked = false,
CreatedDateTime = DateTime.Now,
IsPasswordReset = false
}
};
//db.SaveChanges();
try
{
IdentityResult result = await UserManager.CreateAsync(user,model.Password);
//Assign user to role
I get a
"Property set method not found."Line 258
which is below
IdentityResult result = await UserManager.CreateAsync(user,model.Password);
Am using DocuSign Api's for signing documents. Now I have created template in DocuSign and Uploaded the PDF's there.
Now when user click's on submit, we need to auto populate docusign pdf's and I don't have custom fields added at docusign and it should be dynamic. Below is the code which is not working.
public string SignDocument()
{
var accountId = Login();
var url = GetRecipientDocumentUrl(accountId);
return url;
}
private string Login()
{
string authHeader = "{\"Username\":\"" + Username + "\", \"Password\":\"" + Password + "\", \"IntegratorKey\":\"" + IntegratorKey + "\"}";
DocuSign.eSign.Client.Configuration.Default.AddDefaultHeader("X-DocuSign-Authentication", authHeader);
// we will retrieve this from the login() results
string accountId = null;
// the authentication api uses the apiClient (and X-DocuSign-Authentication header) that are set in Configuration object
var authApi = new AuthenticationApi();
LoginInformation loginInfo = authApi.Login();
// find the default account for this user
foreach (LoginAccount loginAcct in loginInfo.LoginAccounts)
{
if (loginAcct.IsDefault == "true")
{
accountId = loginAcct.AccountId;
break;
}
}
if (accountId == null)
{ // if no default found set to first account
accountId = loginInfo.LoginAccounts[0].AccountId;
}
return accountId;
}
private string GetRecipientDocumentUrl(string accountId)
{
//var envelope = BuildEnvelopeDefinition(documents);
var envelope = BuildEnvelopeDefinition();
// |EnvelopesApi| contains methods related to creating and sending Envelopes (aka signature requests)
var envelopesApi = new EnvelopesApi();
//TemplateCustomFields
var summary = envelopesApi.CreateEnvelope(accountId, envelope);
//===========================================================
// Step 3: Create Embedded Signing View (URL)
//===========================================================
var viewOptions = BuildRecipientViewRequest(envelope);
var recipientView = envelopesApi.CreateRecipientView(accountId, summary.EnvelopeId, viewOptions);
return recipientView.Url;
}
private EnvelopeDefinition BuildEnvelopeDefinition()
{
TemplateRole templateRole = new TemplateRole();
templateRole.Email = "kpothireddy#firstam.com";
templateRole.Name = "Sample";
templateRole.RoleName = "1";
templateRole.Tabs = new Tabs();
templateRole.Tabs.TextTabs = new List<Text>();
Text textTab = new Text();
textTab.TabLabel = "Approved by";
textTab.Value = "Kranthi";
//textTab.XPosition = "100";
//textTab.YPosition = "100";
templateRole.Tabs.TextTabs.Add(textTab);
templateRole.ClientUserId = Guid.NewGuid().ToString();
List<TemplateRole> rolesList = new List<TemplateRole>();
rolesList.Add(templateRole);
//rolesList.Add(templateRole1);
var envelope = new EnvelopeDefinition
{
TemplateRoles = rolesList,
//TemplateId = "3b07a774-5ec5-4bbd-928a-a4b0bace2fc5",
TemplateId = "44d25c06-4fc3-4cbe-a9d0-7e0e1e3013bc", //Prefill
Status = "sent"
};
//Envelope e = new Envelope();
return envelope;
}
private RecipientViewRequest BuildRecipientViewRequest(EnvelopeDefinition envelope)
{
RecipientViewRequest viewOptions = new RecipientViewRequest()
{
ReturnUrl = ReturnUrl,
ClientUserId = envelope.TemplateRoles.First().ClientUserId, // must match clientUserId set in step #2!
AuthenticationMethod = "email",
UserName = envelope.TemplateRoles.First().Name,
Email = envelope.TemplateRoles.First().Email
//UserName = envelope.Recipients.Signers.First().Name,
//Email = envelope.Recipients.Signers.First().Email
};
return viewOptions;
}
Could you please help me out.
I used following method to create two roles and two users when my web app starts (In Application_Start() in Global.asax.cs).
However the Administrator role is being created but not the User role. Similar thing happens for user named Admin#admin.com and user named user#user.net. First one is being created but not the second one.
Here is my code.
void create() {
ApplicationDbContext context = new ApplicationDbContext();
IdentityResult IdRoleResult;
IdentityResult IdUserResult;
var roleStore = new RoleStore<IdentityRole>(context);
var roleMngr = new RoleManager<IdentityRole>(roleStore);
if (!roleMngr.RoleExists("Administrator"))
IdRoleResult = roleMngr.Create(new IdentityRole("Administrator"));
roleStore = new RoleStore<IdentityRole>(context);
roleMngr = new RoleManager<IdentityRole>(roleStore);
if (!roleMngr.RoleExists("User"))
IdRoleResult = roleMngr.Create(new IdentityRole("User"));
var userMngr = new UserManager<ApplicationUser>(new UserStore<ApplicationUser>(context));
var appUser = new ApplicationUser() { UserName = "Admin#admin.com" };
IdUserResult = userMngr.Create(appUser, "pa$$word");
if (IdUserResult.Succeeded)
IdRoleResult = userMngr.AddToRole(appUser.Id, "Administrator");
userMngr = new UserManager<ApplicationUser>(new UserStore<ApplicationUser>(context));
appUser = new ApplicationUser() { UserName = "user#user.net" };
IdUserResult = userMngr.Create(appUser, "user");
if (IdUserResult.Succeeded)
IdRoleResult = userMngr.AddToRole(appUser.Id, "User");
}
Can anybody tell me, what I've done wrong or any alternative way to perform this.
Thanks in advance.
Updated Code:
void createAdmin() {
ApplicationDbContext context = new ApplicationDbContext();
IdentityResult IdRoleResult;
IdentityResult IdUserResult;
var roleStore = new RoleStore<IdentityRole>(context);
var roleMngr = new RoleManager<IdentityRole>(roleStore);
if (!roleMngr.RoleExists("Administrator")) {
IdRoleResult = roleMngr.Create(new IdentityRole("Administrator"));
if (!IdRoleResult.Succeeded)
throw new Exception("Administrator role wasnt created.");
}
if (!roleMngr.RoleExists("User")) {
IdRoleResult = roleMngr.Create(new IdentityRole("User"));
if (!IdRoleResult.Succeeded)
throw new Exception("User role wasnt created.");
}
var userMngr = new UserManager<ApplicationUser>(new UserStore<ApplicationUser>(context));
ApplicationUser appUser;
var q = from user in userMngr.Users
where user.UserName == "Admin#admin.com"
select user;
if (q.Count() == 0) {
appUser = new ApplicationUser() { UserName = "Admin#admin.com" };
IdUserResult = userMngr.Create(appUser, "pa$$word");
if (IdUserResult.Succeeded) {
IdRoleResult = userMngr.AddToRole(appUser.Id, "Administrator");
if (!IdRoleResult.Succeeded)
throw new Exception("Admin user wasn't added to Administrator role.");
} else
throw new Exception("Admin user wasn't created.");
}
q = from user in userMngr.Users
where user.UserName == "user#user.net"
select user;
if (q.Count() == 0) {
appUser = new ApplicationUser() { UserName = "user#user.net" };
IdUserResult = userMngr.Create(appUser, "user");
if (IdUserResult.Succeeded) {
IdRoleResult = userMngr.AddToRole(appUser.Id, "User");
if (!IdRoleResult.Succeeded)
throw new Exception("User user wasn't added to User role.");
} else
throw new Exception("User user wasn't created.");
}
}
Here I found that, the code is throwing exception with message "User user wasn't created."
throw new Exception("User user wasn't created.");
I think you should reading error in object result 'IdUserResult', and insert user with function CreateAsync().
I have two sub-sites in my sharepoint site,SampleSite1 and SampleSite2 under Parentsite called MainSite.
http://xyz.sharepoint.com/sites/MainSite/ - SiteUrl
http://xyz.sharepoint.com/sites/MainSite/SampleSite1 - Subsite1's Url
http://xyz.sharepoint.com/sites/MainSite/SampleSite2 - Subsite2's Url
Each of the Sites have two groups superUser and NormalUser respectively.
The credential uses SiteUrl of MainSite.
SecureString password = new SecureString();
string pwd = "Pass123";
string UserName = "abc#xyz.com";
password = convertToSecureString(pwd);
ClientContext clientContext = new ClientContext("http://xyz.sharepoint.com/sites/MainSite/");
clientContext.Credentials = new SharePointOnlineCredentials(UserName, password);
Incase of adding user to subsite's groups like NormalUser,Can we use the same sharepoint context with above siteUrl to access and perform operations(add/remove user) in groups present under subsites?
If Yes,how can we do it?I already have built code to add or remove user from a sharepoint site group based on some requirement.
public void AddUserToDMSite(string useremail, string securityGroupName)
{
GroupCollection collGroup = SPContext.Web.SiteGroups;
Group oGroup1 = collGroup.GetByName("UserList");
Group oGroup2 = collGroup.GetByName(securityGroupName);
UserCollection oUserCollection1 = oGroup1.Users;
UserCollection oUserCollection2 = oGroup2.Users;
SPContext.Load(oUserCollection1);
SPContext.Load(oUserCollection2);
SPContext.ExecuteQuery();
var uname = oGroup1.Users.GetByEmail(useremail);
var userCheck = oUserCollection2.Where(u => u.Email == useremail).FirstOrDefault();
if (userCheck == null)
{
Microsoft.SharePoint.Client.User oUser2 = oGroup2.Users.AddUser(uname);
}
SPContext.ExecuteQuery();
}
For subsites you can proceed as follows:
Web oWebsite = clientContext.Web;
clientContext.Load(oWebsite, website => website.Webs);
clientContext.ExecuteQuery();
foreach (Web orWebsite in oWebsite.Webs)
{
AddUserToDMSite(useremail, securityGroupName, orWebSite)
}
and change AddUserToDMSite to work with either sites and subsites as:
public void AddUserToDMSite(string useremail, string securityGroupName, Web aWeb)
{
GroupCollection collGroup = aWeb.SiteGroups;
Group oGroup1 = collGroup.GetByName("UserList");
Group oGroup2 = collGroup.GetByName(securityGroupName);
UserCollection oUserCollection1 = oGroup1.Users;
UserCollection oUserCollection2 = oGroup2.Users;
SPContext.Load(oUserCollection1);
SPContext.Load(oUserCollection2);
SPContext.ExecuteQuery();
var uname = oGroup1.Users.GetByEmail(useremail);
var userCheck = oUserCollection2.Where(u => u.Email == useremail).FirstOrDefault();
if (userCheck == null)
{
Microsoft.SharePoint.Client.User oUser2 = oGroup2.Users.AddUser(uname);
}
SPContext.ExecuteQuery();
}