How to check WebSecurity 'Password Reset Token ID' validity? - c#

I've been looking for a method from WebSecurity library to check the validity of the reset password token before open a reset password page for users, but unfortunately no luck!
the only thing that I've found so far is
WebSecurity.ResetPassword('new password', 'token id');
This method resets the password using a new password and if the token is not valid it will return a false value which is good but in my case I need to only check the validity of the ResetTokenId not resetting a password and that's it.
So I was wondering if anyone knows any other methods or extensions that could help me with checking the validity of the token id?
Thanks

Use WebSecurity.GetUserIdFromPasswordResetToken to find a matching user ID. If the value is -1, you don't have a valid token.

Related

What is the logic is MembershipUser.ResetPassword() method

Normally, ResetPassword(string passwordAnswer) returns a new password for the membership user. ChangePassword(string oldPassword,string newPassword) takes two parameters: old and new password. I'm OK with that but in the code below:
string pwd = mu.ResetPassword(k.SecretAnswer);
mu.ChangePassword(pwd, k.password);
return RedirectToAction("Login");
According to this code, pwd is contains old password, but ResetPassword() method returns a new random password. So how can pwd represent old password? Shouldn't the ResetPassword() method return a new password? What am I missing? What is the logic is behind?
Reset password created a password that must be reset upon first usage. It is used more as a token (in the auth realm) than an actual password.
So when you called mu.ChangePassword(pwd, k.password);, you "exchanged" the pwd token for a "normal" password.
If you had skipped changing the password in the line above and tried to log in using pwd from the Reset method it would not have succeeded.
The UI would force you to change your password and then login with the new password.
This is designed so a user is the only one to have ever seen their password in plain text (ie unencrypted).
EDIT: What exactly is a token and what is the difference between a token and a password?
Short answer(s):
A password can be used multiple times while a token can only be used once.
A password is verified while a token is redeemed.
A password requires verification for each use. A token requires verification before it is given.
While both tokens and passwords are used to gain access, it's how they are used that differentiates them.
Let's try some real-world examples (granted these examples don't align 100% with our use case, but I believe they could help).
The PIN for your ATM card is a password because:
it is secret
it is verified each time you use it
you can use it over and over
If you take a suit to the dry cleaners, they hand you a ticket (with a number) that you will use to get your suit back. That's a token because:
You must physically possess the ticket to get your suit back
If you have the ticket, you get the suit. No questions asked. You proved it was your suit when you dropped it off.
Once you use it, the ticket is worthless.

reset password in custom membership

i just want to reset password using mvc 4 c#
FYI: i am using my own custom authentication and authorization ,
i know that the best way is to send link for reset password ,
i just need article or code snippet apply this without membership,
i want to know how to make link expire? and how to generate unique link? and what is token ? and the use of token in rest password?
FYI:when i am build my own authorize system i just override AuthorizeCore function like this
protected override bool AuthorizeCore(HttpContextBase httpContext)
{
}
is there any functions like AuthorizeCore to confirm account or change password can override ?
appreciate help thanks
Splitting up the problem":
Generate a GUID to create a unique link
I like links that are not recognizable by the user; your best candidate is probably a random number or a GUID (http://en.wikipedia.org/wiki/Globally_unique_identifier).
System.Guid.NewGuid().ToString("P"));
Persist the username + expiry time with the GUID
Either in memory or in your database, store the guid, the username and the timeout data. You do not expose this data to the outside
Reset the password
Your user clicks ",,/reset&guid=3432432. You retrieve the data in your database and the username, the timeout to the guid provided and reset the password (or not)

Does FormsAuthentication.SetAuthCookie() Require a Redirect?

After checking a user's credentials and confirming they are good, I'm using FormsAuthentication.SetAuthCookie("Username", false); to authenticate the user.
In the masterpage I then use Page.User.Identity.IsAuthenticated to make sure we're dealing with a logged in user and not a guest.
The problem lies in first setting the auth cookie. When I set the auth cookie, immediately afterwards I run a method that uses Page.User.Identity.IsAuthenticated to change the welcome message from a generic "Welcome, guest!" message to a more personal "Welcome, username!" message. This does not work until I go to another page, so I know the login process has worked, but it seems I cannot access the information I need until a refresh or a redirect happens.
Do I need to redirect the user after setting the auth cookie in order use Page.User.Identity.IsAuthenticated to change the message?
I have seen this before so I know the answer is yes. (As in, yes you do need to redirect the user to correctly use Page.User.Identity.IsAuthenticated)
What I imagine is the cause is because IsAuthenticated evaluates the current request, and when the current request first came in it was recorded as not authenticated.
What you will need to do is apply whatever logic you have in said method without the check for IsAuthenicated (make it assume true).
Now I don't know the details of your method as to suggest how to re-factor it to cope with this, but you could split out the "Do Stuff" part into a separate function which you could then call directly from you login function to bypass the authentication check.
EDIT: To back up my assumption you can read this page.
The interesting part:
The forms-authentication ticket supplies forms-authentication
information to the next request made by the browser.
I'd like to point out that there's actually a way around this (since I've never seen this said in any other question like this). You can retrieve the cookie and its data where User.Identity's information comes from without a redirect. The thing is, the cookie just hasn't been sent to the browser yet.
It simply gets the cookie made by FormsAuthentication from the Response.Cookies object:
HttpCookie EncryptedCookie = Response.Cookies.Get(FormsAuthentication.FormsCookieName);
FormsAuthenticationTicket DecryptedCookie;
try {
DecryptedCookie = FormsAuthentication.Decrypt(EncryptedCookie.Value);
} catch (ArgumentException) {
// Not a valid cookie
return false;
}
// DecryptedCookie.Name: The Username
// DecryptedCookie.UserData: Any additional data, as a string. This isn't normally used
return !DecryptedCookie.Expired;

Forgot password: How can I send an email to user in DotNetNuke

I have made custom login control for DNN (DotNetNuke). Now I am trying to implement the forgot password feature. I am able to retrieve password from the database using the code:
UserInfo uInfo = UserController.GetUserByName(this.PortalId, userName);
if (uInfo != null)
{
string password = UserController.GetPassword(ref uInfo, String.Empty);
}
I want to send the retrieved password to the user using DNN.
Any help will be appreciated.
Sending passwords via email is considered as a big security vulnerability and really not recomended.
If you still need this functionality though, I guess you can simply accomplish this by sending email through SendMail or SendEmail methods:
DotNetNuke.Services.Mail.Mail.SendEmail()
DotNetNuke.Services.Mail.Mail.SendMail()
The SendMail method provides more options/parameters than the SendEmail method. The paramters names should be self explanatory enough to use the methods.
The simplest way to send a user their password is to call the DotNetNuke.Services.Mail.Mail.SendMail overload that takes a UserInfo, a MessageType, and PortalSettings. You can pass in the user and MessageType. PasswordReminder and DNN will take care of the rest.
That said, I join the crowd in saying that it would be much better to switch to using hashed passwords and consider this an impossible feature request (that should, instead, be fulfilled with a password reset feature).

Determine AD password policy programmatically

I have been using the System.DirectoryService (ADSI) classes and methods to create and change users in an Active Directory.
Recently we added a feature to allow users to set their own password through the system. However, using the SetPassword method throws an exception when the password is not accepted by the Password Policy set.
userEntry.Invoke("SetPassword", new object[] {password});
My question is: How do I check to see if a password lives up to the password policy, before attempting to use the SetPassword-method?
I read in this post that you can get the Password Policy-settings from the root domain node, but where can I read more about what each attribute means? For instance, which characters are required to fullfill the "Complexity" policy?
Once I know this, I can implement my own password check-method, but as this is an error-prone approach, I would rather use a built-in check and give the user appropriate info on what is wrong with their password.
I am working on a similar project at my work. We are rolling a forgot password application. I ended up just doing an Invoke("SetPassword", "[randomString]") and saved the random string for the Invoke("ChangePassword","[randomString]","[user supplied pw]"). The result of the ChangePassword was returned to the user.
SetPassword does not check for password complexity or history rules. It is the same as right clicking a user in AD and selecting "Reset Password." ChangePassword however, does check for password history requirements.
The API function you want is NetValidatePasswordPolicy.
There are three modes it operates in:
NetValidateAuthentication: if you are authenticating a user; so the function can check password expiration policies, bad login attempts, account lockouts, bad login attempts, etc
NetValidatePasswordChange: if the user is changing their password; so the function can check against lockout, or against the password policy
and the mode you want:
NetValidatePasswordReset: you are an admin resetting a user's password; which only checks the password complexity.
I'll try transcoding from another language to C# on the fly; but you will have to P/Invoke it.
<summary>Check password during password reset.
The result from NetValidatePasswordReset, this member can be one of the following values.
NERR_Success The password passes the validation check.
NERR_PasswordTooShort Validation failed. The password does not meet policy requirements because it is too short.
NERR_PasswordTooLong Validation failed. The password does not meet policy requirements because it is too long.
NERR_PasswordNotComplexEnough Validation failed. The password does not meet policy requirements because it is not complex enough.
NERR_PasswordFilterError Validation failed. The password does not meet the requirements of the password filter DLL.
</summary>
UInt32 TestPasswordComplexity(String username, SecureString password)
{
//All code on stack overflow is in the public domain; no attribution
//is required.
const UInt32 NetValidatePasswordReset = 3;
NET_VALIDATE_PASSWORD_RESET_INPUT_ARG args = new NET_VALIDATE_PASSWORD_RESET_INPUT_ARG();
args.UserAccountName = Username; //some policies check that your password cannot contain your username
args.ClearPassword = SecureStringToString(password);
PNET_VALIDATE_OUTPUT_ARG res;
DWORD le = NetValidatePasswordPolicy(null, null, NetValidatePasswordReset, #args, {out}Pointer(res));
if (le <> NERR_Success)
throw new WindowsException(le); //
return res.ValidationStatus;
}
The complexity policy is that it must contain three out of five of these types:
Upper case letters
Lower case letters
Digits
Non-alphanumeric characters: ~!##$%^&*_-+=`|(){}[]:;"'<>,.?/
Unicode characters that are alphabetics but not uppercase or lowercase.
It also can't be the sAMAccountName or displayName (or parts of). You can read about it here. The other password policy rules are in adjacent documents.
You could try setting it and catch exceptions but from memory I don't think it tells you what's wrong with the password, just that it doesn't meet the requirements.

Categories

Resources