how to use Membership.ValidateUser using entities connection to DB? - c#

i have a web service call a method to authenticate user
the method is :
public bool getUser(string User, string Pass)
{
return( Membership.ValidateUser(TvId, TvPass));
}
but Membership.ValidateUser need to get connection to db, and I'm using Entity framework , any help?

We have two different connection strings defined, one for EF and one for the Membership provider, even though they're both the same DB.
So in the Web.config we have:
<configuration>
<connectionStrings>
<!-- Used by the EF DbContext -->
<add name="EFConnection" connectionString="metadata=res://*/Model.csdl|res://*/Model.ssdl|res://*/Model.msl;provider=System.Data.SqlClient;provider connection string="Data Source=localhost;Initial Catalog=MyDB;Persist Security Info=False;Trusted_Connection=yes;MultipleActiveResultSets=true;"" providerName="System.Data.EntityClient" />
<!-- Used for membership, see the Web.config entries below -->
<add name="ApplicationServices" connectionString="data source=localhost;initial catalog=MyDB;Persist Security Info=False;Trusted_Connection=yes;MultipleActiveResultSets=true;" providerName="System.Data.SqlClient" />
</connectionStrings>
<system.web>
<membership>
<providers>
<!-- Uses the ApplicationServices connection string defined above to set the connection information for the membership provider -->
<add name="AspNetSqlMembershipProvider" type="System.Web.Security.SqlMembershipProvider" connectionStringName="ApplicationServices" enablePasswordRetrieval="false" enablePasswordReset="true" requiresQuestionAndAnswer="false" requiresUniqueEmail="false" maxInvalidPasswordAttempts="5" minRequiredPasswordLength="6" minRequiredNonalphanumericCharacters="0" passwordAttemptWindow="10" applicationName="ePubDirect" />
</providers>
</membership>
</system.web>
</configuration>
There's a load of other stuff in the Web.config too of course, and your connection strings will likely be very different than my local dev environment, but this is the type of wiring you need for your Membership to just work.
Instead of System.Web.Security.SqlMembershipProvider you may need something more like:
<membership defaultProvider="DefaultMembershipProvider">
<providers>
<add name="DefaultMembershipProvider" type="System.Web.Providers.DefaultMembershipProvider, System.Web.Providers, Version=2.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35" connectionStringName="DefaultConnection" enablePasswordRetrieval="false" enablePasswordReset="true" requiresQuestionAndAnswer="false" requiresUniqueEmail="false" maxInvalidPasswordAttempts="5" minRequiredPasswordLength="6" minRequiredNonalphanumericCharacters="0" passwordAttemptWindow="10" applicationName="/" />
</providers>
</membership>
Or whatever membership provider you're using. Your detailed settings are likely to be different to these too.

It doesn't mean you r using entity framework or Ado.net classes to make the connection with the database. membership provider will work with entity framework as well. you need to define the membership connection string in the Web.config file

Related

ASP.NET Login Not Reading Connection String

This is probably a noob question, I am new to ASP.NET Login controls. The problem is, the login page loads and you enter the username and password. However, it always says "Your login attempt was not successful. Please try again." That prompted me to see if it was even hitting the db. It is not, because this is the connection string as you can see below:
connectionString="Data2121212 Source=20e2127213597;Initial Catalog=ramsl323312sanddb;User Id=ramsl1342anddb42o;Password=r13zzzzzzbs;"
Even with that connection string which is completely invalid it throws no error. So obviously its not even trying to connect. What I can't figure out, is why is not connecting. I was told that the login control would just read the web.config file and pick up the connection string etc. But its not. Can someone please explain to me whats going on?
And yes, the site is using that config file.
<connectionStrings>
<clear/>
<add name="LocalSqlServer" connectionString="Data2121212 Source=20e2127213597;Initial Catalog=ramsl323312sanddb;User Id=ramsl1342anddb42o;Password=r134zAP5bs;" providerName="System.Data.SqlClient"/>
</connectionStrings>
<system.web>
<compilation debug="true" targetFramework="4.0">
<assemblies>
<add assembly="System.Design, Version=4.0.0.0, Culture=neutral, PublicKeyToken=B03F5F7F11D50A3A"/>
<add assembly="System.Web.Extensions.Design, Version=4.0.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35"/>
<add assembly="System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=B77A5C561934E089"/></assemblies></compilation>
<authentication mode="Forms">
<forms name=".ASPXAUTH" loginUrl="~/Login.aspx"/>
</authentication>
<authorization>
<deny users="?"/>
</authorization>
<!-- Validation and decryption keys must exactly match and cannot
be set to "AutoGenerate". The validation and decryption
algorithms must also be the same. -->
<machineKey validationKey="AB5D0FE7450DA6CB8821D213C36EE85BC26FB34259E194B86F2D7240D10B42AE8887A5204B733EF7E860963C0403CA12FBF0892AD50570B4E79D5DC530FD1CFF" decryptionKey="1ED07D110F095B571EB62B0EF4C6D6F4F2DA5596103C233E98C8B6832C23F888" validation="AES" decryption="AES" />
<membership defaultProvider="AspNetSqlMembershipProvider">
<providers>
<clear/>
<add connectionStringName="LocalSQLServer" applicationName="/" enablePasswordRetrieval="true" passwordFormat="Encrypted" enablePasswordReset="true" requiresQuestionAndAnswer="false" requiresUniqueEmail="false" maxInvalidPasswordAttempts="5" minRequiredPasswordLength="6" minRequiredNonalphanumericCharacters="0" passwordAttemptWindow="10" name="AspNetSqlMembershipProvider" type="System.Web.Security.SqlMembershipProvider"/>
</providers>
</membership>
<profile defaultProvider="AspNetSqlProfileProvider">
<providers>
<clear/>
<add connectionStringName="LocalSQLServer" applicationName="/" name="AspNetSqlProfileProvider" type="System.Web.Profile.SqlProfileProvider"/>
</providers>
</profile>
<roleManager enabled="true" defaultProvider="AspNetSqlRoleProvider">
<providers>
<clear/>
<add connectionStringName="LocalSQLServer" applicationName="/" name="AspNetSqlRoleProvider" type="System.Web.Security.SqlRoleProvider"/>
</providers>
</roleManager>
</system.web>
<system.webServer>
<modules runAllManagedModulesForAllRequests="true"/>
</system.webServer>
</configuration>
Try putting the following line in:
So your new connection strings settings should look like this:
<connectionStrings>
<remove name="LocalSqlServer"/>
<add name="LocalSqlServer" connectionString="Data2121212 Source=20e2127213597;Initial Catalog=ramsl323312sanddb;User Id=ramsl1342anddb42o;Password=r13zzzzzzbs;"/>
</connectionStrings>
now for as long as your Database has the ASP.Net database in it with a user account it should work perfectly fine.
I got it! My noob client coded the login control all wrong apparently, because when I used a new one, it worked great!
Also, great tips here for anyone who has an issue like this:
http://www.codeproject.com/Articles/27682/Your-Login-Attempt-was-not-Successful-Please-Try

Connection String C#

public string ConnectionString = string.Empty;
In the line above, if the connection string is assigned as string.empty, then how will the connection string get its value? I dont understand what this means exactly.
The code am reading through contains the following after the above statement:
public DataSet GetData(SqlCommand cmd)
{
SqlConnection conn = new SqlConnection(this.ConnectionString);
DataSet ds = new DataSet();
try
{
cmd.Connection = conn;
SqlDataAdapter ad = new SqlDataAdapter(cmd);
conn.Open();
ad.Fill(ds);
cmd.Parameters.Clear();
}
catch (Exception ex)
{
throw ex;
}
finally
{
cmd.Parameters.Clear();
conn.Close();
}
return ds;
}
So, here where does the connection string gets it value from
The answer to your question is that if your class has that ConnectionString as a property then the SqlConnection object here cannot connect to anything as its had the value String.Empty passed to it.
It doesn't magically work out the value its just never going to connect to anything, as you do not have a valid connection string. Does this code actually connect? if it does it can't be using String.Empty like you are describing.
To clarify I would expect the connection string to come from a settings object of some sort, either from a .config file or other such mechanism.
In an attempt to help I am guessing you are using ASP.net as below you talk about a post variable. These application types tend to read from a web.config file like below.
Then your connection string variable would be initialized by a piece of code that looked something like this, if there are multiple keys in the connectionString elements (noted by the add element) then you access via the indexer as shown.
ConnectionStringSettings connectionStringSettings = ConfigurationManager.ConnectionStrings["ApplicationServices"];
string connectionString = connectionStringSettings.ConnectionString;
config code follows:
<?xml version="1.0"?>
<!--
For more information on how to configure your ASP.NET application, please visit
http://go.microsoft.com/fwlink/?LinkId=169433
-->
<configuration>
<connectionStrings>
<add name="ApplicationServices"
connectionString="data source=.\SQLEXPRESS;Integrated Security=SSPI;AttachDBFilename=|DataDirectory|\aspnetdb.mdf;User Instance=true"
providerName="System.Data.SqlClient" />
</connectionStrings>
<system.web>
<compilation debug="false" targetFramework="4.0" />
<authentication mode="Forms">
<forms loginUrl="~/Account/Login.aspx" timeout="2880" />
</authentication>
<membership>
<providers>
<clear/>
<add name="AspNetSqlMembershipProvider" type="System.Web.Security.SqlMembershipProvider" connectionStringName="ApplicationServices"
enablePasswordRetrieval="false" enablePasswordReset="true" requiresQuestionAndAnswer="false" requiresUniqueEmail="false"
maxInvalidPasswordAttempts="5" minRequiredPasswordLength="6" minRequiredNonalphanumericCharacters="0" passwordAttemptWindow="10"
applicationName="/" />
</providers>
</membership>
<profile>
<providers>
<clear/>
<add name="AspNetSqlProfileProvider" type="System.Web.Profile.SqlProfileProvider" connectionStringName="ApplicationServices" applicationName="/"/>
</providers>
</profile>
<roleManager enabled="false">
<providers>
<clear/>
<add name="AspNetSqlRoleProvider" type="System.Web.Security.SqlRoleProvider" connectionStringName="ApplicationServices" applicationName="/" />
<add name="AspNetWindowsTokenRoleProvider" type="System.Web.Security.WindowsTokenRoleProvider" applicationName="/" />
</providers>
</roleManager>
</system.web>
<system.webServer>
<modules runAllManagedModulesForAllRequests="true"/>
</system.webServer>
</configuration>
Right click on this.ConnectionString and find all refferences. I'm sure it is being set somewhere in your code befor it gets to public DataSet GetData(SqlCommand cmd)

Microsoft Media Platform + Forms Authentification

Forms Authentication does not work. Auth cookies are not sent to server when SMF attempts to get access to *.ism/Manifest files on a server that requires specific user roles.
What i do:
1. Create new Silverlight Smooth Streaming template with supporting RIA WCF.
2. Configure web.config :
<connectionStrings>
<add name="ApplicationServices" connectionString="Data Source=[SERVER];Initial Catalog=[CATALOG];User ID=[USER];Pwd=[PASSWORD];" providerName="System.Data.SqlClient" />
<system.web>
<authentication mode="Forms">
<forms loginUrl="~/Account/LogOn" timeout="2880" />
</authentication>
<membership>
<providers>
<clear />
<add name="AspNetSqlMembershipProvider" type="System.Web.Security.SqlMembershipProvider" connectionStringName="ApplicationServices" enablePasswordRetrieval="false" enablePasswordReset="true" requiresQuestionAndAnswer="false" requiresUniqueEmail="false" maxInvalidPasswordAttempts="5" minRequiredPasswordLength="6" minRequiredNonalphanumericCharacters="0" passwordAttemptWindow="10" applicationName="/" />
</providers>
</membership>
<profile>
<providers>
<clear />
<add name="AspNetSqlProfileProvider" type="System.Web.Profile.SqlProfileProvider" connectionStringName="ApplicationServices" applicationName="/" />
</providers>
<properties>
<add name="Gender" />
<add name="Birthday" />
<add name="AvatarPath" />
</properties>
</profile>
<roleManager enabled="true">
<providers>
<clear />
<add connectionStringName="ApplicationServices" applicationName="/" name="AspNetSqlRoleProvider" type="System.Web.Security.SqlRoleProvider" />
<add applicationName="/" name="AspNetWindowsTokenRoleProvider" type="System.Web.Security.WindowsTokenRoleProvider" />
</providers>
</roleManager>
Add Authentification Service and correct User class (add 3 props).
On client side add this to app.xaml.cs:
public App()
{
//Default things...
InitializeWebContext();
}
private void InitializeWebContext()
{
WebContext webContext = new WebContext();
var fa = new FormsAuthentication();
var ac = new AuthenticationDomainService1();
fa.DomainContext = ac;
fa.Login(new LoginParameters("user", "password"), (y) =>
{
if (!y.HasError)
{
this.RootVisual = new MainPage();
}
}, null);
webContext.Authentication = fa;
ApplicationLifetimeObjects.Add(webContext);
Resources.Add("WebContext", WebContext.Current);
}
Access is restricted by web.config file in target directory:
<?xml version="1.0" encoding="UTF-8"?>
<configuration>
<system.web>
<authorization>
<allow roles="Role_name" />
<deny users="*" />
</authorization>
</system.web>
</configuration>
User exists in this role.
When I use the default video that's specified in Xaml (Big Bunny) - everything is fine. But when I change mediasource to a path to s restricted zone on my server I get an access error.
On the client side, I get user credentials succesfully.
Fiddler shows next thing:
When I try access to another resctricted methods ([RequiresAuthentication]) on RIA WCF, client send Auth cookies, but when SMFPlayer try access to media source, that cookie wasn`t sent.
What have I missed?
I found some workaround:
If you transfer the stream files into a subdirectory, and restrict access to it (instead of a directory with "ism" files). Manifest will be issued to anonymous users, but the data streams is only for registered (when player try touch data stream it sucessfully attach auth cookies).

The EntitySet name 'xxxxx_dk_dbEntities.Vehicle' could not be found

I use a mssql 2008 server (at my webhotel) and I am trying to save data in it from my code.
I have made this little test code here that gives me this error in topic
Context = new XXX_dk_dbEntities();
var vehicle = new Vehicle { Name = "test" };
Context.AddObject("Units", vehicle);
Context.SaveChanges();
EDIT: Changing Context.AddObject(vehicle.GetType().Name, vehicle); to Context.AddObject("Something", vehicle); gives the same error, so I think it might be my connectionstring or my EF that needs proper setup, anyway I can test that?
Edit 2: Changed it to Units now which makes my error {"The underlying provider failed on Open."} and inspecting that gives me this error {"Login failed for user 'xxxxx_dk'."} so it must be my connectionstring
<add name="xxxxx_dk_dbEntities" connectionString="metadata=res://*/Areas.Units.UnitsModel.csdl|res://*/Areas.Units.UnitsModel.ssdl|res://*/Areas.Units.UnitsModel.msl;provider=System.Data.SqlClient;provider connection string="data source=mssql1.unoeuro.com;initial catalog=xxxxxxx_dk_db;persist security info=True;user id=xxxxxxxx_dk;MultipleActiveResultSets=True;App=EntityFramework"" providerName="System.Data.EntityClient" />
This is the solutionexplore showing my edmx structure
After I found I had to add the remove (For some reason it uses a connectionstring specified in machine.config) and changed the name of my own provider to "AspNetSqlMembershipProvider" I created a new connectionstring for this to use so remove old connectionstring (Wierd!), create a custom memberprovider like
<membership>
<providers>
<add connectionStringName="unoeurotest" enablePasswordRetrieval="false"
enablePasswordReset="true" requiresQuestionAndAnswer="false"
requiresUniqueEmail="false" maxInvalidPasswordAttempts="5" minRequiredPasswordLength="6"
minRequiredNonalphanumericCharacters="0" passwordAttemptWindow="10"
applicationName="/" name="DefaultMembershipProvider" type="System.Web.Providers.DefaultMembershipProvider, System.Web.Providers, Version=1.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35" />
</providers>
</membership>
And then make a connectionstring only for this
<add name="unoeurotest" connectionString="Data Source=mssql1.unoeuro.com;Initial Catalog=xxxxxx_dk_db;User Id=xxxxx_dk;Password=xxxxxx;MultipleActiveResultSets=True;"/>

ASP.NET Membership PasswordLength and other properties

I am going crazy, when I go into the Web Site Administration Tool to create some new users, it always tells me that my password is not 7 characters long.
Error msg:
Password length minimum: 7. Non-alphanumeric characters required: 1.
Here is my web.config, seems like it is not even looked at.
<membership userIsOnlineTimeWindow="20">
<providers>
<remove name="AspNetSqlProvider" />
<add name="AspNetSqlProvider" connectionStringName="LocalSqlServer"
type="System.Web.Security.SqlMembershipProvider"
applicationName="OCIS"
minRequiredPasswordLength="3"/>
</providers>
</membership>
I even went as far to modify the machine.config and after rebooting, still the same result.
Very frustrating.
You guys have any ideas why my web.config files seems to be ignored?
Thank you,
Steve
The AspNetSqlProvider is not the default provider name that is defined in the MembershipSection. Thus, you have to set the default provider name as follows.
<membership defaultProvider="AspNetSqlProvider">
<providers>
<add name="AspNetSqlProvider" ... />
</providers>
</membership>
You probably should never have need to modify machine.config but I understand your frustration.
First, try implementing all properties of the provider in your local config to your specs and see what happens..
<membership>
<providers>
<add
name="AspNetSqlMembershipProvider"
type="System.Web.Security.SqlMembershipProvider, ..."
connectionStringName="LocalSqlServer"
enablePasswordRetrieval="false"
enablePasswordReset="true"
requiresQuestionAndAnswer="true"
applicationName="/"
requiresUniqueEmail="false"
passwordFormat="Hashed"
maxInvalidPasswordAttempts="5"
minRequiredPasswordLength="7"
minRequiredNonalphanumericCharacters="1"
passwordAttemptWindow="10"
passwordStrengthRegularExpression=""
/>
</providers>
</membership>

Categories

Resources