Asp.net forms authentication for users in sqlserver - asp.net

I want to use form authentication in ASP.net . Users are in a database of my project. my codes are below.but these codes doesn't work.(users can't login). users are in "users" table in "news"database.
My web.config file:
<configuration>
<system.web>
<authentication mode="Forms">
<forms loginUrl="default.aspx" name=".asp" path="/" timeout="1" >
</forms>
</authentication>
<authorization>
<allow users="*"/>
</authorization>
<compilation debug="true" targetFramework="4.0"/>
<membership>
<providers>
<clear/>
<add name="MySqlMembershipProvider"
connectionStringName="news"
applicationName="users"
type="System.Web.Security.SqlMembershipProvider, System.Web, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a" />
</providers>
</membership>
</system.web>
<appSettings/>
<connectionStrings>
<add name="news" connectionString="Data Source=Data Source=.\SQLEXPRESS;AttachDbFilename=C:\Users\ava\Desktop\WebSite3\App_Data\news.mdf;Integrated Security=True;User Instance=True"
providerName="System.Data.SqlClient" />
</connectionStrings>
<location path="karbar.aspx">
<system.web>
<authorization>
<deny users="?" />
</authorization>
</system.web>
</location>
</configuration>
and my codes in default.aspx form for login is:
> protected void Button1_Click(object sender, EventArgs e) {
> if (FormsAuthentication.Authenticate(user.Text, pass.Text))
> {
> FormsAuthentication.SetAuthCookie(user.Text, true);
> FormsAuthentication.RedirectFromLoginPage(pass.Text, true);
> }
> else
> user.Text = ":((((((("; }

Update your configuration file this way:
<membership>
<providers>
<clear/>
<add name="MySqlMembershipProvider"
connectionStringName="ConnectionString"
applicationName="users"
type="System.Web.Security.SqlMembershipProvider, System.Web, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a" />
</providers>
</membership>
</system.web>
<appSettings/>
<connectionStrings>
<add name="ConnectionString" connectionString="Data Source=Data Source=.\SQLEXPRESS;AttachDbFilename=C:\Users\ava\Desktop\WebSite3\App_Data\news.mdf;Integrated Security=True;User Instance=True"
providerName="System.Data.SqlClient" />
</connectionStrings>
Update
I hope you have also problem in your code change it to
if (Membership.ValidateUser(user.Text, pass.Text))
{
FormsAuthentication.SetAuthCookie(user.Text, true);
FormsAuthentication.RedirectFromLoginPage(user.Text, true);
}
Update: Since you're using your own database no need for membership
<configuration>
<system.web>
<authentication mode="Forms">
<forms loginUrl="default.aspx" name=".asp" path="/" timeout="1" >
</forms>
</authentication>
<authorization>
<allow users="*"/>
</authorization>
<compilation debug="true" targetFramework="4.0"/>
<connectionStrings>
<add name="news" connectionString="Data Source=Data Source=.\SQLEXPRESS;AttachDbFilename=C:\Users\ava\Desktop\WebSite3\App_Data\news.mdf;Integrated Security=True;User Instance=True"
providerName="System.Data.SqlClient" />
</connectionStrings>
<location path="karbar.aspx">
<system.web>
<authorization>
<deny users="?" />
</authorization>
</system.web>
See remove the <membership> tag all together.
then in code behind read the user record from database put the result in datareader
protected void Button1_Click(object sender, EventArgs e) {
//assume you opened the db
SqlCommand cmd=new SqlCommand();
cmd.CommandText="select * from users where username=#name and password=#pass";
cmd.Connection=conn;
cmd.Parameters.AddWithValue("name",user.Text);
cmd.Parameters.AddWithValue("pass",pass.Text);
SqlDataReader dr=cmd.ExecuteReader();
if (dr.HasRows)
{
FormsAuthentication.SetAuthCookie(user.Text, true);
FormsAuthentication.RedirectFromLoginPage(user.Text, true);
}
else labelerror.Text="Incorrect name or pass";
}
Now use your table name and I'm hopeful you know what to do. Remember you've only one web form secured karbar.aspx.

Two things:
As others mentioned in comments, make sure the connection name is news, not in but in <connectionStrings> element.
Your database should have a series of special talbes+views+SPs of Forms Authentication, by running aspnet_regsql.exe. These tables are administered internally by ASP.NET's authentication/membership/role providers.

In The Following Tag :
<forms loginUrl="default.aspx" name=".[CookieName]" path="/" timeout="1" >
Put The name of your cookie in the name property .
Also --> change the seconde parameter in :
FormsAuthentication.RedirectFromLoginPage(pass.Text, true);
to
FormsAuthentication.RedirectFromLoginPage(pass.Text, false);

Related

asp.net forms authentication only redirects to default.aspx

I am using ASP.NET Forms Authentication with an activation email. I have gotten the registration to work, which adds the user to the database and sends the activation email, the email is sent to the user and the click on it and are activated. I am able to login with the correct crednetials, but everytime- it just redirects to default.aspx at the root of my project. I tried adding links to pages in the sub directory allowed for that role- but it just brings you back to the login page. When you login again- it just goes back to default.aspx
Here is the code on login.aspx.vb
Imports System.Data
Imports System.Configuration
Imports System.Data.SqlClient
Imports System.Web.Security
Imports Microsoft.VisualBasic
Imports System
Partial Class login
Inherits System.Web.UI.Page
Protected Sub ValidateUser(sender As Object, e As AuthenticateEventArgs) Handles Login1.Authenticate
Dim userID As Integer = 0
Dim roles As String = String.Empty
Session("roles") = Nothing
Using con As New SqlConnection("Data Source=(LocalDB)\MSSQLLocalDB;AttachDbFilename=|DataDirectory|\BandDatabase.mdf;Integrated Security=True")
Using cmd As New SqlCommand("Validate_User")
cmd.CommandType = CommandType.StoredProcedure
cmd.Parameters.AddWithValue("#Username", Login1.UserName)
cmd.Parameters.AddWithValue("#Password", Login1.Password)
cmd.Connection = con
con.Open()
Dim reader As SqlDataReader = cmd.ExecuteReader()
If reader.Read() Then
userID = Convert.ToInt32(reader("UserId"))
roles = reader("RoleName").ToString()
Session("roles") = roles
End If
con.Close()
End Using
Select Case userID
Case 1
Login1.FailureText = "Username and/or password is incorrect."
Exit Select
Case 2
Login1.FailureText = "Account has not been activated."
Exit Select
Case Else
Dim ticket As New FormsAuthenticationTicket(1, Login1.UserName, DateTime.Now, DateTime.Now.AddMinutes(2880), Login1.RememberMeSet, roles,
FormsAuthentication.FormsCookiePath)
Dim hash As String = FormsAuthentication.Encrypt(ticket)
Dim cookie As New HttpCookie(FormsAuthentication.FormsCookieName, hash)
If ticket.IsPersistent Then
cookie.Expires = ticket.Expiration
End If
Response.Cookies.Add(cookie)
Response.Redirect(FormsAuthentication.GetRedirectUrl(Login1.UserName, Login1.RememberMeSet))
Exit Select
End Select
End Using
End Sub
Protected Sub Page_Load(sender As Object, e As EventArgs) Handles Me.Load
If Not Me.IsPostBack Then
If Me.Page.User.Identity.IsAuthenticated Then
FormsAuthentication.SignOut()
Response.Redirect("~/login.aspx")
Else
Session.Abandon()
Session.Clear()
End If
End If
End Sub
End Class
Here is the web config (root of project- I read something about having to put a web config in each directory)
<authentication mode="Forms">
<forms defaultUrl="~/Default.aspx" loginUrl="~/login.aspx" slidingExpiration="true" timeout="2880">
</forms>
</authentication>
</system.web>
<!--https://www.codeproject.com/Articles/2905/Role-based-Security-with- Forms- Authentication-->
<location path="Admin">
<system.web>
<authorization>
<!-- Order and case are important below -->
<allow roles="Admin" />
<deny users="*" />
</authorization>
</system.web>
</location>
<location path="Judges">
<system.web>
<authorization>
<!-- Order and case are important below -->
<allow roles="Judge" />
<deny users="*" />
</authorization>
</system.web>
</location>
<location path="Students">
<system.web>
<authorization>
<!-- Order and case are important below -->
<allow roles="Student" />
<deny users="*" />
</authorization>
</system.web>
</location>
Here is the directory structure...
directory structure
Full web config...
<?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>
<system.webServer>
<validation validateIntegratedModeConfiguration="false" />
<handlers>
<remove name="ChartImageHandler" />
<add name="ChartImageHandler" preCondition="integratedMode" verb="GET,HEAD,POST" path="ChartImg.axd" type="System.Web.UI.DataVisualization.Charting.ChartHttpHandler, System.Web.DataVisualization, Version=4.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35" />
<add name="ReportViewerWebControlHandler" preCondition="integratedMode" verb="*" path="Reserved.ReportViewerWebControl.axd" type="Microsoft.Reporting.WebForms.HttpHandler, Microsoft.ReportViewer.WebForms, Version=11.0.0.0, Culture=neutral, PublicKeyToken=89845dcd8080cc91" />
</handlers>
</system.webServer>
<connectionStrings>
<add name="Database" connectionString="Data Source=(LocalDB)\MSSQLLocalDB;AttachDbFilename=|DataDirectory|\Database.mdf;Integrated Security=True"
providerName="System.Data.SqlClient" />
<add name="BandDatabaseConnectionString" connectionString="Data Source=(LocalDB)\MSSQLLocalDB;AttachDbFilename=|DataDirectory|\BandDatabase.mdf;Integrated Security=True"
providerName="System.Data.SqlClient" />
</connectionStrings>
<system.web>
<httpHandlers>
<add path="ChartImg.axd" verb="GET,HEAD,POST" type="System.Web.UI.DataVisualization.Charting.ChartHttpHandler, System.Web.DataVisualization, Version=4.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35"
validate="false" />
<add path="Reserved.ReportViewerWebControl.axd" verb="*" type="Microsoft.Reporting.WebForms.HttpHandler, Microsoft.ReportViewer.WebForms, Version=11.0.0.0, Culture=neutral, PublicKeyToken=89845dcd8080cc91"
validate="false" />
</httpHandlers>
<pages>
<controls>
<add tagPrefix="asp" namespace="System.Web.UI.DataVisualization.Charting" assembly="System.Web.DataVisualization, Version=4.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35" />
</controls>
</pages>
<compilation debug="true" strict="false" explicit="true" targetFramework="4.5">
<buildProviders>
<add extension=".rdlc" type="Microsoft.Reporting.RdlBuildProvider, Microsoft.ReportViewer.WebForms, Version=11.0.0.0, Culture=neutral, PublicKeyToken=89845dcd8080cc91" />
</buildProviders>
</compilation>
<httpRuntime targetFramework="4.5" />
<authentication mode="Forms">
<forms defaultUrl="~/Default.aspx" loginUrl="~/login.aspx" slidingExpiration="true" timeout="2880">
</forms>
</authentication>
</system.web>
<!--https://www.codeproject.com/Articles/2905/Role-based-Security-with-Forms-Authentication-->
<location path="Admin">
<system.web>
<authorization>
<!-- Order and case are important below -->
<allow roles="Admin, Student, Judge" />
<deny users="?" />
</authorization>
</system.web>
</location>
<location path="Judges">
<system.web>
<authorization>
<!-- Order and case are important below -->
<allow roles="Judge" />
<deny users="?" />
</authorization>
</system.web>
</location>
<location path="Students">
<system.web>
<authorization>
<!-- Order and case are important below -->
<allow roles="Student" />
<deny users="?" />
</authorization>
</system.web>
</location>
<appSettings>
<add key="ValidationSettings:UnobtrusiveValidationMode" value="None" />
<add key="ChartImageHandler" value="storage=file;timeout=20;dir=c:\TempImageFiles\;" />
</appSettings>
<system.net>
<mailSettings>
<smtp deliveryMethod="Network" from="people#overthere.com">
<network host="localhost" userName="" password="" defaultCredentials="true" />
</smtp>
</mailSettings>
</system.net>
</configuration>
Web.config tells you where the login redirects to (Default.aspx):
<authentication mode="Forms">
<forms defaultUrl="~/Default.aspx"
loginUrl="~/login.aspx"
slidingExpiration="true" timeout="2880">
</forms>
</authentication>
i have a login page that uses the web.config to redirect to the default page.
i also use a separate login control on certain pages that redirects to the page they're on.
note: if a user is not allowed on the page/directory they're trying to log in on, they are automatically redirected to the default page.

Active Directory Membership Provider - AD Groups / Web.Config not working

I have a asp.net/c# application that is using Windows authentication. I'm trying to control permission based on what AD users belong in but I can't seem to get it to work through the web.config.
I also added some code in the code behind and it's even acting strange:
if (Roles.IsUserInRole("STP Admin"))
{
int j = 1;
}
if (User.IsInRole(#"DOMAINNAME\STP Admin"))
{
int i = 1;
}
the first if block does not work however the second one does. So I believe this tells me the application can/is communicating with AD.
Here is my web.config that is where I'd like the code to go and it is not working for granting permissions. It will deny me access to the paths even though I am in those groups, proven by code above.
<?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>
<configSections>
<section name="loggingConfiguration" type="Microsoft.Practices.EnterpriseLibrary.Logging.Configuration.LoggingSettings, Microsoft.Practices.EnterpriseLibrary.Logging, Version=4.1.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35"/>
<section name="dataConfiguration" type="Microsoft.Practices.EnterpriseLibrary.Data.Configuration.DatabaseSettings, Microsoft.Practices.EnterpriseLibrary.Data, Version=4.1.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35"/>
</configSections>
<loggingConfiguration name="Logging Application Block" tracingEnabled="true" defaultCategory="General" logWarningsWhenNoCategoriesMatch="true">
<listeners>
<add databaseInstanceName="STPDB" writeLogStoredProcName="WriteAuditLog" addCategoryStoredProcName="AddAuditCategory" formatter="Custom Audit Database Formatter" listenerDataType="Microsoft.Practices.EnterpriseLibrary.Logging.Database.Configuration.FormattedDatabaseTraceListenerData, Microsoft.Practices.EnterpriseLibrary.Logging.Database, Version=4.1.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35" traceOutputOptions="None" filter="All" type="Microsoft.Practices.EnterpriseLibrary.Logging.Database.FormattedDatabaseTraceListener, Microsoft.Practices.EnterpriseLibrary.Logging.Database, Version=4.1.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35" name="Database Trace Listener"/>
<add source="Enterprise Library Logging" formatter="Text Formatter" log="Application" machineName="" listenerDataType="Microsoft.Practices.EnterpriseLibrary.Logging.Configuration.FormattedEventLogTraceListenerData, Microsoft.Practices.EnterpriseLibrary.Logging, Version=4.1.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35" traceOutputOptions="None" filter="All" type="Microsoft.Practices.EnterpriseLibrary.Logging.TraceListeners.FormattedEventLogTraceListener, Microsoft.Practices.EnterpriseLibrary.Logging, Version=4.1.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35" name="Formatted EventLog TraceListener"/>
</listeners>
<formatters>
<add template="{dictionary({key} - {value})}" type="Microsoft.Practices.EnterpriseLibrary.Logging.Formatters.TextFormatter, Microsoft.Practices.EnterpriseLibrary.Logging, Version=4.1.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35" name="Custom Audit Database Formatter"/>
<add template="Timestamp: {timestamp}
Message: {message}
Category: {category}
Priority: {priority}
EventId: {eventid}
Severity: {severity}
Title:{title}
Machine: {machine}
Application Domain: {appDomain}
Process Id: {processId}
Process Name: {processName}
Win32 Thread Id: {win32ThreadId}
Thread Name: {threadName}
Extended Properties: {dictionary({key} - {value}
)}" type="Microsoft.Practices.EnterpriseLibrary.Logging.Formatters.TextFormatter, Microsoft.Practices.EnterpriseLibrary.Logging, Version=4.1.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35" name="Text Formatter"/>
</formatters>
<categorySources>
<add switchValue="All" name="Audit">
<listeners>
<add name="Database Trace Listener"/>
</listeners>
</add>
<add switchValue="All" name="General">
<listeners>
<add name="Formatted EventLog TraceListener"/>
</listeners>
</add>
</categorySources>
<specialSources>
<allEvents switchValue="All" name="All Events"/>
<notProcessed switchValue="All" name="Unprocessed Category">
<listeners>
<add name="Formatted EventLog TraceListener"/>
</listeners>
</notProcessed>
<errors switchValue="All" name="Logging Errors & Warnings">
<listeners>
<add name="Formatted EventLog TraceListener"/>
</listeners>
</errors>
</specialSources>
</loggingConfiguration>
<connectionStrings>
<add name="STPDB" connectionString="Data Source=server\;Initial Catalog=DB;user id=usr;pwd=pass;Integrated Security=False" providerName="System.Data.SqlClient"/>
</connectionStrings>
<appSettings>
<add key="FromEmailAddress" value="stp1#company.com"/>
<add key="TrainingWarning" value="*Note: Training not being recorded for Medical, ..."/>
<add key="PrivacyMessage" value="This Information System Is Subject To The Privacy Act Of 1974"/>
</appSettings>
<system.web>
<compilation debug="true" targetFramework="4.0" />
<securityPolicy>
<trustLevel name="Full" policyFile="internal"/>
</securityPolicy>
<authentication mode="Windows"/>
<authorization>
<deny users="?"/>
<allow roles="DOMAIN\STP Training"/>
<allow roles="DOMAIN\STP Personnel"/>
<allow roles="DOMAIN\STP Admin"/>
<allow users="*"/>
</authorization>
<identity impersonate="true"/>
<membership defaultProvider="AspNetActiveDirectoryMembershipProvider">
<providers>
<clear/>
<add name="AspNetActiveDirectoryMembershipProvider"
type="System.Web.Security.ActiveDirectoryMembershipProvider,
System.Web, Version=4.0.0.0, Culture=neutral,
PublicKeyToken=b03f5f7f11d50a3a" />
</providers>
</membership>
<roleManager enabled="true" defaultProvider="AspNetWindowsTokenRoleProvider">
<providers>
<add name="WindowsProvider" type="System.Web.Security.WindowsTokenRoleProvider"/>
</providers>
</roleManager>
<siteMap defaultProvider="XmlSiteMapProvider" enabled="true">
<providers>
<add name="XmlSiteMapProvider" type="System.Web.XmlSiteMapProvider" siteMapFile="Web.sitemap" securityTrimmingEnabled="true"/>
</providers>
</siteMap>
<profile>
<providers>
<clear/>
<add name="AspNetSqlProfileProvider" type="System.Web.Profile.SqlProfileProvider" connectionStringName="ApplicationServices" applicationName="/"/>
</providers>
</profile>
<!--
The <customErrors> section enables configuration
of what to do if/when an unhandled error occurs
during the execution of a request. Specifically,
it enables developers to configure html error pages
to be displayed in place of a error stack trace.
-->
<customErrors mode="RemoteOnly" redirectMode="ResponseRewrite" defaultRedirect="~/ErrorPage.aspx">
</customErrors>
</system.web>
<location path="\TrainingSec">
<system.web>
<authorization>
<allow roles="STP Training"/>
<allow roles="STP Admin"/>
<deny users="*"/>
</authorization>
</system.web>
</location>
<location path="\Manage">
<system.web>
<authorization>
<allow roles="STP Training"/>
<deny users="*"/>
<allow roles="Sentry Admin"/>
</authorization>
</system.web>
</location>
<location path="\Admin">
<system.web>
<authorization>
<allow roles="STP Admin"/>
<deny users="*"/>
</authorization>
</system.web>
</location>
<system.net>
<mailSettings>
<smtp deliveryMethod="Network" from="STP#Company.com">
<network defaultCredentials="false" host="11.111.11.11" port="25"/>
</smtp>
</mailSettings>
</system.net>
<system.webServer>
<modules runAllManagedModulesForAllRequests="true"/>
<defaultDocument>
<files>
<clear />
<add value="Dashboard.aspx"/>
</files>
</defaultDocument>
</system.webServer>
</configuration>
You seem to have forgotten the domain part :
<location path="\TrainingSec">
<system.web>
<authorization>
<allow roles="DOMAIN\STP Training"/>
<allow roles="DOMAIN\STP Admin"/>
<deny users="*"/>
</authorization>
</system.web>
</location>

MVC2 login with Active Directory error=“Unable to establish secure connection with the server”

I got this strange error message:
Unable to establish secure connection with the server
when I try to login with my AD account. I've tried to connect to LDAP in ASP.NET webforms and it seems to work fine there and I don't think its the connection string who cause the problem.
But when I'm using MVC, the parser error appears. I've also tried to look around and google it but I can't seem to find the right solution. According to configuration error it says that
the source error is:
<add name="AspNetActiveDirectoryMembershipProvider"
type="System.Web.Security.ActiveDirectoryMembershipProvider"
connectionStringName="ADConnectionString"
connectionUsername="cn=actualUser"
connectionPassword="actualUsersPassword" />`
Here is my web.config:
<connectionStrings>
<add name="ADConnectionString" connectionString="LDAP://IPadress/DC=example,DC=test"/>
</connectionStrings>
<system.web>
<authentication mode="Forms">
<forms name=".ADAuthCookie" loginUrl="~/Account/LogOn" timeout="15"
slidingExpiration="false" protection="All" />
</authentication>
<authorization>
<deny users="?" />
<allow users="*" />
</authorization>
<compilation debug="true" targetFramework="4.0">
<assemblies>
<add assembly="System.Web.Abstractions, Version=4.0.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35" />
<add assembly="System.Web.Routing, Version=4.0.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35" />
<add assembly="System.Web.Mvc, Version=2.0.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35" />
</assemblies>
</compilation>
<membership defaultProvider="AspNetActiveDirectoryMembershipProvider">
<providers>
<clear/>
<add name="AspNetActiveDirectoryMembershipProvider"
type="System.Web.Security.ActiveDirectoryMembershipProvider"
connectionStringName="ADConnectionString"
connectionUsername="cn=actualUser" connectionPassword="actualUsersPassword" />
</providers>
</membership>
<trust level="Full" />
<pages>
<namespaces>
<add namespace="System.Web.Mvc" />
<add namespace="System.Web.Mvc.Ajax" />
<add namespace="System.Web.Mvc.Html" />
<add namespace="System.Web.Routing" />
</namespaces>
</pages>
</system.web>
Here is my class, i got the error message from " if (Membership.ValidateUser(model.UserName, model.Password))
{" where it points to the membership provider in web.config :
[HttpPost]
public ActionResult LogOn(LogOnModel model, string returnUrl)
{
if (ModelState.IsValid)
{
if (Membership.ValidateUser(model.UserName, model.Password))
{
FormsAuthentication.SetAuthCookie(model.UserName,Convert.ToBoolean(model.Password));
if ((!String.IsNullOrEmpty(returnUrl)))
{
return Redirect(returnUrl);
}
else
{
return RedirectToAction("Index", "Home");
}
}
else
{
ModelState.AddModelError("", "The user name or password provided is incorrect.");
}
}
// If we got this far, something failed, redisplay form
return View(model);
}
Have you tried to set your windows authentication mode to Windows ?
<authentication mode="Windows" />

Membership Role Provider doesn't work with custom connection string?

plz help with one issue.
I have Membership configured with IIS7, tables for it located in my own database, created with aspnet_regsql utility, and I am using custom connection string to access it.
This is part of web.config related to Membership :
<connectionStrings>
<add connectionString="Server=CORESERVER\SQLExpress;Database=Shop;User ID=Tema;Password=Matrix" name="CustomSqlConnection" />
</connectionStrings>
<profile enabled="true">
<providers>
<add name="CustomSqlProfileProvider" type="System.Web.Profile.SqlProfileProvider, System.Web, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a" connectionStringName="CustomSqlConnection" />
</providers>
</profile>
<roleManager defaultProvider="AspNetSqlRoleProvider" enabled="true">
<providers>
<add name="CustomSqlRoleProvider" type="System.Web.Security.SqlRoleProvider, System.Web, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a" connectionStringName="CustomSqlConnection" />
</providers>
</roleManager>
<membership defaultProvider="CustomSqlMemberProvider">
<providers>
<add name="CustomSqlMemberProvider" type="System.Web.Security.SqlMembershipProvider, System.Web, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a" connectionStringName="CustomSqlConnection" enablePasswordReset="true" enablePasswordRetrieval="false" passwordFormat="Hashed" requiresQuestionAndAnswer="true" requiresUniqueEmail="true" applicationName="/" maxInvalidPasswordAttempts="10" minRequiredPasswordLength="6" minRequiredNonalphanumericCharacters="0" passwordAttemptWindow="10" passwordStrengthRegularExpression="" />
</providers>
</membership>
<authentication mode="Forms">
<forms cookieless="UseCookies" loginUrl="login.aspx" name="WebShopAuthentication" protection="All" timeout="30" path="/" requireSSL="false" defaultUrl="~/admin/default.aspx" />
</authentication>
<authorization>
<allow users="*" />
</authorization>
And ... Forms authorization, getting user and his membership info is OK.
But ... getting roles is always FALSE.
MembershipUser userData = Membership.GetUser(HttpContext.Current.User.Identity.Name); // OK !!! IT IS GREAT :)
var a = new RolePrincipal(HttpContext.Current.User.Identity);
var aa = a.getRoles(); // {string[0]} - EMPTY!!!
var b = Roles.IsUserInRole("Administrator", "Administrator"); // FALSE!!!
var c = Roles.Providers["CustomSqlRoleProvider"].GetAllRoles(); // {string[0]} - EMPTY!!!
var d = Roles.IsUserInRole(HttpContext.Current.User.Identity.Name, "Administrator"); // FALSE!!!
var e = HttpContext.Current.User.IsInRole("Administrator"); // FALSE !!!
WHYYYY???
What am i doing wrong???
Just to refine ... authorization works fine and uses roles correctly. Another part of my web.config :
<location path="Admin">
<system.web>
<pages styleSheetTheme="Admin" theme="Admin">
</pages>
<authorization>
<deny users="?" />
<allow roles="Administrator" />
</authorization>
</system.web>
<appSettings>
<add key="ThemeName" value="Admin" />
</appSettings>
</location>
And then in code is used :
Membership.ValidateUser(userName.Text, userPassword.Text) // AND IT WORKS - USER IS LOGGED IN
The answer is that i didn't add applicationName parameter to web.config correctly - after adding i should restart IIS and if needed recreate roles.
This is final version of web.config :
<roleManager defaultProvider="CustomSqlRoleProvider" enabled="true">
<providers>
<add name="CustomSqlRoleProvider" type="System.Web.Security.SqlRoleProvider, System.Web, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a" connectionStringName="CustomSqlConnection" applicationName="/" />
</providers>
</roleManager>

Problems with the Login Page

I have this problem; I'm developing a site with ASP.Net 2005, the database I use is MySQL and the Web Server is Cassini, also I use Forms Authentication to handle the access to the pages.
I was making tests in all the computers accessing the site, however yesterday when I accessed the site from a PC the login page is presented but when I press the button to authenticate I stay in the same login page.
I don't know what is going because I can access the pages in the server but accessing from any other terminal it keeps me in the login page without accessing to the site (program) itself.
What is wrong here?
This is the code of the login button
qfh.User user = qfh.Global.Login(txtUserName.Text, txtPassword.Text, null, null);
if (user != null)
{
// Initialize FormsAuthentication, for what it's worth
FormsAuthentication.Initialize();
// Create a new ticket used for authentication
FormsAuthenticationTicket ticket = new FormsAuthenticationTicket(
1, // Ticket version
user.UserName, // Username associated with ticket
DateTime.Now, // Date/time issued
DateTime.Now.AddMinutes(30), // Date/time to expire
true, // "true" for a persistent user cookie
string.Join(",", user.GetRoles()), // User-data, in this case the roles
FormsAuthentication.FormsCookiePath);// Path cookie valid for
//Fill the complementary data
Profile.User = user.UserName;
Profile.Name = user.Name;
//Profile.Enterprise = user.Enterprise.EnterpriseCode; // enterprise.EnterpriseCode;
//Profile.Period = user.Enterprise.GetActivePeriod().PeriodCode; //enterprise.GetActivePeriod().PeriodCode;
Session["Enterprise"] = user.Enterprise.EnterpriseCode;
Session["Period"] = user.Enterprise.GetActivePeriod().PeriodCode;
// Encrypt the cookie using the machine key for secure transport
string hash = FormsAuthentication.Encrypt(ticket);
HttpCookie cookie = new HttpCookie(
FormsAuthentication.FormsCookieName, // Name of auth cookie
hash); // Hashed ticket
// Set the cookie's expiration time to the tickets expiration time
if (ticket.IsPersistent) cookie.Expires = ticket.Expiration;
// Add the cookie to the list for outgoing response
Response.Cookies.Add(cookie);
// Redirect to requested URL, or homepage if no previous page
// requested
string returnUrl = Request.QueryString["ReturnUrl"];
if (returnUrl == null) returnUrl = "/";
// Don't call FormsAuthentication.RedirectFromLoginPage since it
// could
// replace the authentication ticket (cookie) we just added
Response.Redirect(returnUrl);
}
else
{
lblStatusMessage.Text = Utilities.JSAlert("Access denied");
return;
}
This is the web.config
<?xml version="1.0"?>
<!--
Note: As an alternative to hand editing this file you can use the
web admin tool to configure settings for your application. Use
the Website->Asp.Net Configuration option in Visual Studio.
A full list of settings and comments can be found in
machine.config.comments usually located in
\Windows\Microsoft.Net\Framework\v2.x\Config
-->
<configuration>
<configSections>
<section name="activerecord" type="Castle.ActiveRecord.Framework.Config.ActiveRecordSectionHandler, Castle.ActiveRecord"/>
</configSections>
<appSettings>
<add key="QFH" value="QFH2009" />
</appSettings>
<activerecord isWeb="true">
<config>
<add key="hibernate.connection.driver_class" value="NHibernate.Driver.MySqlDataDriver"/>
<add key="hibernate.dialect" value="NHibernate.Dialect.MySQLDialect"/>
<add key="hibernate.connection.provider" value="NHibernate.Connection.DriverConnectionProvider"/>
<add key="hibernate.connection.connection_string" value="Server=localhost;Database=qfh;User ID=root;Password=admin;Pooling=false;Min Pool Size=5;Max Pool Size=100;"/>
</config>
</activerecord>
<connectionStrings>
<!--<add name="QFHConnectionString" connectionString="Dsn=QFH" providerName="System.Data.Odbc"/>-->
<add name="QFHConnectionString" connectionString="Server=localhost;Database=qfh;User ID=root;Password=admin;Pooling=false;Min Pool Size=5;Max Pool Size=100;"/>
</connectionStrings>
<system.web>
<roleManager defaultProvider="MySqlRoleProvider"
enabled="true"
cacheRolesInCookie="true"
cookieName=".ASPROLES"
cookieTimeout="30"
cookiePath="/"
cookieRequireSSL="false"
cookieSlidingExpiration="true"
cookieProtection="All" >
<providers>
<clear />
<add
name="MySqlRoleProvider"
type="Andri.Web.MySqlRoleProvider"
connectionStringName="QFHConnectionString"
applicationName="QFH"
writeExceptionsToEventLog="true"
/>
</providers>
</roleManager>
<membership defaultProvider="MySqlMembershipProvider" userIsOnlineTimeWindow="15">
<providers>
<clear />
<add
name="MySqlMembershipProvider"
type="Andri.Web.MySqlMembershipProvider"
connectionStringName="QFHConnectionString"
applicationName="QFH"
enablePasswordRetrieval="false"
enablePasswordReset="true"
requiresQuestionAndAnswer="true"
requiresUniqueEmail="true"
passwordFormat="Hashed"
writeExceptionsToEventLog="true"
/>
</providers>
</membership>
<!--
Set compilation debug="true" to insert debugging
symbols into the compiled page. Because this
affects performance, set this value to true only
during development.
-->
<httpModules>
<add name="ar.sessionscope" type="Castle.ActiveRecord.Framework.SessionScopeWebModule, Castle.ActiveRecord"/>
</httpModules>
<compilation debug="true">
<assemblies>
<add assembly="MySql.Data, Version=5.1.7.0, Culture=neutral, PublicKeyToken=C5687FC88969C44D"/>
<add assembly="System.Windows.Forms, Version=2.0.0.0, Culture=neutral, PublicKeyToken=B77A5C561934E089"/>
<add assembly="System.Design, Version=2.0.0.0, Culture=neutral, PublicKeyToken=B03F5F7F11D50A3A"/>
<add assembly="System.Transactions, Version=2.0.0.0, Culture=neutral, PublicKeyToken=B77A5C561934E089"/>
<add assembly="Microsoft.VisualBasic, Version=8.0.0.0, Culture=neutral, PublicKeyToken=B03F5F7F11D50A3A"/>
</assemblies>
</compilation>
<!--
The <authentication> section enables configuration
of the security authentication mode used by
ASP.NET to identify an incoming user.
-->
<!--<roleManager enabled="false"/>-->
<authentication mode="Forms">
<forms name="QFHWEBAPP.ASPXAUTH" loginUrl="Login.aspx" defaultUrl="Default.aspx" />
</authentication>
<authorization>
<!-- Do not allow all users come in -->
<deny users="?"/>
</authorization>
<anonymousIdentification enabled="true"/>
<!-- Temporary fields for the session -->
<profile defaultProvider="MySQLProfileProvider">
<providers>
<!--<add name="MySqlProfileProvider"
type="Malachi.MySqlProviders.MySqlProfileProvider"-->
<add name="MySQLProfileProvider"
type="Ezim.MySql.Web.Profile.MySqlProfileProvider"
connectionStringName="QFHConnectionString"
applicationName="QFH"/>
</providers>
<properties>
<add name="User" allowAnonymous="true" type="System.String"/>
<add name="Name" allowAnonymous="true" type="System.String"/>
<add name="Period" allowAnonymous="true" type="System.Int32"/>
<add name="Enterprise" allowAnonymous="true" type="System.Int32"/>
</properties>
</profile>
<!--
The <customErrors> section enables configuration
of what to do if/when an unhandled error occurs
during the execution of a request. Specifically,
it enables developers to configure html error pages
to be displayed in place of a error stack trace.
<customErrors mode="RemoteOnly" defaultRedirect="GenericErrorPage.htm">
<error statusCode="403" redirect="NoAccess.htm" />
<error statusCode="404" redirect="FileNotFound.htm" />
</customErrors>
-->
<customErrors mode="Off" />
</system.web>
<!--This code is used to make available the css-->
<location path="css">
<system.web>
<authorization>
<allow users="*"/>
</authorization>
</system.web>
</location>
</configuration>
First rule out issues with the PC can you run fiddler (google it some MS devs wrote it) on the pc to check that the submit is getting processed by the server. If its not going to the web server then it could be a proxy issue blocking the pc from seeing your site or a javascript permissions issue stopping the button from being submitted.
If it is connecting then i would check the db query is going through (you did change the username and password in the web.config above i hope.) If that is ok; are your page permission settings correct; my sites web.config has a lot more authorisation settings in it.
<location path="css">
<system.web>
<authorization>
<allow users="*"/>
</authorization>
</system.web>
</location>
</configuration>

Resources