Authentication on one site using the ASP.NET membership of another - asp.net-mvc

We have one site that uses ASP.NET Membership for its user accounts. Let's say this site is at www.domain.com.
We have another site, let's say at www.domain.com/site2, which already connects to the database of site #1 for other reasons. We'd like to implement a username/password login to site #2, and would like to use the existing login credentials for site #1, as site #1 is where they apply for permission to access various systems, etc.
I'm not trying to create a SSO kind of solution, where signing into one site signs you in to the other, which is what other questions have been about.
I would like them to be able to enter their username and password that they have on site #1, enter it on site #2 and it auths them to site #2.
Is this possible?
Web.config of site #1:
<machineKey decryptionKey="AutoGenerate" validation="SHA1" validationKey="AutoGenerate" />
<membership>
<providers>
<clear />
<add name="AspNetSqlMembershipProvider"
type="System.Web.Security.SqlMembershipProvider"
connectionStringName="VTDB"
enablePasswordRetrieval="false"
enablePasswordReset="true"
requiresQuestionAndAnswer="false"
requiresUniqueEmail="true"
maxInvalidPasswordAttempts="5"
minRequiredPasswordLength="8"
minRequiredNonalphanumericCharacters="0"
passwordAttemptWindow="10"
applicationName="/" />
</providers>
</membership>
<profile>
<providers>
<clear />
<add name="AspNetSqlProfileProvider"
type="System.Web.Profile.SqlProfileProvider"
connectionStringName="VTDB"
applicationName="/" />
</providers>
</profile>
<roleManager enabled="true">
<providers>
<clear />
<add connectionStringName="VTDB"
name="AspNetSqlRoleProvider"
applicationName="/"
type="System.Web.Security.SqlRoleProvider" />
</providers>
</roleManager>
....
Web.config of site #2:
<membership defaultProvider="AspNetSqlMembershipProvider">
<providers>
<clear />
<add name="AspNetSqlMembershipProvider"
type="System.Web.Security.SqlMembershipProvider"
connectionStringName="VTConnString" />
</providers>
</membership>
<machineKey decryptionKey="AutoGenerate" validation="SHA1" validationKey="AutoGenerate" />
Where VTConnString points to site #1's database.
But when I call Membership.ValidateUser(userName, password) in site #2, it always returns false.

I figured out the issue:
I was missing applicationName="/" in site #2's web.config. Now that the applicationNames are set the same, it works correctly.

Related

Sharing authentication cookie between DNN Site and ASP.NET Site

I have a DNN site on example.com and an MVC site on subdomain.example.com. I've set up MembershipProvider and a RoleProvider in according to this article: SharePoint-Forms-Based-Authentication-Using-DotNet. Now I want to share auth cookie between two sites. I've set up domain keys in both web.config files like domain=".example.com". Fiddler says the same cookie is used when requesting to any of the sites. And there's a following effect: When I log in to one of the sites, I'm being logged off from another. What could I missed?
Below is a part of the web.config of the MVC site:
<machineKey
validationKey="DEE8F9D31F46D663FA0BCF9A6A9701B0796777C5"
decryptionKey="E75FBCF55F6BB0B2A352036B965725FD739B2EB21B790659"
decryption="3DES"
validation="SHA1" />
<authentication mode="Forms">
<forms
name=".DOTNETNUKE"
protection="All"
timeout="60"
cookieless="UseCookies"
loginUrl="~/Account/Login"
domain=".example.com"
path="/" />
</authentication>
<httpCookies httpOnlyCookies="true" requireSSL="false" domain=".example.com" />
<!-- Configure the Sql Membership Provider -->
<membership defaultProvider="SqlMembershipProvider" userIsOnlineTimeWindow="15">
<providers>
<clear />
<add
name="SqlMembershipProvider"
type="System.Web.Security.SqlMembershipProvider"
connectionStringName="DnnSqlServer"
enablePasswordRetrieval="false"
enablePasswordReset="true"
requiresQuestionAndAnswer="false"
minRequiredPasswordLength="7"
minRequiredNonalphanumericCharacters="0"
requiresUniqueEmail="false"
passwordFormat="Hashed"
applicationName="DotNetNuke" />
</providers>
</membership>
<!-- Configure the Sql Role Provider -->
<roleManager enabled="true" defaultProvider="SqlRoleProvider">
<providers>
<clear/>
<add
name="SqlRoleProvider"
connectionStringName="DnnSqlServer"
applicationName="DotNetNuke"
type="System.Web.Security.SqlRoleProvider,System.Web,
Version=2.0.0.0,Culture=neutral,
PublicKeyToken=b03f5f7f11d50a3a" />
</providers>
</roleManager>
When you see this behavior it is typically from the encryption MachineKey values being different between the different applications. When the other application attempts to read the cookie, it cannot decrypt it and then deletes it, allowing you to login.
I would validate those items in the web.config. (They are not too far down from the node.

Error Unable connect to SQL Server when add <roleManager enabled="true">

When I add
<roleManager enabled="true"></roleManager>
to my web.config, I get an error
Unable to connect to SQL Server database
occurs on this line of code:
System.Web.Security.Roles.AddUserToRole(m.UserName, "admin");
I added this to the web.config and it solved my problem:
<system.web>
<roleManager enabled="true" defaultProvider="CustomizedRoleProvider">
<providers>
<add name="CustomizedRoleProvider" type="System.Web.Security.SqlRoleProvider" connectionStringName="DefaultConnection" />
</providers>
</roleManager>
</system.web>
I had the exact same error when I had enabled believing I was enabling ASP.NET Identity 2. They are not the same! The enabled an old version of identity management which uses a different table structure to ASP.NET Identity 2 (which doesn't need "enabling" by the way - it's just there).
check the connection String.
If you are intentionally using the old role-manager and still getting the error you might be looking at the default localdb instead of your database, in which case you can modify to point at any connection string you want:
<roleManager
enabled="true"
cacheRolesInCookie="true"
defaultProvider="OurSqlRoleProvider"
>
<providers>
<add
connectionStringName="DefaultConnection"
applicationName="/"
name="OurSqlRoleProvider"
type="System.Web.Security.SqlRoleProvider" />
</providers>
</roleManager>
If you are are after using ASP.NET Identity 2, here's an article on it:
http://johnatten.com/2014/04/20/asp-net-mvc-and-identity-2-0-understanding-the-basics/

ASP.Net MVC app logout not completely logging out

This app is running in an environment where some users are still using IE7 if that makes any difference. What we're seeing is occasionally after someone logs out and someone else logs in they still get residue from the previous person where it may show that persons profile. Any suggestions would be greatly appreciated.
I'm using the following as the logout method in my asp.net mvc app
public ActionResult LogOff()
{
System.Web.HttpContext.Current.Response.Cookies.Clear();
FormsService.SignOut();
Session["User"] = null;
Session.Clear();
Session.Abandon();
Session.RemoveAll();
return Redirect("/");
}
The app is using sessions saved into the database because it's running on two different web servers.
Here's some settings from the web.config
<sessionState sqlConnectionString="LiveDB" />
<authentication mode="Forms">
<forms loginUrl="~/Account/LogOn" timeout="2880" />
</authentication>
<membership>
<providers>
<clear />
<add name="AspNetSqlMembershipProvider" type="System.Web.Security.SqlMembershipProvider" connectionStringName="LiveDB" enablePasswordRetrieval="false" enablePasswordReset="true" requiresQuestionAndAnswer="false" requiresUniqueEmail="false" maxInvalidPasswordAttempts="50" minRequiredPasswordLength="6" minRequiredNonalphanumericCharacters="0" passwordAttemptWindow="10" applicationName="/" />
</providers>
</membership>
<profile>
<providers>
<clear />
<add name="AspNetSqlProfileProvider" type="System.Web.Profile.SqlProfileProvider" connectionStringName="LiveDB" applicationName="/" />
</providers>
</profile>
<roleManager enabled="true">
<providers>
<clear />
<add connectionStringName="LiveDB" applicationName="/" name="AspNetSqlRoleProvider" type="System.Web.Security.SqlRoleProvider" />
<add applicationName="/" name="AspNetWindowsTokenRoleProvider" type="System.Web.Security.WindowsTokenRoleProvider" />
</providers>
</roleManager>
If you use FormAuthentication to login like this -
FormsAuthentication.SetAuthCookie("username", false);
then Logout is supposed to be
FormsAuthentication.SignOut();
If you still have issue, you can force cookie to expire like this.
Membership and Session providers works separetly. Two members may use one session. That is not a rule, but it can be.
I'm not sure but I have a suggetion about your problem. Session has property IsNewSession. Microsofts says, that it "Gets a value indicating whether the session was created with the current request."
So, you may try to check if the Session of login user is new, because as he may share session with old user, and, may be, this is a reason, why one sees others profile.

Setting up SimpleMembership in MVC4

I am reading that in MVC4 to set up simple membership I should do this step:
In the AppSettings include a line:
<add key="enableSimpleMembership" value="true" />
However when I look at the samples generated from the templates they only have:
<appSettings>
<add key="webpages:Version" value="2.0.0.0" />
<add key="webpages:Enabled" value="false" />
<add key="PreserveLoginUrl" value="true" />
<add key="ClientValidationEnabled" value="true" />
<add key="UnobtrusiveJavaScriptEnabled" value="true" />
</appSettings>
So why do I keep reading it's necessary to set the enableSimpleMembership key?
By default the SimpleMembershipProvider is enabled when you create a new ASP.NET MVC 4 application. But some hosting providers might disable it by overriding this setting in a higher level web.config.
Quote from an article about SimpleMembership:
If you see an error that tells you that a property must be an
instance of ExtendedMembershipProvider, the site might not be
configured to use the ASP.NET Web Pages membership system
(SimpleMembership). This can sometimes occur if a hosting provider's
server is configured differently than your local server. To fix this,
add the following element to the site's Web.config file:
<appSettings>
<add key="enableSimpleMembership" value="true" />
</appSettings>
This setting is used by the WebMatrix.WebData.PreApplicationStartCode method which executes automatically when your site runs and will use the value of this setting to enable the simple membership provider.
Actually configuring the SimpleMembershipProvider explicitly is what I would recommend you:
<membership defaultProvider="SimpleMembershipProvider">
<providers>
<clear/>
<add name="SimpleMembershipProvider"
type="WebMatrix.WebData.SimpleMembershipProvider, WebMatrix.WebData"/>
</providers>
</membership>
<roleManager enabled="true" defaultProvider="SimpleRoleProvider">
<providers>
<clear/>
<add name="SimpleRoleProvider" type="WebMatrix.WebData.SimpleRoleProvider, WebMatrix.WebData"/>
</providers>
</roleManager>
Now, there's no room for confusion anymore. Both the membership and role providers are configured explicitly.

ERROR: Key cannot be null. Parameter name: key

SOLVED:the method public override string[] GetRolesForUser(string username) was erroneously returning null as the first item of the array.All good now.
I am trying to implement custom role and membership providers for my application but not having luck with role provider. In one of my controller's method, if I have [Authorize] directive it works fine but when I want to have role based authorization by adding [Authorize(Roles = "Admin")] it gives an error saying 'Key cannot be null. Parameter name: key' .
I think there is something wrong with the entires in web.config file but cannot find what it is. The modified entries in web.config file look like
<membership defaultProvider="CustomMembershipProvider">
<providers>
<clear />
<add name="CustomMembershipProvider" type="eLibrary.Models.CustomMembershipProvider" connectionStringName="AppDb" enablePasswordRetrieval="false" enablePasswordReset="true" requiresQuestionAndAnswer="false" requiresUniqueEmail="false" maxInvalidPasswordAttempts="5" minRequiredPasswordLength="6" minRequiredNonalphanumericCharacters="0" passwordAttemptWindow="10" applicationName="/" />
</providers>
</membership>
<roleManager defaultProvider="CustomRoleProvider" enabled="true" cacheRolesInCookie="true" >
<providers>
<clear/>
<add name="CustomRoleProvider" type="eLibrary.Models.CustomRoleProvider" />
</providers>
</roleManager>
It would be great if anyone can throw some lights on.
SOLVED:the method public override string[] GetRolesForUser(string username) was erroneously returning null as the first item of the array.All good now.

Resources