Role based authorization - asp.net

I am trying to use Role based authorization in declarative way, when unauthorized user attempt to access a page, it never fire an exception or show the user an error message. What I should do to show unauthorized message? is that possible in declarative way?
using coding is not a nice option sense I have several roles, and folder authorized for several roles while other folders are authorized for one role.
thanks

Use the following code in your Login page to redirect the user to either an unauthorized page or the default page.
protected void Page_Load( object sender, EventArgs e )
{
if( Page.IsPostBack )
return;
if( !Request.IsAuthenticated )
return;
if( !string.IsNullOrEmpty( Request.QueryString["ReturnUrl"] ) && !UrlAuthorizationModule.CheckUrlAccessForPrincipal(Request.QueryString["ReturnUrl"], User,"GET"))
{
// In Forms Authentication, authenticated but unauthorized requests are converted into a Redirect to the Login page.
// Redirect these to an error page instead.
Response.Redirect( "~/UnauthorizedAccess.aspx", false );
}
else
{
Response.Redirect( FormsAuthentication.DefaultUrl, false );
}
}
See this link for a picture of what's happening and more info:
http://www.asp.net/security/tutorials/user-based-authorization-cs

If it fails authorization it will throw an exception. It must be passing. What are you using for authentication? Have you disabled anonymous access?

Perhaps you could make use of a site map. More on those here, plus a bit about tying security to them here.

It's also possible to use web.config to set up permissions for various folders or files. Each folder could have a list of allows or denys like so:
<?xml version="1.0"?>
<configuration>
<system.web>
<authorization>
<allow roles="Administrators" />
<allow roles="Random Role" />
<deny users="*" />
<deny users="?" />
</authorization>
</system.web>
</configuration>
Then when someone hits the page that requires authorization that they don't have permission for it will redirect them to your login page. You could then check the query string for the page they came from and perhaps set up case specific responses, or at the very least if it has a returnURL page on it, say "You are not authorized to see this page."

Related

Windows Authentication Initialization ASP.net

In a ASP.net WebForms project, we currently use Forms Authentication, but the client wishes to use Windows Authentication instead. So I've changed the web.config to use Windows authentication. However, the application needs some user input and put in into a session before any webpage can be accessed. We currently do this in the postback of the loginpage.
Since Windows authentication does not have a 'Login' page, how can this be achieved? Should I check on every page it's On_Init event if the session has been set correctly..?
If you need a specific data in session available in every single page, the easiest approach would be to have a dedicated module that checks the condition in one of early pipeline events where the session is available (the acquire request state event sounds most suitable).
public class CustomConditionCheckModule : IHttpModule
{
public void Init( HttpApplication context )
{
context.AcquireRequestState += new EventHandler( acq_req_state );
}
public void acq_req_state( object sender, EventArgs e )
{
// check your condition there - the data is in session
var session = HttpContext.Current.Session;
if ( ... the condition ... )
Response.Redirect( "~/anonymous.page.aspx" );
}
}
Then you also need a page that can be accessed anonymously (you need a section in the web.config for this):
<location path="anonymous.page.aspx">
<system.web>
<authorization>
<allow users="*" />
</authorization>
</system.web>
</location>
I think you could go with LDAP (Active Directory Authentication)
with windows authentication in web.config but if its intranet web application or another way i.e. role based security with windows authentication.

How to check if user is logged in

I have created a Login page where users must provide username and password to have access to some specific resources, where they can upload images, or just edit some description about themselves.
My web.config file looks like this:
<authentication mode="Forms">
<forms loginUrl="Secure/Login.aspx" defaultUrl="index.aspx" name=".ASPXFORMSAUTH" timeout="30"/>
</authentication>
<authorization>
<allow users="*"/>
</authorization>
</system.web>
<location path="Secure">
<system.web>
<authorization>
<deny users="?"/>
</authorization>
</system.web>
</location>
So when the user has typed in the username and pw, he is redirected to the index.aspx page.
Depending wether the user is logged in or not, the index.aspx should show or hide some stuff.
This is how I check if he is logged in:
bool isLoggedIn = HttpContext.Current.User.Identity.IsAuthenticated;
if (isLoggedIn)
{
placeHolder2.Visible = true;
...
}
Now the problem is that the: HttpContext.Current.User.Identity.IsAuthenticated; ALWAYS returns true, so unauthorised people will be seeing the stuff that should be hidden.
I am not sure about the: HttpContext.Current.User.Identity.IsAuthenticated;
I just googled "How to check if user is logged in", and suggestions were the:
HttpContext.Current.User.Identity.IsAuthenticated;
I want only the people that are logged in to view the private stuff. How do I go about this? How do I make the: HttpContext.Current.User.Identity.IsAuthenticated only return true when the user is logged in?
Thanks
if (Request.IsAuthenticated) {.....}
edit based on some comments
Authenticated via "Forms", check here
HttpContext.Current.User.Identity.IsAuthenticated // will be "Forms" if using forms based auth
// "Negotiate" is using windows integrated
// etc
If using .net 4.5 and you wanted "SET" user claims.
The ClaimsPrincipal is recommended reading
bool isLoggedIn = System.Web.HttpContext.Current.User.Identity.IsAuthenticated
My coding is
bool val1 = (System.Web.HttpContext.Current.User != null) &&
(System.Web.HttpContext.Current.User.Identity.IsAuthenticated) &&
(System.Web.HttpContext.Current.User.Identity.AuthenticationType.ToString() == "Forms");
for identifying the users with domain login and logged in form

asp.net session logout

I have made an asp.net application. This application has session variables which shows that a user is logged in or logged out.
If there any way to capture the expiration of session without going to single pages and once this is logged out user can be redirected to login( Re-login) page?
Can my asp.net classes inherit some base class which can have some abstract method to check if session is existing or not.
Please suggest me some architecture to do this.
Thanks in advance.
This application has session variables which shows that a user is logged in or logged out.
This can be achieved by checking the HttpContext.Current.Request.IsAuthenticated property.
If there any way to capture the expiration of session without going to single pages and once > this is logged out user can be redirected to login( Re-login) page?
Configure the following elements in your applications web.config to restrict\allow access to resources\pages\directories on your site:
<authorization>
<allow .../>
<deny .../>
</authorization>
http://msdn.microsoft.com/en-us/library/8d82143t
And, configure the FormsAuthentication defaulturl and loginurl attributes to redirect users away from restricted resources.
You can use global.asax's session end event:
void Session_End(Object sender, EventArgs E) {
// your code....
}
When the session expire this event called.

ASP.Net authentication: Can I have multiple responses when user fails to authenticate/authorize to access a page

I am using ASP.net form authentication for my web application. I have folder "admin" for administration work, and also I can lock one user if he/she misbehaves.
currently if an normal user tries to access the admin page, it will be redirected to the logon page, although he/she is already logged on.
The question is: how can I configure the web app, so that when the user fails to access a page, I can show different pages such as "you need admin privilege to access this page"/"your account is locked out"/(normal logon page)?
ValidateUser() can only return bool. :(
Thanks a lot
You'll need to implement roles and add people to them. Once you assign people to the proper roles, you would check to see if the person is in the proper role to access a page. If not, redirect them or show the proper error message. You would be able to do this with code behind like it seems like you are already trying:
if(!Roles.IsUserInRole("Administrator")) Response.Redirect("~/");
Or you can use the web.config
<configuration>
<location path="memberPages">
<system.web>
<authorization>
<allow roles="Administrator" />
<deny users="*" />
</authorization>
</system.web>
</location>
<configuration>
See the links below for more info:
https://web.archive.org/web/20210417083524/https://www.4guysfromrolla.com/articles/121405-1.aspx
http://msdn.microsoft.com/en-us/library/ff647401.aspx
I solved this kind of problem giving different urls to diffenrent roles.
To admin you give www.yoursite.com/admin
to user you give www.yoursite.com/private
asp.net will automatically redirect both to the login.aspx page but you can get from the url parameter which kind of user it is.
//I detect where the request originated from
string str = Request.QueryString["ReturnUrl"] == null ? "" : Request.QueryString["ReturnUrl"].ToString();
//if this is Admin can access to Admin Area only
if (str.Contains("Admin") == true || str.Contains("admin") == true || str.Contains("ADMIN") == true)
{ .......

ASP.Net: Login control, LoginUser_LoggedIn, and Role population

I have a forms based application. The application is standard ASP.Net wizard generated with login controls. The root's web.config appears to be in order for forms based authentication. I did have to change the <roleManager> element to use type="System.Web.Security.SqlRoleProvider" (rather than a Windows token) per How To: Use Role Manager in ASP.NET.
I have setup three roles - Administrators, Engineers, Customers. There are three users - admin (administrator), eddie (engineer), and cathy (customer). I have verified the users and their roles using ASP.Net Configuration Tool.
Each role has its own directory on disk, and each role has its own collection of ASPX files and 'landing page'. Each directory has a web.config to limit access to the role in question. For example:
<location path="~/Engineers">
<system.web>
<authorization>
<allow roles="Engineers" />
<deny users="*"/>
</authorization>
</system.web>
</location>
Upon successful login, I hook LoginUser_LoggedIn to write a destination URL. The problem I am having is the user's roles are not populated upon login, so I'm not getting a good redirect. In the code below, rolesArray has a zero size.
Any ideas? Should I be approaching this from a different angle?
Private Sub LoginUser_LoggedIn(sender As Object, e As System.EventArgs) Handles LoginUser.LoggedIn
Try
Dim rolesArray() As String
rolesArray = Roles.GetRolesForUser()
Debug.Assert(rolesArray.Length > 0)
If (Roles.IsUserInRole("Administrators") = True) Then
LoginUser.DestinationPageUrl = "~/Administrators/Dashboard.aspx"
ElseIf (Roles.IsUserInRole("Engineers") = True) Then
LoginUser.DestinationPageUrl = "~/Engineers/Workspace.aspx"
ElseIf (Roles.IsUserInRole("Customers") = True) Then
LoginUser.DestinationPageUrl = "~/Customers/Dashboard.aspx"
Else
Debug.Assert(False)
End If
Catch ex As Exception
Debug.Print(ex.ToString)
End Try
End Sub
The same request upon logging in, the cookie is not available for use (for instance, if you check this.User.Identity.IsAuthenticated, it returns false too). It's because the cookie is established during that request, and will be available upon subsequent requests.
I'd recommend redirecting to a common page, then doing this check and redirect again, or query the roles directly from the database using the user Id of the login control.

Resources