Unable to establish secure connection with the server , when using LDAP - asp.net

I am working on an asp.net mvc web application, and I have added the following provider to my asp.net web.config:
<system.web>
<membership>
<providers>
<add name="TestDomain1ADMembershipProvider" type="System.Web.Security.ActiveDirectoryMembershipProvider,System.Web, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a,Version=4.0.0.0" connectionStringName="TestDomain1ConnectionString" connectionUsername="ad-domainA.intra\it360ad.user" connectionPassword="$$$$$3" />
</providers>
</membership>
&
<add name="TestDomain1ConnectionString"
connectionString="LDAP://10.211.12.30.ad-domainA.intra/CN=Users,DC=ad-domainA,DC=intra" />
but when the users try to access the application and they enter username and password , this will raise the following exception :
Unable to establish secure connection with the server
So what might be the problem? and also is it right to include my server IP address inside the connection string as I am doing ?
EDIT
I changed my setting to be:
<system.web>
<trust level="Full" originUrl="" />
<membership>
<providers>
<add name="TestDomain1ADMembershipProvider" type="System.Web.Security.ActiveDirectoryMembershipProvider,System.Web, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a,Version=4.0.0.0" connectionStringName="TestDomain1ConnectionString" connectionUsername="it360ad.user" connectionPassword="$$$$$" />
</providers>
</membership>
&
<add name="TestDomain1ConnectionString"
connectionString="LDAP://ad-domainA.intra/OU=TM,DC=ad-doaminA,DC=intra" />
but currently the following check
if(domainProvider.ValidateUser(model.UserName, model.Password)
inside the Account controller action method will return
The user name or password provided is incorrect
[HttpPost]
[AllowAnonymous]
[ValidateAntiForgeryToken]
public ActionResult Login(LoginModel model, string returnUrl)
{
MembershipProvider domainProvider;
domainProvider = Membership.Providers["TestDomain1ADMembershipProvider"];
// Validate the user with the membership system.
if (domainProvider.ValidateUser(model.UserName, model.Password))
{
//code goes here
}
else
{
ModelState.AddModelError("", "The user name or password provided is incorrect.");
return View(model);
}
Can you advice why the validation will always fail ?
Thanks

Try using this connectionString="LDAP://10.211.12.30:389 />. I had the same problem and I found that I had to remove anything else after :389in the connection string.
I dont know why that is but it worked for me..... Hope this helps

Related

ASP.NET MVC Multiple Custom AuthorizeAttribute

I am developing a Web Application using ASP.NET MVC 4 and I create a couple of custom MembershipProvider and RoleProvider like bellow:
# Custom MembershipProviders
<membership defaultProvider="myMembershipProvider">
<providers>
<clear />
<add name="myMembershipProvider" type="WebApp1.Business.Auth.MyMembershipProvider" />
<add name="adminMembershipProvider" type="WebApp1.Business.Auth.AdminMembershipProvider" />
</providers>
</membership>
# Custom RoleProviders
<roleManager enabled="true" defaultProvider="MyRoleProvider">
<providers>
<clear />
<add name="MyRoleProvider" type="WebApp1.Business.Auth.MyRoleProvider" />
<add name="AdminRoleProvider" type="WebApp1.Business.Auth.AdminRoleProvider" />
</providers>
</roleManager>
My intention is to create a custom AuthorizeAttribute called Logon that will use the "myMembershipProvider" and "MyRoleProvider"; and create another one called AdminLogon that will use "adminMembershipProvider" and "AdminRoleProvider".
The reason I am creating two custom AuthorizeAttributes is because I want to separate some methods that get the permissons of each role.
The question is, how can I set dynamically the default MembershipProvider and RoleProviders
inside both custom AuthorizeAttribute.
For example:
// Set the default MembershipProvider as adminMembershipProvider
// Set the default RoleProvidersas as AdminRoleProvider
[AdminLogon(Roles = "Administrador")]
public ActionResult Funcionarios()
{
return View();
}
// Set the default MembershipProvider as myMembershipProvider
// Set the default RoleProvidersas as MyRoleProvider
[Logon(Roles = "Administrador")]
public ActionResult Funcionarios()
{
return View();
}

How to implement Google reCaptcha in an MVC3 application?

Can anyone explain how to have reCaptcha functionality like stackoverflow in my MVC3 application.
And how can you customize that?
I use the Google ReCaptcha and it works very well and is very simple to implement.
Note that if you are using Https be sure you have the current version of the dll (1.0.5.0 at this time)
You need to create an account on the Google Recaptcha site and get a set of public and private keys. Add the keys to your web project main web.config file:
<appSettings>
<add key="webpages:Version" value="1.0.0.0"/>
<add key="ClientValidationEnabled" value="true"/>
<add key="UnobtrusiveJavaScriptEnabled" value="true"/>
<add key="ReCaptchaPrivateKey" value="put your private key value here" />
<add key="ReCaptchaPublicKey" value="put your public key value here" />
</appSettings>
Now use NuGet and install the reCAPTCHA plugin for .NET
Then, go to your web.config file inside of your VIEWS folder. Add this line:
<namespaces>
<add namespace="System.Web.Mvc" />
<add namespace="System.Web.Mvc.Ajax" />
<add namespace="System.Web.Mvc.Html" />
<add namespace="System.Web.Routing" />
<add namespace="Recaptcha"/>
</namespaces>
Then, in your view that you want to show the captcha, add the using statement at the top of your file
#using Recaptcha;
then add this to your view:
<div class="editor-label">
Are you a human?
</div>
<div class="editor-field">
#Html.Raw(Html.GenerateCaptcha("captcha", "clean"))
#Html.ValidationMessage("captcha")
</div>
In your controller action you will need to modify the signature to accept the captcha results:
[HttpPost]
[RecaptchaControlMvc.CaptchaValidator]
public ActionResult ForgotPassword(CheckUsernameViewModel model, bool captchaValid, string captchaErrorMessage) {
if (!Membership.EnablePasswordReset)
throw new Exception("Password reset is not allowed\r\n");
if(ModelState.IsValid) {
if(captchaValid) {
return RedirectToAction("AnswerSecurityQuestion", new { username = model.Username });
}
ModelState.AddModelError("", captchaErrorMessage);
}
return View(model);
}
Following those steps have allowed me to implement captcha on several pages and it works smoothly. Note that the parameter names on the controller action MUST BE NAMED CORRECTLY:
bool captchaValid, string captchaErrorMessage
If you changed these parameter names you WILL get an error at runtime when your form posts back to the controller action.
I would recommend using a Honeypot Captcha. The experience for your users is MUCH better. There is one fore ASP.NET MVC here http://nuget.org/packages/SimpleHoneypot.MVC
PM> Install-Package SimpleHoneypot.MVC4
There is a WiKi on how to get it up here: https://github.com/webadvanced/Honeypot-MVC/wiki
Just start out with the Getting Started section.
You can read more about the general idea of a Honeypot Captcha here: http://haacked.com/archive/2007/09/11/honeypot-captcha.aspx

MVC - Users must reauthenticate on IIS Recycle

I need an app pool recycle to be completely transparent to the users of my web app.
Currently, upon an IIS 7 App Pool recycle all users logged into my web app are kicked out and are required to log back in (Context.User.Identity.IsAuthenticated is set to false). I employ SQL State Server, I use forms authentication and both are configured to use cookies. I was under the impression that .NET and/or IIS handles authentication of cookies.
However, every time the app pool is recycled Context.User.Identity.IsAuthenticated is set to false (and I've no idea where this occurs) my users are kicked out and are required to log back in. I can see that the session id remains the same throughout logins, I can also view this session information in the database/state server.
I can't tell if this is a session or a cookie problem.
Please Help!
Logon method:
public ActionResult LogOn(string userName, string password, bool rememberMe, string returnUrl)
{
if (!ValidateLogOn(userName, password))
{
return View();
}
FormsAuth.SignIn(userName, true); // uses FormsAuthentication.SetAuthCookie(username, true);
Session["userName"] = userName;
if (!String.IsNullOrEmpty(returnUrl))
{
return Redirect(returnUrl);
}
else
{
return RedirectToAction("Index", "Home");
}
}
Custom Controller Attribute:
public class CookieAuthorizeAttribute : ActionFilterAttribute
{
public override void OnActionExecuting(ActionExecutingContext filterContext)
{
HttpContext lvContext = HttpContext.Current;
if (!lvContext.User.Identity.IsAuthenticated)
{
lvContext.Response.Redirect("~/Account/Logon");
}
else
{
FormsIdentity identity = (FormsIdentity)HttpContext.Current.User.Identity;
FormsAuthentication.RenewTicketIfOld(identity.Ticket);
}
base.OnActionExecuting(filterContext);
}
}
WebConfig:
<authentication mode="Forms">
<forms cookieless="UseCookies" loginUrl="~/Account/LogOn" slidingExpiration="true" name=".ASPXAUTH" requireSSL="false" timeout="2880" />
</authentication>
<modules runAllManagedModulesForAllRequests="true">
<remove name="ScriptModule" />
<remove name="UrlRoutingModule" />
<remove name="Session" />
<remove name="FormsAuthentication" />
<add name="ScriptModule" preCondition="managedHandler" type="System.Web.Handlers.ScriptModule, System.Web.Extensions, Version=3.5.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35" />
<add name="UrlRoutingModule" type="System.Web.Routing.UrlRoutingModule, System.Web.Routing, Version=3.5.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35" />
<add name="NHibernateMvcSessionModule" type="EpnNHibernateBase.NHibernateMvcSessionModule, EpnNHibernateBase" />
<add name="Session" type="System.Web.SessionState.SessionStateModule" />
<add name="FormsAuthentication" type="System.Web.Security.FormsAuthenticationModule" />
</modules>
I was able to find a solution on my own. The problem was not with how authentication was handled programmatically or how I was authenticating users. The problem was with how I had configured the authentication in IIS/web.config.
I carefully followed the steps in the links listed below:
Configuring Forms Authentication (IIS 7) (Branching out on every related section)
Configuring Machine Keys in IIS 7 <-- This one in particular
After having followed those steps closely I was able to correctly generate a machine key.
This machine key is as follows (with a fabricated key):
<machineKey decryptionKey="ASDF3WS545AS5D4F8254A12DAFA5SDF7,IsolateApps" validation="3DES" validationKey="A65A6S5DF46ASD4F89WEF6SAD2F4A68EF4AW65F4D3A2F4AS6DF89A98D4F6A5SD4F6A5SDF46ASD8F4A6S5DF46AS5D4F6AS5DF49AS8DF46AS5D4F6AS5DF46SAD5F,IsolateApps" />
Additionally, httpModules and system.webServer:modules sections in the web.config required the addition of the following modules:
<remove name="Session" />
<remove name="FormsAuthentication" />
<add name="Session" type="System.Web.SessionState.SessionStateModule" />
<add name="FormsAuthentication" type="System.Web.Security.FormsAuthenticationModule" />
Summary: From what I gather, cookies were being created and encrypted, but because there was no machine key I was unable to unencrypt the cookie, thus causing the need to reauthenticate.
have you tried storing the sessions in a database so they are persistent even if the process is recycled?
see here for howto
Reading your post closely, it looks like the real issue is that users are not logged back in automatically. This is handled by cookies assuming you are using forms authentication.
Once a user is logged in, their session state will be restored if you are using SQL to persist it.
To debug cookies, you can use Fiddler or other cookie sniffers.
Posting your web.config would be helpful as well.

Default SqlRoleProvider in backend code

How do I access the default SqlProvider in a DAL? I've only ever done this before from webforms.
With the following
using System.Web.Security;
....
SqlRoleProvider roleProvider = new SqlRoleProvider();
string[] roles = roleProvider.GetAllRoles(); //for example to get all role names
EDIT
To configure your application to use the SqlRoleProvider you'll need to add the following under the <system.web> section of your web.config file.
<roleManager enabled="true" defaultProvider="SqlRoleManager">
<providers>
<add name="SqlRoleManager"
type="System.Web.Security.SqlRoleProvider"
connectionStringName="MyConnectionStringName" //change this to the name of your connection string
applicationName="MyApplication" />
</providers>
</roleManager>

How to manually verify a user against the ASP.NET memberhip database?

I would like to know how I can verify a user's credential against an existing asp.net membership database. The short story is that we want provide single sign on access.
So what I've done is to connect directly to the membership database and tried to run a sql query against the aspnet_Membership table:
private bool CanLogin(string userName, string password)
{
// Check DB to see if the credential is correct
try
{
string passwordHash = FormsAuthentication.HashPasswordForStoringInConfigFile(password, "SHA1");
string sql = string.Format("select 1 from aspnet_Users a inner join aspnet_Membership b on a.UserId = b.UserId and a.applicationid = b.applicationid where a.username = '{0}' and b.password='{1}'", userName.ToLowerInvariant(), passwordHash);
using (SqlConnection sqlConn = new SqlConnection(ConfigurationManager.ConnectionStrings["LocalSqlServer"].ConnectionString))
using (SqlCommand sqlCmd = new SqlCommand(sql, sqlConn))
{
sqlConn.Open();
int count = sqlCmd.ExecuteNonQuery();
return count == 1;
}
}
catch (Exception ex)
{
return false;
}
}
The problem is the password value, does anyone know how the password it is hashed?
if you have two asp.net apps on the same IIS server, you can do SSO like this. I asked this question and answered it myself.
here
Once you have both apps pointing at your asp_membership database by placing the following in the system.web section of your web config
<authentication mode="Forms" />
<membership>
<providers>
<clear/>
<add name="AspNetSqlMembershipProvider"
type="System.Web.Security.SqlMembershipProvider, System.Web, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a"
connectionStringName="membership"
applicationName="/"
/>
</providers>
</membership>
<roleManager enabled="true" />
make sure both have the same applicationname property set.
I was using IIS 6 so I configured it to autogenerate a machine key for both applications. Because both of these applications live on the same machine the key would be identical, this is the critical part to making the SSO work. After setting up IIS the following was added to my web.config
<machineKey decryptionKey="AutoGenerate" validation="SHA1" validationKey="AutoGenerate" />
That was all there was to it. Once that was done I could log into app1 and then browse to app2 and keep my security credentials.
The problem is the password value,
does anyone know how the password it
is hashed?
Yes - you do! Check your web.config file for something like this:
<membership defaultProvider="MembershipSqlProvider"
userIsOnlineTimeWindow="15">
<providers>
<add name="MembershipSqlProvider"
type="System.Web.Security.SqlMembershipProvider, System.Web,
Version=1.2.3400.0, Culture=neutral,
PublicKeyToken=b03f5f7f11d50a3a"
PasswordFormat="Hashed" />
</providers>
</membership>
The PasswordFormat is what you are looking for. It can have the following three values:
Clear
Encrypted
Hashed
And, Microsoft sets the default value to Hashed for PasswordFormat.
Why don't check it automatically via System.Web.Security.Membership.ValidateUser() ?
<?xml version="1.0" encoding="utf-8"?>
<configuration>
<system.web>
<membership defaultProvider="MyMembershipProvider">
<providers>
<clear />
<add name="MyMembershipProvider" type="MyApplication.MyMembershipProvider" connectionStringName="MyConnString" />
</providers>
</membership>
</system.web>
</configuration>

Resources