Asp.Net Role Based Authentication? - c#

I want to redirect user based upon role.I can do it without using Forms Authentication but I want to do it with forms authentication. Following is my code:
Web.Config
<authentication mode="Forms">
<forms loginUrl="Forms/Login.aspx" defaultUrl="Member/Home.aspx">
</forms>
</authentication>
<authorization>
<deny users="?"/>
</authorization>
Login.aspx.cs
protected void btnLogin_Click(object sender, EventArgs e)
{
members.memberEmail = txtEmail.Text;
members.memberPassword = operation.EncodePasswordToBase64(txtPassword.Text);
DataSet ds = operation.GetUsers(members);
if (ds != null)
{
int role = int.Parse(ds.Tables[0].Rows[0]["memberType"].ToString());
if (role == 2)
{
Response.Redirect("../Member/Home.aspx");
}
else if(role == 1)
{
Response.Redirect("../Admin/Home.aspx");
}
}
}
Here GetUsers function giving back the Dataset of members and I am checking role from DataSet and redirecting the user to respective home page. I am trying to accomplish same thing using forms authentication:
I have enabled the role manager in web config:
<roleManager enabled="true">
</roleManager>
I know, I am doing wrong. Can anyone guide me?

Related

How to restrict access to a folder to a specific active directory group in an Asp.Net WebForms application?

I have a WebForms application that uses Active Directory for authentication. The entire company should be able to access the application (and they can), but there are several forms in a "Mgr" folder that should only be accessed by AD group "ta_admins". I have read several threads on SO, but I can't seem to get anything to work.
I created a Web.config file inside the "Mgr" folder and tried the following:
<?xml version="1.0"?>
<configuration>
<system.web>
<authorization>
<allow roles = "ta_admins" />
<deny users = "*" />
</authorization>
</system.web>
</configuration>
I have tried changing "
Method is only supported if the user name parameter matches the user name in the current Windows Identity.
I am a member of ta_admins.
Here is part of the application's Web.config:
<system.web>
<authorization>
<deny users="?" />
</authorization>
<authentication mode="Windows" />
<roleManager enabled="true" defaultProvider="AspNetWindowsTokenRoleProvider">
<providers>
<clear />
<add name="AspNetWindowsTokenRoleProvider" type="System.Web.Security.WindowsTokenRoleProvider" applicationName="/" />
</providers>
</roleManager>
..............
</system.web>
The aspx page has a grid that is populated with the members of a specific AD group. This works just fine when I'm not attempting to control the user group that can access the "Mgr" folder. The code behind is below (not sure if it's needed, but just-in-case...):
protected void Page_Load(object sender, EventArgs e)
{
DataTable dt = new DataTable();
dt.Columns.AddRange(new DataColumn[5]
{
new DataColumn("givenName", typeof (string)),
new DataColumn("sn", typeof (string)),
new DataColumn("mail", typeof (string)),
new DataColumn("department", typeof (string)),
new DataColumn("manager", typeof (string))
});
using (var context = new PrincipalContext(ContextType.Domain, null))
{
using (var group = (GroupPrincipal.FindByIdentity(context, "reps")))
{
var users = group.GetMembers(true);
foreach (UserPrincipal user in users)
{
DirectoryEntry de = user.GetUnderlyingObject() as DirectoryEntry;
dt.Rows.Add
(
Convert.ToString(de.Properties["givenName"].Value),
Convert.ToString(de.Properties["sn"].Value),
Convert.ToString(de.Properties["mail"].Value),
Convert.ToString(de.Properties["department"].Value),
Regex.Replace((Convert.ToString(de.Properties["manager"].Value)), #"CN=([^,]*),.*$", "$1")
);
}
rgAdUsrs.DataSource = dt;
rgAdUsrs.DataBind();
}
}
}
Please let me know if additional information is required.
Well I found and different way to get this done. I just get a list of all groups the user is in and base form access on that.
PrincipalSearchResult<Principal> groups = UserPrincipal.Current.GetGroups();
IEnumerable<string> groupNames = groups.Select(x => x.SamAccountName);
if (!groupNames.Contains("ta_admins"))
{
Response.Redirect("~/AccessDenied.aspx");
}
}
Then I disabled directoryBrowse in the web.config of the folder.

Role based authentication setting to defaultUrl in web.config in asp.net

My application contains the roles "Admin" and "Users". How can I provide web.config setting for "users" with one default URL & "admin" with another default URL in web.config file.
My current web.config file code :
<authentication mode="Forms">
<forms defaultUrl="/Welcome.aspx" loginUrl="/LogIn.aspx" >
</forms>
</authentication>
<authorization>
<deny users="?" />
</authorization>
My aspx.cs code under login with condition :
if (res =="USER")
{
Details det = new Details();
int id = det.UserId(Email, Passwor);
Label2.Text = id.ToString();
Session["ID"] = Label2.Text;
string name = det.UserName(Email, Passwor);
Label3.Text = name;
Session["Name"] = Label3.Text;
Session["Role"] = TextBox1.Text;
Response.Redirect("Welcome.aspx");
}
if (res =="ADMIN")
{
FormsAuthentication.GetRedirectUrl(Email,true);
//Response.Redirect("admin_page.aspx");
}

.NET FormsAuthentication and HttpContext.Current.User.Identity.IsAuthenticated combination not working

I'm trying to create a simple setup where the user navigates to a page and if they're not authenticated, taken to a login page. If the user enters the correct username and password, he/she is taken back to the first page where they have the ability to add data to a SQL database. Unfortunately as of now, when the user is authenticated, they get bounced from the first page back to the login page (e.g. the user isn't being authenticated). Here's what I have for code:
The applicable code in first page (where the user can enter data)
protected void Page_Load(object sender, EventArgs e)
{
/*Make sure the user is authenticated. If not, redirect them to the Login page*/
if (!HttpContext.Current.User.Identity.IsAuthenticated)
FormsAuthentication.RedirectToLoginPage();
else
LabelMsg.Text = "Authenticated: " + HttpContext.Current.User.Identity.IsAuthenticated.ToString();
}//end Page_Load()
The applicable code in login page:
using (SqlDataAdapter sda = new SqlDataAdapter())
{
sda.SelectCommand = myCommand;
DataTable dt = new DataTable();
sda.Fill(dt);
GridView GridViewBookList = new GridView();
GridViewBookList.DataSource = dt;
GridViewBookList.DataBind();
if (GridViewBookList.Rows.Count > 0)
{
FormsAuthentication.SetAuthCookie("admin", true);
FormsAuthentication.RedirectFromLoginPage("admin", true);
}
else
LabelMsg.Text = "Incorrect username or password";
}
Web.Config piece
<location path="~/whatsnew/add-newbook.aspx">
<!--Unauthenticated users cannot access this page-->
<system.web>
<authentication mode="Forms">
<!--.NEWBOOK is the name of the cookie used in authorization-->
<forms loginUrl="~/whatsnew/login.aspx" defaultUrl="~/default.aspx" requireSSL="true" name=".NEWBOOK"/>
</authentication>
<authorization>
<deny users="?"/>
<allow roles="admin"/>
</authorization>
</system.web>
Any help would be greatly appreciated.
I think you need to check Request.IsAuthenticated in your code. If you would like to use the HttpContext.Current.User.IsAuthenticated, in my experience I have had to set it by saying something like the following in my login page:
string username = "My username";
string[] roles = new string[] {"Role1", "Role2"};
HttpContext.Current.User =
new GenericPrincipal(new GenericIdentity(userName), roles);
I can see you're doing simple forms authentication. Have you tried adding WebSecurity.Login before you set the cookie?
WebSecurity.Login("admin", pwd, True);
FormsAuthentication.SetAuthCookie("admin", true);
FormsAuthentication.RedirectFromLoginPage("admin", true);

asp.net users role not being passed to page via FormsAuthenticationTicket

I'm trying to create a basic role based user access via FormsAuthenticationTicket but it's not working correctly as it doesn't seem to be passing the role to the page. The code I'm using is:
web.config:
<?xml version="1.0" encoding="utf-8"?>
<configuration>
<location path="HRPages">
<system.web>
<authorization>
<allow roles = "HR" />
<deny users ="*" />
</authorization>
</system.web>
</location>
<location path="SalesPages">
<system.web>
<authorization>
<allow roles = "Sales" />
<deny users ="*" />
</authorization>
</system.web>
</location>
<system.web>
<compilation debug="true" targetFramework="4.5" />
<httpRuntime targetFramework="4.5" />
<authentication mode="Forms" />
</system.web>
</configuration>
Login Page:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.Security;
namespace formlogin
{
public partial class Login : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
}
protected void cmdLogin_Click(object sender, EventArgs e)
{
if (this.txtUsersname.Text.Trim() == "1"
&& this.txtPassword.Text.Trim() == "2")
{
FormsAuthenticationTicket ticket = new FormsAuthenticationTicket(
1, // Ticket version
this.txtUsersname.Text.Trim(), // Username associated with ticket
DateTime.Now, // Date/time issued
DateTime.Now.AddMinutes(30), // Date/time to expire
true, // "true" for a persistent user cookie
"HR", // User-data, in this case the roles
FormsAuthentication.FormsCookiePath);// Path cookie valid for
// 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
{
// Never tell the user if just the username is password is incorrect.
// That just gives them a place to start, once they've found one or
// the other is correct!
Response.Write( "Username / password incorrect. Please try again.");
}
}
}
}
When I go to a page under the HRPages folder it presents me with the login screen and on successful login it creates a ticket and redirects me back to the page but then reverts back to the login screen again. What am I doing wrong please as it seems as if the role isn't being passed through?

trying to get the username used to sign into the website

I'm using the following code to check the user's credentials and if successful I put them to make-request.aspx, but on make-request.aspx I want to check the value of the username they entered so I can show certain content.
Here's the authentication code:
foreach (string key in ConfigurationSettings.AppSettings.Keys)
{
dominName = key.Contains("DirectoryDomain") ? ConfigurationSettings.AppSettings[key] : dominName;
adPath = key.Contains("DirectoryPath") ? ConfigurationSettings.AppSettings[key] : adPath;
if (!String.IsNullOrEmpty(dominName) && !String.IsNullOrEmpty(adPath))
{
if (true == AuthenticateUser(dominName, userName, txtPassword.Text,adPath, out strError))
{
Response.Redirect("../make-request.aspx");// Authenticated user redirects to default.aspx
}
dominName = string.Empty;
adPath = string.Empty;
if (String.IsNullOrEmpty(strError)) break;
}
Everything works fine but I'm not sure how to get the username they entered into the form. Here's code that I've tried that is getting username of the machine username -- I think. Any help would be appreciated!
I've tried all three of these:
//string userName = Environment.UserName;
string userName = HttpContext.Current.User.Identity.Name;
//string userName = System.Security.Principal.WindowsIdentity.GetCurrent().Name;
Here's the authentication/auth section of web.config:
<authentication mode="Windows" />
<authorization>
<allow users="*" />
<!--<deny users="*"/>-->
</authorization>
You are authenticating the user but not setting forms authentication cookie. Here's what you need to do:
FormsAuthentication.SetAuthCookie(userName, false);
Response.Redirect("../make-request.aspx");
Also make sure you have proper authentication/authorization set in your web.config. If you are not sure if it is setup correctly, share it here so we can take a look.
Set FormsAuthentication as below:
<authentication mode="Forms">
<forms loginUrl="Login.aspx"/>
</authentication>
<authorization>
<deny users="?"/>
</authorization>
The HttpContext.Current.User.Identity.Name will work as long as the user is currently logged in when it is ran. In one of my sites, I use the following (written in VB):
Dim u As MembershipUser = Membership.GetUser(Membership.GetUserNameByEmail(HttpContext.Current.User.Identity.Name))
Tip: You can test if the user is already logged in by checking the value of HttpContext.Current.User.Identity.IsAuthenticated.
However . . .
. . . Using the current HTTP context is only necessary in content pages or web APIs. Alternatively, you can use MembershipUser u = Membership.GetUser(); from the master page, and then use u.Username to retrieve the username or u.ProviderUserKey to retrieve the GUID of the user.
If Session Is Nothing OrElse Session(Current_User) Is Nothing Then
udtGeneral = GetdoGeneralInstance()
susername = Request.ServerVariables("LOGON_USER").Split("\")(1).ToString()
'Either of these work i believe
susername = Request.ServerVariables(7).Split("\")(1).ToString()
'Dim susername1 = Request.Browser.Capabilities("extra").ToString.Split(";")(14).ToString.Split(":")(1).ToString
Session("ipAddress") = Request.ServerVariables("REMOTE_ADDR").ToString()
End If

Categories