I am getting a lot of these in my event viewer:
Event code: 4006
Event message: Membership credential verification failed.
Event time: 1/18/2014 11:33:27 AM
Event time (UTC): 1/18/2014 5:33:27 PM
Event ID: dd4b04a795db4e5ab5fafd8243280047
Event sequence: 1224
Event occurrence: 28
Event detail code: 0
Application information:
Application domain: /LM/W3SVC/3/ROOT/SuburbanCustPortal-1-130345141090318852
Trust level: Full
Application Virtual Path: /SuburbanCustPortal
Application Path: C:\inetpub\secure.ssswebportal.com\SuburbanCustPortal\
Machine name: WIN-OB929P97YAR
Process information:
Process ID: 4384
Process name: w3wp.exe
Account name: NT AUTHORITY\NETWORK SERVICE
Request information:
Request URL: http://myurl.com:443/SuburbanCustPortal/Account/Logon2
Request path: /SuburbanCustPortal/Account/Logon2
User host address: xxx.xxx.xxx.xxx
User:
Is authenticated: False
Authentication Type:
Thread account name: NT AUTHORITY\NETWORK SERVICE
Name to authenticate: nancyduve
Custom event details:
It seems to be always happening on the Logon2 url.
Here is my Logon2:
public ActionResult Logon2(LogOnModel model, string returnUrl, string corpid)
{
var control = Logging.StartLog();
control.Source = SourceEnum.WebPortal;
control.SessionId = Session.SessionID;
try
{
Logging.WriteLog("Starting Logon2");
Logging.WriteLog("returnUrl: " + returnUrl);
Logging.WriteLog("corpid: " + corpid);
Logging.WriteLog("model.UserName: " + model.UserName);
Logging.WriteLog("model.Password: " + model.Password);
Logging.WriteLog(string.Format("ModelState.IsValid: {0}", ModelState.IsValid));
if (ModelState.IsValid)
{
if (Membership.ValidateUser(model.UserName, model.Password))
{
Logging.WriteLog("Validated User");
Logging.WriteLog(string.Format("model.UserName: {0}", model.UserName));
FormsAuthentication.SetAuthCookie(model.UserName, true);
if (Url.IsLocalUrl(returnUrl) && returnUrl.Length > 1
&& returnUrl.StartsWith("/")
&& !returnUrl.StartsWith("//")
&& !returnUrl.StartsWith("/\\"))
{
Logging.WriteLog("Redirect(returnUrl)");
return Redirect(returnUrl);
}
Logging.WriteLog("Start _client.RequestCustomersForAccount(model.UserName)");
var customer = _client.RequestCustomerForAccount(model.UserName);
// ********** NO ACCOUNTS FOUND ************
// No customers assigned to this login
// take them to the add account screen
if (customer == null)
{
// no accounts tied to this logon
Logging.WriteLog("No accounts found for this login.");
Logging.WriteLog("RedirectToAction(AddCustomer, Customer)");
// we need to make sure the branch account number is blank from any prior visits
Session[SessionEnums.CurrentAccountGuid.ToString()] = string.Empty;
Session[SessionEnums.CurrentBranchNumber.ToString()] = string.Empty;
Session[SessionEnums.CurrentAccountNumber.ToString()] = string.Empty;
return RedirectToAction("AddCustomer", "Customer");
}
// the account's tokenid that was used when the account was created
// takes presidence over the one being passed in since the account
// login is specific to the original company that they signed up with
Guid acctguid;
if (Guid.TryParse(customer.AccountId, out acctguid))
{
var tokenid = _client.GetAccountTokenId(acctguid);
if (tokenid != Guid.Empty)
{
GetCookieInfo.TokenId = tokenid.ToString();
Session[SessionEnums.TokenId.ToString()] = tokenid.ToString();
}
}
Logging.WriteLog("RedirectToAction(AccountScreen, Customer)");
model.AccountId = customer.AccountId;
// save this account info in the cookie and session
Session[SessionEnums.CurrentAccountGuid.ToString()] = customer.AccountId;
Session[SessionEnums.CurrentBranchNumber.ToString()] = customer.Branch;
Session[SessionEnums.CurrentAccountNumber.ToString()] = customer.AccountNumber;
Logging.WriteLog(string.Format("customer.AccountId: {0}", customer.AccountId));
Logging.WriteLog(string.Format("customer.Branch: {0}", customer.Branch));
Logging.WriteLog(string.Format("customer.AccountNumber: {0}", customer.AccountNumber));
// only 1 account tied to this logon
return RedirectToAction("AccountScreen", "Customer");
}
else
{
var user = Membership.GetUser(model.UserName);
if (user != null && user.IsLockedOut)
{
const string lockedmsg =
"This account has been locked due to too many login attempts. Please reset your password to unlock this account.";
Logging.WriteLog(lockedmsg);
ModelState.AddModelError(string.Empty, lockedmsg);
}
if (user != null && !user.IsApproved)
{
const string lockedmsg =
"This account has been registered but the email that was sent was never authenticated. Please check your email account for this email.";
Logging.WriteLog(lockedmsg);
ModelState.AddModelError(string.Empty, lockedmsg);
}
else
{
const string msg = "Invalid username or password.";
Logging.WriteLog(msg);
ModelState.AddModelError(string.Empty, msg);
}
}
}
// If we got this far, something failed, redisplay form
return View("Logon");
}
catch (Exception ex)
{
Logging.WriteLog(string.Format("exception: {0}", ex.Message));
Logging.WriteException(ex);
return View("Logon");
}
finally
{
Logging.WriteLog(control, "End Logon2");
}
}
Am I missing something in my code or is this a normal log?
Have you checked that your ApplicationName in your Web.Config has been set up correctly? That's when I've seen this error the most.
Alternatively it's possible you have a user (nancy) who is locked out and she keeps trying to log in, have you enabled locking users out and could you check to see if she meets this criteria?
Related
I am using Firebase Unity SDK and I use phone numbers to signup users with the option to link an email address as well. The problem is that the system always signs up the user as new once they enter the OTP (when verifying the phone number in registration) even if the phone number is already signed up in the Authentication.
I was looking for a way to check if the phone number is already signed up before proceeding to register the user but only found the getUserByPhone method that is in the Admin SDK (im using regular Firebase), same thing for checking if the email is in use before linking it to the user.
My signup code:
phoneAuthProvider = PhoneAuthProvider.GetInstance(FirebaseAPI.Auth);
phoneAuthProvider.VerifyPhoneNumber(UserData.phoneNo, 60000, null,
verificationCompleted: (credential) => {
Debug.Log("Phone Auth, auto-verification completed");
},
verificationFailed: (error) => {
Debug.LogError("Phone verification failed: " + error);
},
codeSent: (id, token) => {
phoneAuthID = id;
Prompt_OTP promptInstantiated = OpenPrompt(prompt_OTP).GetComponent<Prompt_OTP>();
promptInstantiated.Init(verifyOTP, null, null);
Debug.Log("Code sent to: " + UserData.phoneNo);
},
codeAutoRetrievalTimeOut: (id) => {
Debug.Log("Phone Auth, auto-verification timed out");
});
OTP verification:
Credential credential = phoneAuthProvider.GetCredential(phoneAuthID, OTP_StringField.Value);
if (credential == null)
{
OnFail("Failed, please try again\n" + phoneAuthID +"," + OTP_StringField.Value);
Debug.LogError("Failed, please try again\n" + phoneAuthID + "," + OTP_StringField.Value);
return;
}
FirebaseAPI.Auth.SignInWithCredentialAsync(credential).ContinueWith(task =>
{
if (task.IsFaulted)
{
Debug.LogError("Signing in with credentials errored: " + task.Exception);
OnFail("OTP verification error, please try again");
return;
}
FirebaseUser user = task.Result;
FirebaseAPI.User = user;
user.TokenAsync(true).ContinueWithOnMainThread(task =>
{
if (task.IsCanceled || task.IsFaulted)
{
Debug.Log("Could not get token");
OnFail("Failed, please try again");
return;
}
UserData.tokenID = task.Result;
authToken = task.Result;
});
AddUserToDB();
});
Email linking:
Credential credential = EmailAuthProvider.GetCredential(email, UserData.user_password);
Debug.Log("Email to link with: " + email);
if(credential != null)
{
FirebaseAPI.Auth.CurrentUser.LinkWithCredentialAsync(credential).ContinueWith(task =>
{
if (task.IsCanceled)
{
Debug.LogError("Linking with credentials canceled");
return;
}
if (task.IsFaulted)
{
Debug.LogError("Linking with credentials errored: " + task.Exception);
return;
}
FirebaseUser user = task.Result;
});
}
There is no call in the client-side APIs for Firebase to find a user by their phone number, or even to check if a phone number is already registered.
The two most common options are to:
Either write your own custom API endpoint, where you then implement the functionality using the Admin SDK.
Implement your own custom storage of the phone numbers that are used in your app, using a cloud-hosted database such as the ones in Firebase.
Whichever of these solutions you pick, be sure to secure access to the list of phone numbers properly.
I am using Firebase to allow the user to login to a Unity game via Facebook. It is working fine, but I cannot get access to the user's email by using this parameter auth.CurrentUser.Email. Also, the email is not stored in Firebase Authentication Console. The email can be stored/accessed succussfully when I use other sign-in methods, such as email and google.
Here is my code:
public void SignInFacebook()
{
var perms = new List<string>() { "public_profile", "email", "user_friends" };
FB.LogInWithReadPermissions(perms, AuthCallback);
}
private void AuthCallback(ILoginResult result)
{
if (FB.IsLoggedIn)
{
// AccessToken class will have session details
var aToken = Facebook.Unity.AccessToken.CurrentAccessToken;
// Print current access token's User ID
Debug.Log(aToken.UserId);
// Print current access token's granted permissions
foreach (string perm in aToken.Permissions)
{
Debug.Log(perm);
}
Credential credential = FacebookAuthProvider.GetCredential(aToken.TokenString);
auth.SignInWithCredentialAsync(credential).ContinueWithOnMainThread(task => {
if (task.IsCanceled)
{
Debug.LogError("SignInWithCredentialAsync was canceled.");
return;
}
if (task.IsFaulted)
{
Debug.LogError("SignInWithCredentialAsync encountered an error: " + task.Exception);
return;
}
Firebase.Auth.FirebaseUser newUser = task.Result;
Debug.LogFormat("User signed in successfully: {0} - {2} - ({1})",
newUser.DisplayName, newUser.UserId, newUser.Email);
});
}
else
{
Debug.Log("User cancelled login");
}
}
And this is what it looks like in the console ("-" is where the email is supposed to be stored. If I use another sign-in method, such as email or google, the email is stored without any issues)
Similar questions were asked about this issue and it was suggested that I change the Account email address setting in Firebase to Prevent creation of multiple accounts with the same email address, but it did not solve the issue.
Thanks!
If your Facebook app is in test mode you must login from your Facebook ID. Go to the settings, scroll down, select Apps and Websites, and click on your app. From there, make sure email address require is enabled.
you can try this
private void FacebookAuthCallback(ILoginResult result)
{
if (FB.IsLoggedIn)
{
FB.API("/me?fields=id,name,email", HttpMethod.GET, FacebookGetInfo);
}
else
{
Debug.Log("User cancelled login");
}
}
private void FacebookGetInfo(IResult result)
{
if (result.Error == null)
{
if (result.ResultDictionary.ContainsKey("email"))
{
string aEmail = result.ResultDictionary["email"].ToString();
return;
}
}
else
{
Debug.Log(result.Error);
}
}
I have the following code as part of a web application for my Active Directory users to be able to update their passwords (for active directory and gmail at the same time). I am using C# with System.DirectoryServices.AccountManagement.
This code worked until yesterday
try
{
State.log.WriteLine("Connecting LDAP.");
string ldapPath = "LDAP://192.168.76.3";
DirectoryEntry directionEntry = new DirectoryEntry(ldapPath, domainName + "\\" + userName, currentPassword);
if (directionEntry != null)
{
DirectorySearcher search = new DirectorySearcher(directionEntry);
State.log.WriteLine("LDAP Connected, searching directory for SAMAccountName");
search.Filter = "(SAMAccountName=" + userName + ")";
SearchResult result = search.FindOne();
if (result != null)
{
State.log.WriteLine("Getting User Entry.");
DirectoryEntry userEntry = result.GetDirectoryEntry();
if (userEntry != null)
{
State.log.WriteLine("Setting Password");
if (force)
{
userEntry.Invoke("SetPassword", new[] { newPassword });
}
else
{
userEntry.Invoke("ChangePassword", new object[] { currentPassword, newPassword });
}
userEntry.CommitChanges();
State.log.WriteLine("Changes Committed to ActiveDirectory.");
}
else
{
State.log.WriteLine("Could not get user Entry...");
}
}
else
{
State.log.WriteLine("Search returned no results.");
}
}
else
{
State.log.WriteLine("Could not connect to LDAP with given username and passwd");
}
}
Since yesterday, this code makes it to the line:
userEntry.Invoke("ChangePassword", new object[] { currentPassword, newPassword });
and then throws the following exception:
[8:37:00 AM] : Password Requirements Met.
[8:37:00 AM] : Connecting LDAP.
[8:37:00 AM] : LDAP Connected, searching directory for SAMAccountName
[8:37:01 AM] : Getting User Entry.
[8:37:01 AM] : Setting Password
[8:37:01 AM] : Failed to reset Windows Password for jason.
Exception has been thrown by the target of an invocation.
The system cannot contact a domain controller to service the authentication request. Please try again later. (Exception from HRESULT: 0x800704F1)
The "force" option using "SetPassword" still works just fine, but the "ChangePassword" method which can be invoked by non-administrator users does not.
Change userPrincipal.ChangePassword("Old pass", "New Pass"); to userPrincipal.SetPassword(model.NewPassword);
I found a work-around and forgot to post it. What I did was use the code above to authenticate the user and then just call my "ForceChangePassword" method:
public static void ForceChangeADPassword(String username, String newPassword)
{
String DN = "";
try
{
DN = GetObjectDistinguishedName(objectClass.user, returnType.distinguishedName, username, DOMAIN_CONTROLLER_IP);
}
catch(Exception e)
{
throw new PasswordException(String.Format("Could not find AD User {0}", username), e);
}
if(DN.Equals(""))
throw new PasswordException(String.Format("Could not find AD User {0}", username));
DirectoryEntry userEntry = new DirectoryEntry(DN.Replace("LDAP://", LdapRootPath), "accounts", AcctPwd);
userEntry.Invoke("SetPassword", new object[] { newPassword });
userEntry.Properties["LockOutTime"].Value = 0;
userEntry.CommitChanges();
userEntry.Close();
}
Earlier this month Microsoft released a security patch, resolving some vulnerabilities in the area of password change. Specifically, the update blocked fallback to NTLM authentication after a failed Kerberos authentication when changing a password.
You might want to read more about the update here.
Microsoft has updated this article: https://support.microsoft.com/en-us/kb/3177108 . Here they have given us problems created by the original "fixes" as well as some tips for working with Kerberos and self-service password reset.
As of October 11, 2016 Microsoft re-released the patches associated with https://technet.microsoft.com/en-us/library/security/ms16-101.aspx to resolve issues caused by the original updates (which you can read in https://support.microsoft.com/en-us/kb/3177108 including the fact that you could no longer change passwords on local accounts).
I created MVC 4 application. In that application If user forgot the password I have method to send an email to user to reset password. I'm using asp.net Identity membership
I'm getting following error message when I deploy this project in web server. Its working perfectly in my localhost mode.
Error Message
Cannot edit this User The data protection operation was unsuccessful.
This may have been caused by not having the user profile loaded for
the current thread's user context, which may be the case when the
thread is impersonating.!
this is the forgot password method
[AllowAnonymous]
public ActionResult ForgotPassword()
{
return View();
}
[HttpPost]
[AllowAnonymous]
[ValidateAntiForgeryToken]
public async Task<ActionResult> ForgotPassword(ForgotPasswordViewModel model)
{
if (model.UserName == null)
{
ModelState.AddModelError("", "Please enter the Username");
}
if (model.Email == null)
{
ModelState.AddModelError("", "Please enter the Email ID");
}
if (model.Email == null & model.UserName == null)
{
ModelState.AddModelError("", "Please enter the Username and Email ID");
}
if(ModelState.IsValid)
{
var username = await UserManager.FindByNameAsync(model.UserName);
var user = await UserManager.FindByEmailAsync(model.Email);
if (user != null && username != null)
{
ApplicationDbContext context = new ApplicationDbContext();
UserStore<ApplicationUser> store = new UserStore<ApplicationUser>(context);
var provider = new Microsoft.Owin.Security.DataProtection.DpapiDataProtectionProvider("MyProject");
UserManager.UserTokenProvider = new Microsoft.AspNet.Identity.Owin.DataProtectorTokenProvider<ApplicationUser>(provider.Create("EmailConfirmation"));
var code = await UserManager.GenerateEmailConfirmationTokenAsync(user.Id);
System.Net.Mail.MailMessage m = new System.Net.Mail.MailMessage(
new System.Net.Mail.MailAddress("sample#email.lk", "My Application"),
new System.Net.Mail.MailAddress(user.Email));
m.Subject = "Reset your Password";
m.IsBodyHtml = true;
m.Body = string.Format("<img src=\"##IMAGE##\" alt=\"\"><BR/><BR/>Hi {0},<BR/><BR/>Please click the below link to reset your password. <BR/><BR/> Reset Password", user.UserName, Url.Action("ResetPassword", "Account", new { UserId = user.Id, code = code }, Request.Url.Scheme)) + string.Format("<BR/><BR/>Regards,<BR/>We Are <BR/>");
string attachmentPath = Server.MapPath("~/Images/hec-logo.png");
string contentID = Path.GetFileName(attachmentPath).Replace(".", "") + "#zofm";
Attachment inline = new Attachment(attachmentPath);
inline.ContentDisposition.Inline = true;
inline.ContentDisposition.DispositionType = DispositionTypeNames.Inline;
inline.ContentId = contentID;
inline.ContentType.MediaType = "image/png";
inline.ContentType.Name = Path.GetFileName(attachmentPath);
m.Attachments.Add(inline);
// replace the tag with the correct content ID
m.Body = m.Body.Replace("##IMAGE##", "cid:" + contentID);
System.Net.Mail.SmtpClient smtp = new System.Net.Mail.SmtpClient("11.11.11.111");
smtp.Port = 11;
smtp.Credentials = new System.Net.NetworkCredential("sample#email.lk", "8888888");
smtp.EnableSsl = false;
smtp.Send(m);
// Don't reveal that the user does not exist or is not confirmed
}
return View("ForgotPasswordConfirmation");
}
else
{
ModelState.AddModelError("", "The Username or Email ID is invalid.");
}
// If we got this far, something failed, redisplay form
return View(model);
}
I had same issue , then after many research I found out that problem is in IIS deployment
so following this thread I able to fix my issue
The data protection operation was unsuccessful. This may have been caused by not having the user profile loaded for the current thread’s user context, which may be the case when the thread is impersonating.
Open your IIS Manager
Find out what AppPool your application is using by selecting your App, right-click on it, and Select Manage Application -> Advanced
Settings.
After that, on the top left hand side, select Applications Pools, and go ahead and select the App Pool used by your app.
Right-click on it, and select Advanced Settings, Go to the Process Model Section and Find the “Load User Profile” Option and set it to
true.
Here is my login code, the problem happens to users redirected to "Profile" after logging in.
protected void UserLogin_Click(object sender, EventArgs e)
{
if (IsValid)
{
var manager = new IdentityModels.UserManager();
IdentityModels.User user = manager.Find(Username.Text, Password.Text);
if (user != null)
{
if (isUserActive(user.PatientId)=="isNotActive")
{
lblError.Text =
"you are no longer active. Please contact your local clinic to find out why.";
return;
}
if (isUserActive(user.PatientId) == "clinicNotActive")
{
lblError.Text =
"Your clinic is no longer active. Please contact your local clinic to find out why.";
return;
}
IdentityModels.IdentityHelper.SignIn(manager, user, RememberMe.Checked);
if (manager.IsInRole(user.Id,"Administrator") || manager.IsInRole(user.Id,"Staff") || manager.IsInRole(user.Id,"Physician"))
{
Response.Redirect("Dashboard");
}
if (Request.QueryString["Profile"] != null)
{
IdentityModels.IdentityHelper.RedirectToReturnUrl(Request.QueryString["Profile"], Response);
}
else
{
Response.Redirect("Profile");
}
}
else
{
ModelState.AddModelError("", "Invalid username or password");
lblError.Text = "Invalid username or password";
}
}
}
here is my page load code on the Profile page:
var manager = new IdentityModels.UserManager();
IdentityModels.User user = manager.FindById(HttpContext.Current.User.Identity.GetUserId());
if (user == null)
{
var ex = new Exception("patient was null, BUT TRIED SIGNING IN NOW" + UserAccess.GetUserId().ToString());
Elmah.ErrorSignal.FromCurrentContext().Raise(ex);
Response.Redirect("Login");
}
Elmah logs show the exception "patient was null, BUT TRIED SIGNING IN NOW 0".
So if my users are signing in successfully, which they must be because they are hitting the profile page, then why do some of them hit this error. Why is the user null?
I just can't figure it out, why it effects some but not all. When I republish the website all users can then login for a few minutes, sometimes a few hours, then it starts again.
Try using User.Identity rather than HttpContext.Current.User.Identity. I've seen some cases where the context (which is based on ASP.NET's session) gets out of sync with Identity's tokens.
OK guys, here is the answer.
Change the session state from InProc, in my case to SQLServer, it's been 22 hours since a login redirect, which hasn't happened before, so I think it's safe to say the problem is solved and that was the answer.