ldap authentication using ActiveDirectyoryMembershipProvider on GC port fails in MVC2 application - asp.net-mvc-2

I am developing an MVC2 application using C# ASP.NET.
In my application I am using ActiveDirectoryMembershipProvider for user authentication. Below is the snippet from my web.config file.
If I use the global catalog port 3268 in my connection string I get the error "LDAP connections on GC port are not supported against Active Directory". I did google on this error message and was unable to find an appropriate solution. Many people have suggested using port 389, some have suggested code changes. But I want to be able to use the GC port to allow users connected to different forests, because it is more cleaner.
Some observations:
The same connection string(with port 3268) is working perfectly for other applications in my company i.
When I change my connection string to point to port 389 it works perfectly i.e people who belong to the local domain are able to log in. However people from another domain cant.
I put breakpoints in my AcconuntModel and AccountController. With connection string pointing to port 3268,Membership.Provider threw "ConfigurationErrorsException".
It would be very helpful if someone can help me resolve this issue.
web.config:
<add name="ADConnectionString" connectionString="LDAP://myADServer.abc.ad:389/DC=abc,DC=ad" />
<membership defaultProvider="MyADMembershipProvider">
<providers>
<clear />
<add connectionStringName="ADConnectionString" maxInvalidPasswordAttempts="1000" connectionUsername="ldapuser#abc.ad" connectionPassword="password" connectionProtection="None" enableSearchMethods="True" name="MyADMembershipProvider" type="System.Web.Security.ActiveDirectoryMembershipProvider,System.Web, Version=2.0.0.0,Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a" />
<add name="MySqlMembershipProvider" type="MySql.Web.Security.MySQLMembershipProvider,MySql.Web,Version=6.5.4.0,Culture=neutral,PublicKeyToken=c5687fc88969c44d" connectionStringName="MySqlMembershipConnection" enablePasswordRetrieval="false" enablePasswordReset="true" requiresQuestionAndAnswer="false" requiresUniqueEmail="true" passwordFormat="Hashed" maxInvalidPasswordAttempts="5" minRequiredPasswordLength="6" minRequiredNonalphanumericCharacters="0" passwordAttemptWindow="10" applicationName="/" autogenerateschema="true" />
</providers>
</membership>
<!-- Added for custom provider -->
<roleManager enabled="true" cacheRolesInCookie="true" defaultProvider="DDMS_Custom_RoleProvider">
<providers>
<clear />
<add applicationName="/" connectionStringName="ddms_dataEntities2" name="DDMS_Custom_RoleProvider" type="DDMS_sourcecode.Utilities.DDMS_Custom_RoleProvider, DDMS_sourcecode" />
<add connectionStringName="ApplicationServices" applicationName="/" autogenerateschema="true" name="MySqlRoleProvider" type="MySql.Web.Security.MySQLRoleProvider,MySql.Web,Version=6.5.4.0,Culture=neutral,PublicKeyToken=c5687fc88969c44d" />
</providers>
</roleManager>

If it is Global Catalog that you need to search, why dont you try it this way
using (DirectoryEntry searchRoot = new DirectoryEntry("GC://DC=yourdomain,DC=com"))
using (DirectorySearcher ds = new DirectorySearcher(searchRoot))
{
ds.Filter = "(sAMAccountName=userID1)";
ds.SearchScope = SearchScope.Subtree;
using (SearchResultCollection src = ds.FindAll())
{
foreach (SearchResult sr in src)
{
uxFred.Content = sr.Path;
}
}
}

Related

EntityFramework connect to Visual Studio SQL Server (localdb)

I am running a local instance of Sql Server through Visual Studio:
It is online and I am able to view the data in the database through the UI.
My App.config file looks like the following:
<?xml version="1.0" encoding="utf-8"?>
<configuration>
<configSections>
<section name="entityFramework" type="System.Data.Entity.Internal.ConfigFile.EntityFrameworkSection, EntityFramework, Version=6.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" requirePermission="false"/>
</configSections>
<connectionStrings>
<add name="EntitiesContext" connectionString="Data Source=(localdb)\MSSQLLocalDB;Initial Catalog=master;Integrated Security=True;Connect Timeout=30;Encrypt=False;TrustServerCertificate=False;ApplicationIntent=ReadWrite;MultiSubnetFailover=False" providerName="System.Data.SqlClient"/>
<add name="DefaultConnection" connectionString="Data Source=(localdb)\MSSQLLocalDB;Initial Catalog=master;Integrated Security=True;Connect Timeout=30;Encrypt=False;TrustServerCertificate=False;ApplicationIntent=ReadWrite;MultiSubnetFailover=False" providerName="System.Data.SqlClient" />
</connectionStrings>
<entityFramework>
<defaultConnectionFactory type="System.Data.Entity.Infrastructure.LocalDbConnectionFactory, EntityFramework">
<parameters>
<parameter value="mssqllocaldb" />
</parameters>
</defaultConnectionFactory>
<providers>
<provider invariantName="System.Data.SqlClient"
type="System.Data.Entity.SqlServer.SqlProviderServices, EntityFramework.SqlServer" />
</providers>
</entityFramework>
<startup><supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.6.1"/></startup>
</configuration>
And my EntitiesContext looks like the following:
Could someone please help with what I am missing as this keeps failing connection with the following:
System.Data.SqlClient.SqlException: 'A network-related or instance-specific error occurred while establishing a connection to SQL Server. The server was not found or was not accessible. Verify that the instance name is correct and that SQL Server is configured to allow remote connections. (provider: Named Pipes Provider, error: 40 - Could not open a connection to SQL Server)'
Inner Exception
Win32Exception: The system cannot find the file specified
The issue is that the connection string you are using is reverting to a named pipe connection, and it's telling you that nothing is listening on that Pipe.
Changing it to "localhost\MSSQLLocalDB;...." should work if your local database is set up for Shared Memory connections.
To check what protocols are enabled on your server you can run MMC.exe then add the plugin for SQL Server Configuration Manager. Under SQL Server Network Configuration it will show whether your SQL Server instance is allowing Named Pipes or TCP/IP. I believe by default SQL Express only enables Shared Memory which is fine for local testing purposes.

EF4 The provider did not return a Provider Manifest Token string

Yes, one more question about Provider manifest token. Unfortunately all previous 22 questions was not useful to solve my problem. I developing simple web application using MVC4 + Code First + Sql Express.
Here is my context descendant:
public class MCQContext : DbContext
{
public MCQContext()
: base("name=ApplicationConnection")
{
}
...............
}
And here - part of web.config related to the problem:
<configuration>
<configSections>
<section name="entityFramework"
type="System.Data.Entity.Internal.ConfigFile.EntityFrameworkSection, EntityFramework, Version=4.4.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089"
requirePermission="false" />
</configSections>
<connectionStrings>
<add name="ApplicationConnection"
connectionString="Data Source=.\SQLEXPRESS;Integrated Security=SSPI;AttachDBFilename=|DataDirectory|aspnetdb.mdf;User Instance=true"
providerName="System.Data.SqlClient" />
</connectionStrings>
<entityFramework>
<defaultConnectionFactory type="System.Data.Entity.Infrastructure.SqlConnectionFactory, EntityFramework">
<parameters>
<parameter value="name=ApplicationConnection" />
</parameters>
</defaultConnectionFactory>
</entityFramework>
So, as you can see, correct connection string passed to base of context class (I got the same error if I rename connection string to "MCQContext" and do not pass anything to parent context class).
I have no idea how to fix it. This behavior reproduced if I creating absolutely empty MVC4 application, remove all packages (I prefer manually specify required assemblies and do not use NuGet) and fix references (including reference to sqlserver express).
The problem with your connection string here is:
<add name="TrempimModel"
connectionString="data source=.\SQLEXPRESS;Integrated Security=SSPI;
AttachDBFilename=|DataDirectory|aspnetdb.sdf;
User Instance=true"
providerName="System.Data.SqlClient" />
You're basically defining what "server" you're connecting to - but you're not saying what database inside the file to connect to. Also - the file extension for SQL Server Express database files is .mdf (not .sdf - that's SQL Server Compact Edition) - you need to take that into account, too! (was a typo, according to comment by OP).
You need to define an extra database=.... (or Initial Catalog=.....) in your connection string:
<add name="TrempimModel"
connectionString="data source=.\SQLEXPRESS;Integrated Security=SSPI;
database=YourDatabaseName;
AttachDBFilename=|DataDirectory|aspnetdb.mdf;
User Instance=true"
providerName="System.Data.SqlClient" />
Then it should work just fine.

Schema specified is not valid Membership.CreateUser

I've been tasked with migrating from our old half-baked user store (using encrypted passwords) to the default MS membership/role providers. I've done this in other projects no problem.
In this case, I have created the necessary tables using code-first with the 'new' .NET universal providers. I am simply trying to insert new records into the Users table, and have run into a wall.
I have a simple edmx with the 6 tables created by the membership provider. I have set up my web.config to point to the necessary cxn string & membership/role providers (code below).
Web.Config:
<connectionStrings>
<add name="Test" connectionString="metadata=res://*/Entities.Test.csdl|res://*/Entities.Test.ssdl|res://*/Entities.Test.msl;provider=System.Data.SqlClient;provider connection string="data source=[OurServer];initial catalog=[OurDb];integrated security=True;MultipleActiveResultSets=True;App=EntityFramework"" providerName="System.Data.EntityClient" />
</connectionStrings>
<authentication mode="Forms">
<forms loginUrl="~/Account/Login" timeout="2880" />
</authentication>
<membership defaultProvider="DefaultMembershipProvider">
<providers>
<add name="DefaultMembershipProvider" type="System.Web.Providers.DefaultMembershipProvider" connectionStringName="Test" enablePasswordRetrieval="false" enablePasswordReset="true" requiresQuestionAndAnswer="false" requiresUniqueEmail="false" maxInvalidPasswordAttempts="5" minRequiredPasswordLength="6" minRequiredNonalphanumericCharacters="0" passwordAttemptWindow="10" applicationName="/" />
</providers>
</membership>
<roleManager enabled="true" defaultProvider="DefaultRoleProvider">
<providers>
<add connectionStringName="Test" applicationName="/" name="DefaultRoleProvider" type="System.Web.Providers.DefaultRoleProvider" />
</providers>
</roleManager>
Here is my "update passwords" function:
System.Web.Security.MembershipCreateStatus status = new System.Web.Security.MembershipCreateStatus();
//Get list of existing users, containing Username & encrypted PW
List<UserMigration.Models.Users> usersList = UserMigration.Models.Users.GetUsers();
foreach (var user in usersList)
{
string password = "";
//We have two encryption methods (bogus I know), so I attempt to decrypt with one, then another, using existing utility functions.
if (!EncryptDecrypt.TryDecryptTripleDES(user.Password, out password))
{
EncryptDecrypt.TryDecrypt(user.Password, out password);
}
//if we got a password, lets party
if (!string.IsNullOrEmpty(password))
{
System.Web.Security.Membership.CreateUser(user.Username, password,string.Empty,null,null,true,out status);
}
}
I'm getting an error on the CreateUser call, and I can't for the life of me figure out why. I haven't modified the Entities in any way. This should be dirt simple. The error is:
Schema specified is not valid. Errors:
The relationship 'TestModel.MembershipEntity_Application' was not loaded because the type 'TestModel.Membership' is not available.
The relationship 'TestModel.RoleEntity_Application' was not loaded because the type 'TestModel.Role' is not available.
The relationship 'TestModel.User_Application' was not loaded because the type 'TestModel.User' is not available.
The following information may be useful in resolving the previous error:
The required property 'Roles' does not exist on the type 'System.Web.Providers.Entities.User'.

Azure Diagnostics: Trace messages don't work in VS2012 default template

I'm unable to get Azure Diagnostics to spit out any of my Trace messages - even in the near-as-is VS2012 project template. Here is what I did:
In an empty VS2012, created a new Cloud project (called it "Azure.Diag")
In the wizards next step, added the default template for "WCF Service Web Role" (called it "WCFService.WebRole")
Editted Web.Config to enable Diagnostics (details below)
Editted WebRole.cs to spit a Diagnostic Trace message (details below)
Ran it locally in Azure Emulator (ServiceConfiguration.Local.cscfg: Diagnostics.ConnectionString is "UseDevelopmentStorage=true")
Look at C:\Users\<Username>\AppData\Local\dftmp\Resources\<Instance GUID>\directory\WCFService.WebRole.svclog => see nothing!
There is also nothing in the Local Storage Blog either (not surprising given the folder before move-to-blob is empty)
How can I get this working? I'm trying to avoid my own handwritten .txt logs to leverage the in built trace listener framework (and parsing tools).
WebRole.cs
using System.Diagnostics;
namespace WCFService.WebRole
{
public class WebRole : RoleEntryPoint
{
public override bool OnStart()
{
// To enable the AzureLocalStorageTraceListner, uncomment relevent section in the web.config
DiagnosticMonitorConfiguration diagnosticConfig = DiagnosticMonitor.GetDefaultInitialConfiguration();
diagnosticConfig.Directories.ScheduledTransferPeriod = TimeSpan.FromMinutes(1);
diagnosticConfig.Directories.DataSources.Add(AzureLocalStorageTraceListener.GetLogDirectory());
string message = "Houston, tracing is broken!";
Trace.TraceError(message);
Trace.TraceInformation(message);
Trace.TraceWarning(message);
Trace.WriteLine(message);
return base.OnStart();
}
}
}
Web.Config:
I used the standard template one but uncommented the top portion (had to merge the two system.diagnostic portions to avoid HTTP 500)
<system.diagnostics>
<sharedListeners>
<add name="AzureLocalStorage" type="WCFService.WebRole.AzureLocalStorageTraceListener, WCFService.WebRole" />
</sharedListeners>
<!--<sources>
<source name="System.ServiceModel" switchValue="Verbose, ActivityTracing">
<listeners>
<add name="AzureLocalStorage"/>
</listeners>
</source>
<source name="System.ServiceModel.MessageLogging" switchValue="Verbose">
<listeners>
<add name="AzureLocalStorage"/>
</listeners>
</source>
</sources>-->
<trace autoflush="true">
<listeners>
<add type="Microsoft.WindowsAzure.Diagnostics.DiagnosticMonitorTraceListener, Microsoft.WindowsAzure.Diagnostics, Version=1.7.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35"
name="AzureDiagnostics">
<filter type="" />
</add>
</listeners>
</trace>
</system.diagnostics>
<system.web>
<compilation debug="true" targetFramework="4.0" />
</system.web>

.net site all pages do a 302 redirect with AspxAutoDetectCookieSupport

First let me say that I did see this article:
How to remove AspxAutoDetectCookieSupport
However it seems like it fixes the url issue, but not the 302 AspxAutoDetectCookieSupport issue.
I've also read just about every other article on the web about this issue.
I could really use some help here.
This is my web.config
<sessionState mode="InProc" cookieless="false" timeout="6600" />
<membership defaultProvider="MySqlMembershipProvider">
<providers>
<clear />
<add connectionStringName="SimpleTickConnection" applicationName="TheaterSales" enablePasswordRetrieval="false" enablePasswordReset="true" requiresQuestionAndAnswer="false" requiresUniqueEmail="false" passwordFormat="Hashed" maxInvalidPasswordAttempts="15" minRequiredPasswordLength="7" minRequiredNonalphanumericCharacters="0" passwordAttemptWindow="10" passwordStrengthRegularExpression="" name="MySqlMembershipProvider" type="System.Web.Security.SqlMembershipProvider, System.Web, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a" />
</providers>
</membership>
<anonymousIdentification enabled="true" cookieless="AutoDetect" cookieProtection="All" cookieRequireSSL="false" cookieSlidingExpiration="true" />
To replicate the issue:
http://web-sniffer.net/
and use your url
alt text http://img28.imageshack.us/img28/8615/issue.gif
Ok, I researched on: anonymousIdentification
I removed
cookieless="AutoDetect"
And now the object moved error went away