Webmatrix Reset password - c#

I want to know how to set a password using mvc4 providers without knowing the old password ?
I want to make a forgot password function, where the user receives a secure link via email and then clicks the link, gets directed to the my application and then has to fill in only the new password, no security questions needed.
It was easy to do this with the membership providers that came with mvc3. I'm now using the simple membership providers that come with mvc4 and I'm having trouble getting it working.
the code so far looks as simple as:
MembershipUser user = Membership.GetUser( cust.Email );
String pass = user.GetPassword();
Boolean success = WebSecurity.ChangePassword( cust.Email, pass, model.Password );
It currently gives error on the above line that calls GetPassword() with the error :
Specified method is not supported.
I'll show the relevant section in the web.config also here :
<system.web>
<roleManager enabled="true" defaultProvider="SimpleRoleProvider">
<providers>
<clear/>
<add name="SimpleRoleProvider" type="WebMatrix.WebData.SimpleRoleProvider, WebMatrix.WebData"/>
</providers>
</roleManager>
<membership defaultProvider="SimpleMembershipProvider">
<providers>
<clear/>
<add name="SimpleMembershipProvider" type="WebMatrix.WebData.SimpleMembershipProvider, WebMatrix.WebData"
enablePasswordRetrieval="true" enablePasswordReset="true" passwordFormat="Encrypted" requiresQuestionAndAnswer="false"
requiresUniqueEmail="false" maxInvalidPasswordAttempts="5" minRequiredPasswordLength="5" minRequiredNonalphanumericCharacters="0"
passwordAttemptWindow="10" />
</providers>
</membership>
Above I tried to add the attributes you use for the providers in mvc3 but it doesn't seem to be applicable here.

WebSecurity.GeneratePasswordResetToken generates and returns a unique string.
WebSecurity.ResetPassword uses that token to change the password.
Give the user a link to an action with the token as a parameter, then give them a simple form to change their password.

Related

Authenticating an AD user using Membership Provider

I am running into a weird problem.
Synopsis
My login page can authenticate against SQL uses or AD users. To identify if a user is an AD user, user name should contain a backslash.
The logic for SQL works fine, but I am getting the most generic error (Object reference not set to an instance of an object.) when authenticating a user against AD.
Details
For SQL users, I've CustomSqlMembershipProvider(). The call is like this:
if(Membership.Provider.ValidateUser(userName, userPassword))
userAuthenticated = true;
The class CustomSqlMembershipProvider() sends the credentials to SQL database.
For AD users, I've this logic:
if (Membership.Providers["ADMembership"].ValidateUser(userName, userPassword))
userAuthenticated = true;
This above if statement is generating the error Object reference not set to an instance of an object.
Web.config
<add name="ConnectionStringAD" connectionString="LDAP://it.CompanyName.local" />
...
<membership defaultProvider="CustomSqlMembershipProvider" userIsOnlineTimeWindow="30">
<providers>
<clear/>
<add name="CustomSqlMembershipProvider"
type="Authentication.MembershipProviders.CustomSqlMembershipProvider"
connectionStringName="SqlProviderConnectionString"
enablePasswordRetrieval="false"
enablePasswordReset="true"
requiresQuestionAndAnswer="false"
requiresUniqueEmail="false"
maxInvalidPasswordAttempts="5"
minRequiredPasswordLength="6"
minRequiredNonalphanumericCharacters="0"
passwordAttemptWindow="10"
applicationName="/" />
<add name="ADMembership"
type="System.Web.Security.ActiveDirectoryMembershipProvider, System.Web, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a"
connectionStringName="ConnectionStringAD"
connectionUsername="it\LDAPuser"
connectionPassword="LDAPuserPassword"
connectionProtection="Secure"
maxInvalidPasswordAttempts="5"
attributeMapUsername="sAMAccountName" />
</providers>
</membership>
I strongly think that there is some small issue, but I could not figure it out.
Software
Visual Studio 2010
.NET 4.0
Server 2008 R2 with SP2 (10.50.4000)
IIS 7.5
Its not an answer directly but few suggestion to narrow down the problem:
Try changing defaultProvider in web.config. Set it to ADMembership.
Break down the call:
if (Membership.Providers["ADMembership"].ValidateUser(userName, userPassword))
userAuthenticated = true;
to
var activeDirectoryProvider = Membership.Providers["ADMembership"];
if(activeDirectoryProvider != null)
{
userAuthenticated = true;
}
else
{
Log("activeDirectoryProvider is null");
}
This is wild guess :). Rename "ADMembership" to "ADMembershipProvider" suffixing "Provider" just in case some convention stuff.

ASP.NET membership provider generates two applications in the database

I am using the below defined membership provider web config settings. when I access my admin pages to start to add roles and users to the system generated SQL Server tables I see two applications created. one with a application name of "/" and the second is called what my setting is configured to PolyWebSite.
My steps are:
as an unauthenticated user I browse to role config page to add admin and other roles. this is when the first application is created.
I browse to a custom user page where I add users and assign them roles. also as an unauthenticated user. this is when a second application is created with the name PolyWebSite as set in my web.config
<roleManager enabled="true" />
<membership defaultProvider="AspNetSql2005MembershipProvider">
<providers>
<add name="AspNetSql2005MembershipProvider"
type="System.Web.Security.SqlMembershipProvider, System.Web, Version=2.0.0.0"
connectionStringName="SqlConnString"
enablePasswordReset="true"
requiresQuestionAndAnswer="true"
applicationName="PolyWebSite"
requiresUniqueEmail="false"
maxInvalidPasswordAttempts="5"
minRequiredPasswordLength="1"
minRequiredNonalphanumericCharacters="0"
passwordAttemptWindow="10"
passwordStrengthRegularExpression=""
passwordFormat="Clear"/>
</providers>
</membership>
figured it out: added details to the roleManager part of the web.config to be in sync with membership section. items added were connectionStringName and applicationName.
<membership defaultProvider="AspNetSql2005MembershipProvider">
<providers>
<add name="AspNetSql2005MembershipProvider"
type="System.Web.Security.SqlMembershipProvider, System.Web, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a"
connectionStringName="SqlConnString"
enablePasswordReset="true"
requiresQuestionAndAnswer="true"
applicationName="PolyWebSite"
requiresUniqueEmail="true"
maxInvalidPasswordAttempts="5"
minRequiredPasswordLength="1"
minRequiredNonalphanumericCharacters="0"
passwordAttemptWindow="10"
passwordStrengthRegularExpression=""
passwordFormat="Clear"/>
</providers>
</membership>
<roleManager enabled ="true" defaultProvider ="SqlRoleProvider" >
<providers>
<add name ="SqlRoleProvider"
type="System.Web.Security.SqlRoleProvider"
connectionStringName="SqlConnString"
applicationName="PolyWebSite"/>
</providers>
</roleManager>

Access asp.net membership profile values from a different application scope

I have a solution which includes a website and WCF web service. Within the website I need to get the current logged on user and access a property value in their profile which specifies the username of another user (used for web service). I then need to get a property from the web service user profile (not the logged on web site user!).
So far I have this :
if (HttpContext.Current != null)
{
if (!string.IsNullOrEmpty(HttpContext.Current.Profile.UserName))
{
serviceUsername = HttpContext.Current.Profile.GetPropertyValue("WSUserName").ToString();
if (!string.IsNullOrEmpty(serviceUsername))
{
ProfileBase profile = ProfileBase.Create(serviceUsername);
var siteId = profile.GetPropertyValue("SiteID");
}
}
}
Which almost works, I can get the web service user profile by name but I can see the {ProfileCommon} is showing the properties of the web application instead of the web service so I am unable to see the value I need.
Any advice on how I might be able to achieve this?
OK I managed to get this working by adding additional membership and profile providers to my web.config, including an additional web service property with additional provider attribute :
<membership>
<providers>
<!--(website provider here)-->
<!--additional web service provider-->
<add name="WebServiceMembershipProvider"
type="System.Web.Security.SqlMembershipProvider"
connectionStringName="ApplicationServices"
enablePasswordRetrieval="false"
enablePasswordReset="true"
requiresQuestionAndAnswer="false"
requiresUniqueEmail="true"
maxInvalidPasswordAttempts="5"
minRequiredPasswordLength="6"
minRequiredNonalphanumericCharacters="0"
passwordAttemptWindow="10"
applicationName="MyWebService" />
</providers>
</membership>
<profile>
<providers>
<add name="WebServiceMembershipProvider"
type="System.Web.Profile.SqlProfileProvider"
connectionStringName="ApplicationServices"
applicationName="MyWebService"/>
</providers>
<properties>
<!-- example website property -->
<add name="website_property1"
type="string"/>
<!-- example web service property with additional provider attribute-->
<add name="webservice_property1"
type="string"
provider ="WebServiceMembershipProvider"/>
</properties>
</profile>
<roleManager enabled="true">
<providers>
<!-- (website provider here) -->
<!-- web service provider-->
<add connectionStringName="ApplicationServices"
applicationName="MyWebService"
name="WSAspNetSqlRoleProvider"
type="System.Web.Security.SqlRoleProvider" />
</providers>
</roleManager>
Then in codebehind :
Membership.ApplicationName = "MyWebService";
MembershipUser user = Membership.Providers["WebServiceMembershipProvider"].GetUser(serviceUsername, false);
profile = ProfileBase.Create(serviceUsername);
profile.Initialize(user.UserName, true);
var myProperty = profile.GetPropertyValue("webservice_property1");
hope this helps someone else!

how to custom membership providers

I want use custom Role Provider in website. I have this table in Sql server:
and I have this class for custom role provider:
public class CustomRoleProvider : RoleProvider
{
...
}
please help me for use custom membership in web.config. I use this code:
<membership defaultProvider="CustomRoleProvider">
<providers>
<clear/>
<add name="CustomRoleProvider" type="Login1.Code.CustomRoleProvider" connectionStringName="LoginDB1Entities"
enablePasswordRetrieval="false" enablePasswordReset="true" requiresQuestionAndAnswer="false" requiresUniqueEmail="false"
maxInvalidPasswordAttempts="5" minRequiredPasswordLength="6" minRequiredNonalphanumericCharacters="0" passwordAttemptWindow="10"
applicationName="/" />
</providers>
</membership>
but when you login get this error from web.config:
Provider must implement the class 'System.Web.Security.MembershipProvider'.
I want convert project to asp.net 4
A role provider and a membership provider are two different things.
You need to implement both of them in your case, because you have a custom user as well.
You would register the RoleProvider like this:
<roleManager enabled="true" defaultProvider="WebConfigRoleProvider">
<providers>
<add name="CustomRoleProvider" type="Login1.Code.CustomRoleProvider"/>
</providers>
</roleManager>

Change Password Issue in AspNet MembershipProvider

I am using AspNet Membership Provider in MVC 3.
I am facing issue in change password.
I have two functionality in my project
Forgot password : ask security question and based on security answer change password.
Admin change password: a admin can change password of any user without knowing old password or security answer.
Now the issue is that for functionality # 1, i have to make changes in web config for making requiresQuestionAndAnswer="true" for change password so that i can change password only if security answer is valid.
<membership>
<providers>
<clear />
<add name="AspNetSqlMembershipProvider" type="System.Web.Security.SqlMembershipProvider" connectionStringName="ApplicationServices" enablePasswordRetrieval="false" enablePasswordReset="true" requiresQuestionAndAnswer="true" requiresUniqueEmail="false" maxInvalidPasswordAttempts="5" minRequiredPasswordLength="6" minRequiredNonalphanumericCharacters="0" passwordAttemptWindow="10" applicationName="/" />
</providers>
</membership>
and i am using below code for changing password in forgot password:
string resetPassword = res.ResetPassword(model.PasswordAnswer);
MembershipService.ChangePassword(model.Username, newPassword, model.NewPassword)
now for situation # 2, where for admin i wants facility to change password of any user without knowing old password or security answer. which is only possible (as i know) by making requiresQuestionAndAnswer="false" .
Note:I am using separate MVC AREA for admin part, so may be a another web config can do some magic.
please suggest how can i have have both the features (reset password with security answer and without security answer) together in single application.
Thanks a lot
Finally got the answer:
In web config i set the requiresQuestionAndAnswer="true" so this resolves the issue#1, now for forgot password a security answer is required.
and for issue#2 where i want the facility for admin to change password of any user without knowing old password or security answer. I have used Reflection for it to change the value of private variable _RequiresQuestionAndAnswer to false then reset the password and then again set its value to true:
var _requiresQA = Membership.Provider.GetType().GetField("_RequiresQuestionAndAnswer",
System.Reflection.BindingFlags.Instance | System.Reflection.BindingFlags.NonPublic);
//change the value in the private field
_requiresQA.SetValue(Membership.Provider, false);
//do the reset
tempPassword = user.ResetPassword();
//set it's original value
_requiresQA.SetValue(Membership.Provider, true);
I got this solution at : http://djsolid.net/blog/asp.net-membership---change-password-without-asking-the-old-with-question-and-answer

Categories