So I'm making a login system for my asp.net site. There are 3 different types of users. I've discovered that FORMS can manage roles so I decided to try this.
I have everything working with authentication in FORMS currently - but without roles. I found this piece of code that should limit access to a specific page. But everyone can still access that page. which is odd because I haven't added anyone to the role "member". to start off with I only added 1 role to see if people were blocked from the page.
<configuration>
<connectionStrings>
//EDITED
</connectionStrings>
<system.web>
<roleManager enabled="true" />
<customErrors mode ="Off">
</customErrors>
<authentication mode="Forms">
<forms name=".ASPXAUTH"
loginUrl="login.aspx"
protection="All"
timeout="30"
path="/">
</forms>
</authentication>
<authorization>
<deny users="?" />
<allow users="*" />
</authorization>
</system.web>
<location path="RandomPage.aspx">
<system.web>
<authorization>
<allow roles="Member" />
<deny users="*" />
</authorization>
</system.web>
</location>
<system.webServer>
<modules runAllManagedModulesForAllRequests="true"/>
</system.webServer>
</configuration>
Code for adding the roles to FormsAuthenticationTicket. P.Userole contains the string"Member"
FormsAuthenticationTicket ticket = new FormsAuthenticationTicket(
1, //Ticket version
p.firstName, //username
DateTime.Now,
DateTime.Now.AddMinutes(30),
false, //true for persistant user cookie
p.userRole+"",
FormsAuthentication.FormsCookiePath);
string hashCookies = FormsAuthentication.Encrypt(ticket);
HttpCookie cookie = new HttpCookie(FormsAuthentication.FormsCookieName, hashCookies);
Response.Cookies.Add(cookie);
Response.Redirect("Default.aspx");
I am sure, you did not add roles to the FormsAuthenticationTicket after successfull login. It should be like...
FormsAuthenticationTicket ticket = new FormsAuthenticationTicket(1, "UserId",
DateTime.Now, DateTime.Now.AddMinutes(30), false, "ListOfRolesCommandSeperate", FormsAuthentication.FormsCookiePath);
string hashCookies = FormsAuthentication.Encrypt(ticket);
HttpCookie cookie = new HttpCookie(FormsAuthentication.FormsCookieName, hashCookies);
Response.Cookies.Add(cookie);
You need to pass the roles of the logged in user to the FormsAuthenticationTicket to get it work. As you just added permission rights only in the web.config file.
Related
I have been using following (Asp.net Forms authentication)code some years ago on a former project to authorize users. But why is it no longer working?
This code from the web.config in the "safe" folder:
<configuration>
<system.web>
<authorization>
<allow roles="User" />
<deny users="*"/>
</authorization>
</system.web>
</configuration>
This is the code in the login.aspx:
FormsAuthenticationTicket authTicket = new FormsAuthenticationTicket(1, TextBox1.Text, DateTime.Now, DateTime.Now.AddMinutes(6000), false, "User");
string encryptedTicket = FormsAuthentication.Encrypt(authTicket);
HttpCookie authCookie = new HttpCookie(FormsAuthentication.FormsCookieName, encryptedTicket);
Response.Cookies.Add(authCookie);
Response.Redirect("LoggedOn/SafePage.aspx");
I have used the credential tag in web.config file to authenticate my admin. now I want to know is there any way to make a page with a form for admin to change his username and password?
this is my code in web.config:
<system.web>
<compilation debug="true" targetFramework="4.0" />
<sessionState cookieless="AutoDetect" mode="InProc" timeout="114400">
</sessionState>
<authentication mode="Forms">
<forms timeout="1440" loginUrl="~/entrance_before_paying.aspx" defaultUrl="Admin/Default.aspx" name=".ASPXFORMSDEMO" cookieless="AutoDetect" protection="All">
<credentials passwordFormat="Clear">
<user name="elmiragolshanff#yahoo.com" password="elmira" />
</credentials>
</forms>
</authentication>
</system.web>
I used this code in my sign in page to check if the user is admin or not:
private void enter()
{
if (FormsAuthentication.Authenticate(TextBox1.Text.Trim(), TextBox2.Text.Trim()))
{
FormsAuthentication.RedirectFromLoginPage("admin user name in credential tag", true);
}
else
{
// enter as a user}
}
}
yes, you can do it this way
<location path="Admin">
<system.web>
<authorization>
<allow users="ram"/>
<deny users="*"/>
</authorization>
</system.web>
</location>
Use above code in web.config file. this will allow only user 'ram' to access inside 'Admin' folder.
I used this code now it works fine
<form ID="form1" runat="server">
<div>
<asp:TextBox ID="txtUsername" runat="server">
</asp:TextBox>
<asp:TextBox ID="txtPassword" runat="server">
</asp:TextBox>
<asp:Button ID="btnWrite" runat="server" onclick="btnWrite_Click" Text="Modify" />
</div>
in ChangePassword.aspx.cs:
protected void btnWrite_Click(object sender, EventArgs e)
{
Configuration webconfig = WebConfigurationManager.OpenWebConfiguration("/wite your site name");
SystemWebSectionGroup sysweb = (SystemWebSectionGroup)webconfig.GetSectionGroup("system.web");
AuthenticationSection authSection = sysweb.Authentication;
FormsAuthenticationUserCollection users = authSection.Forms.Credentials.Users;
FormsAuthenticationUser user = users[0];
user.Name = txtUsername.Text;
user.Password = txtPassword.Text;
webconfig.Save();
}
i wrote a login menu and control panel for users,
but during short time it takes me out, see the codes
you know in the config file i wrote that "Admin" folder is secure and it's timeout is 30 minutes but when i'm logging maybe in 40-50 sec it take me out, where am i wrong ?
please help me
Web.config codes :
<authentication mode="Forms">
<forms name="MyAppCookie" path="/" loginUrl="Login.aspx" protection="All" timeout="60" defaultUrl="Admin" />
</authentication>
<authorization>
<allow users="*" />
</authorization>
<customErrors mode="Off" />
<pages validateRequest="false" enableEventValidation="false" viewStateEncryptionMode="Never" enableViewStateMac="false" />
<!--<sessionState timeout="1440"></sessionState>-->
</system.web>
<location path="Admin">
<system.web>
<authorization>
<deny users="?" />
<deny users="Users" />
</authorization>
</system.web>
</location>
Login Menu :
var login = (from u in DataContext.Context.Core_Users
where u.UserName == txtuid.Text && u.Password == txtPwd.Text
select u).FirstOrDefault();
if(login != null)
{
var role = (from r in DataContext.Context.Core_Roles
where r.RoleID == login.RoleID
select r).FirstOrDefault();
if(role != null)
{
string RoleName = role.RoleName;
FormsAuthenticationTicket AuthTicket = new FormsAuthenticationTicket(1, txtuid.Text, DateTime.Now, DateTime.Now.AddDays(1),false,RoleName,FormsAuthentication.FormsCookiePath);
string encryptedTocket = FormsAuthentication.Encrypt(AuthTicket);
HttpCookie AuthCookie = new HttpCookie(FormsAuthentication.FormsCookieName,encryptedTocket);
Response.Cookies.Add(AuthCookie);
Response.Redirect(FormsAuthentication.GetRedirectUrl(txtuid.Text, chkRemember.Checked));
}
else
{
lblMessage.Text = "Role Deleted";
}
}
else
{
lblMessage.Text = "Wrong username or password";
}
And secure pages :
if (!IsPostBack)
{
//Start Authorization Section
if (!Page.User.Identity.IsAuthenticated)
{
FormsAuthentication.RedirectToLoginPage();
}
// End of Authorization Section
}
Sessionstate timeout property is mentioned in minutes
In webconfig file...
<system.web>
.......
<sessionState timeout="1440"></sessionState>
</system.web>
The session will get expired if the webform is idle for 24 hrs continuously.
You can have this sessionstate block only within .
The following posts show how to setup the web.config for a site using Mixed Mode Authentication. IIS7 Mixed Mode Authentication and How to allow mixed-mode authentication in IIS 7.0.
I've got my site setup and working locally (on my developer machine). However, when I run it locally on the server I get 401.2 - Login failed due to server configuration error.
Anyone know how I'm supposed to configure the server, Default Web Site, and My Site?
Edit: Here are the settings in my web.config, including the loginUrl from the Forms authentication node.
<location path="~/Account/WinLogin.aspx">
<system.web>
<authorization>
<deny users="?"/>
<allow users="*"/>
</authorization>
</system.web>
<system.webServer>
<security>
<authentication>
<anonymousAuthentication enabled="false"/>
<windowsAuthentication enabled="true"/>
</authentication>
</security>
</system.webServer>
</location>
<system.web>
<authentication mode="Forms">
<forms loginUrl="~/Account/WinLogin.aspx" timeout="60"/>
</authentication>
<authorization>
<deny users="?"/>
</authorization>
Let's start with server roles configuration (this is under server manager, roles, IIS)
You're gonna want to make sure that the windows auth and anonymous auth sections are enabled/installed, and also the forms auth (which presumably you already have). After those are installed/configured, you'll need to define the following stuff:
In your Web.Config you're going to want to have the following sections defined:
<configuration>
<system.web>
<authentication mode="Forms">
<forms cookieless="UseDeviceProfile" defaultUrl="~/Default.aspx" enableCrossAppRedirects="true" loginUrl="~/WindowsLogin.aspx" name=".ASPXAUTH" path="/" protection="All" requireSSL="false" slidingExpiration="true" timeout="10080"/>
</authentication>
<authorization>
<deny users="?"/>
</authorization>
</system.web>
<location path="Login.aspx">
<system.web>
<authorization>
<allow users="?"/>
</authorization>
</system.web>
<system.webServer>
<security>
<authentication>
<anonymousAuthentication enabled="true"/>
<windowsAuthentication enabled="false"/>
</authentication>
</security>
</system.webServer>
</location>
<location path="WindowsLogin.aspx">
<system.web>
<authorization>
<deny users="?"/>
<allow users="*"/>
</authorization>
</system.web>
<system.webServer>
<security>
<authentication>
<anonymousAuthentication enabled="false"/>
<windowsAuthentication enabled="true"/>
</authentication>
</security>
</system.webServer>
</location>
</configuration>
Then you'll need two files:
Login.aspx (this does forms auth)
WindowsLogin.aspx (this does Windows auth)
LOGIN does forms, right, so that's just bog standard ASP.NET forms auth
It's WindowsLogin that does the magic (and here's that file)
using System;
using System.Web;
using System.Web.Security;
using App_Code.Biz;
public partial class WindowsLogin : System.Web.UI.Page {
protected string UserIsInRoles = string.Empty;
private static readonly BAL _mBAL = new BAL();
protected void Page_Load(object sender, EventArgs e) {
string redirectUrl = Request["returnurl"] ?? "~/default.aspx";
string username = Request.ServerVariables["LOGON_USER"];
try {
if ( Roles.GetRolesForUser( username ).Length < 1 )
Roles.AddUserToRole( username, Global.defaultRole );
int status;
_mBAL.aspnet_Membership_CreateUser( username, out status );
} catch ( Exception ex ) {
ErrHandler.WriteXML( ex );
}
/* Test to see if the user is in any roles */
if ( Roles.GetRolesForUser( username ).Length < 1 ) {
UserIsInRoles = "<br />" + username + "You are not in any rules. This must be your first visit to our site!<br /> Adding you to the " + Global.defaultRole + " role now!";
} else {
UserIsInRoles = "You are in the following roles: ";
string[] roles = Roles.GetRolesForUser( username );
foreach ( string role in roles )
UserIsInRoles += role + ", ";
UserIsInRoles = UserIsInRoles.Remove( UserIsInRoles.Length - 2 ) + "!";
if ( Login( username, String.Join( ",", roles ) ) )
Response.Redirect( redirectUrl );
}
//we shouldn't get here, so if we do, redirect back to a page they can use.
if ( Page.IsPostBack ) {
if ( Response.StatusCode == 401 )
Response.Redirect( "~/Login.aspx" );
}
}
private bool Login(string strUser, string strRole) {
if ( strRole != null ) {
FormsAuthenticationTicket ticket = new FormsAuthenticationTicket(
1, // version
strUser, // user name
DateTime.Now, // create time
DateTime.Now.AddYears(1), // expire time
false, // persistent
strRole ); // user data
string strEncryptedTicket = FormsAuthentication.Encrypt( ticket );
HttpCookie cookie = new HttpCookie( FormsAuthentication.FormsCookieName, strEncryptedTicket );
Context.Response.Cookies.Add( cookie );
return true;
}
return false;
}
}
After all this, you might get a config error for section locked at a parent level. Lock is either by default (overrideModeDefault="Deny") or set explicitly by a location tag ... and if so, then the fastest way to fix that is to open C:\Windows\System32\inetsrv\config\applicationHost.config and edit the following block:
<configSections>
<sectionGroup name="system.webServer">
<sectionGroup name="security">
<sectionGroup name="authentication">
<section name="anonymousAuthentication" overrideModeDefault="Allow">
<section name="windowsAuthentication" overrideModeDefault="Allow">
</sectionGroup>
</sectionGroup>
</sectionGroup>
</configSections>
Also see the chat log: https://chat.stackoverflow.com/rooms/5/conversation/configuring-iis7-and-mixed-mode-authentication-in-asp-net
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>