Custom Roles/Permissions in ASP.NET - c#

I currently have a Web Application which is using it's own "Permissions" table which contains the following columns:
UserName - Windows UserName (Context.User.Identity.Name)
DivisionID - Links to a Division Table
RoleID - Comes from a custom Roles Table
RegionID - Recently added field to divide my Application into Countries (Canada, USA, International)
When the User logs into the site, they choose which Region they want to enter and I need to give them access to those Regions based on if they have any permissions set for that specific RegionID. Upon selecting a Region, the RegionID is stored in Session and will be used for this permission check and defining how data is populated on the pages (I haven't implemented the Session variable into all of the pages just yet so that can be changed if need be)
My initial thought would be to run my Permission Check on each page sending them to one of three destinations:
Invalid Permission Page (false)
Region Select Page - No Region selected in Session (RegionID = 0)
The page they requested - If has a permission set for that Region
I've also looked into using the Application_AuthenticateRequest method within the Global.asax but I cannot use Session within this area and it seems to be hitting the Application_AuthenticateRequest much more than it should be.
With my current App, what would be the best way to authenticate each user with their corresponding Regions, based on their Permissions?

I've really only worked with forms authentication-- but I'm assuming you'll be using windows authentication for membership and some form of custom roles authentication. I've never done it, but one would think it should work.
http://msdn.microsoft.com/en-us/library/system.web.security.roleprovider.getrolesforuser
You could create a custom provider that would take into account the Session value for Region in order to return the correct roles. I know for a web application, the default provider stores the roles as an encrypted cookie on the client. I'm thinking you can do something similar.

Normally I wouldn't recommend this method, but as it seems that you have already developed your application, you could relatively easily implement the following without too much upheaval:
Create a base class for your pages, and then inherit all the pages in your application from the base class. You would of course implement the "authorization" within the base class.
The one rather nasty problem with this is that if you forget to derive your page from the base class, then your page has no security on it.....but you could just as easily forget to implement your "Permission check"....
Something like
public class AuthorizedPage: System.Web.UI.Page
{
protected override void OnLoad(EventArgs e)
{
// ... authorization logic here...
// Be sure to call the base class's OnLoad method!
base.OnLoad(e);
}
}
You could check this out ASP.net "BasePage" class ideas and this https://web.archive.org/web/20211020133935/https://www.4guysfromrolla.com/articles/041305-1.aspx
Or, another idea, if you have used Master Pages you could also just do this stuff in the master page....

Related

Prevent caching of layout file in MVC when caching Index action method

I have many create Views in my MVC application. I have cached the GET Index action method using [OutputCache] annotation, so that the view is stored in the cache.
I store the details about the currently logged in user in the Session, and display the user's first name in the layout after reading it from the Session.
The problem is, since I have cached the views, the layout is also cached. So even if a different user logs in, the first name of the previous user is visible, because the layout was cached last time.
Is there any way to prevent caching of the layout? Or is there any other way I can stop the first name display from getting cached?
I thought about using VaryByCustom, but I am not sure what to do in the GetVaryByCustomString method that I will need to override.
What would be the best approach to prevent caching of the layout, or alternately, varying the cache by user?
EDIT:
I must clarify that I am using my own custom user management logic. I have my own Users table in the database and I retrieve relevant data on login and store it in Session.
Here's one way you could use the GetVaryByCustom function in Global.asax.
public override string GetVaryByCustomString(HttpContext context, string custom)
{
var varyString = string.Empty;
if(context.User.Identity.IsAuthenticated)
{
varyString += context.User.Identity.Name;
}
return varyString;
}
What you could also do is get the user information with an ajax request and insert it using javascript, that way you don't need to recache the page for each user. Personally I would go with this approach if the username is the only thing that differs.

ASP.NET Sessions in C#

My goal here is to properly assign a session and retrieve the value stored in that session.
When users come to my first page, a Default.aspx page, I set the session in the code behind.
HttpContext.Current.Session["permissions"] = "Super";
However, I am unable to access this section in a Data Access Class in another file. Am I doing something wrong, or does anyone know a correct way of accessing an already set session from a C# class?
I try to access the session using the same syntax:
String permission = HttpContext.Current.Session["permissions"].ToString();
I am pretty sure , that you can always override this situation. What you are trying to do is not considered a good design principal.
what you can do is to pass the CurrentUser and/or his/her role to the data class by populating a custom property on that class. Within that class you can use the value of this property to work on the user's role.
let me know , if this helps you.
For code samples , you can always look at this SO question
How to access session variables from any class in ASP.NET?

ASP NET MVC Validation Security Issue

I’m starting to develop a ASP NET MVC 3 application and I have sought to follow some good DDD pratices. I have the following situation which would like an opinion.
One of the System features is the creation of activities which one or more users of the system will participate, a meeting for example. Any user with a certain access profile can create new activities, perhaps only the user who create an activity can change her. The question is:
What’s the correct place to insert this rule?
-> In every setter of “Activity” entity? Seems break the DRY.
-> In the repository at the moment of saving the changes? In this case , what would be the correct moment to pass the user permissions?
One more parameter to this method? In the class constructor(In my model, the repositories are interfaces, if I adopt this option,
the dependency would be explicit only in the infrastructure layer where the repositories are implemented?)
-> Controller? It seems to collaborate with an anemic model.
By the way, questions abound... What do you think about?
If you are using ASP.NET Membership you can take advantage of the Roles and Profile providers and use Authorize attributes to restrict access to the actual views where creation or editing occur. For example, the create action could be:
[Authorize(Roles="Activity Admin")]
public ActionResult CreateActivity()
{
return View();
}
Where "Activity Admin" is your creator role. Then your edit could look something like this:
[Authorize(Roles="Activity Admin")]
public ActionResult EditActivity(int id)
{
Activity activity = ActivityRepository.GetActivityByID(id);
if (activity.CreatorID != CurrentUser.ID)
{
return RedirectToAction("Activities");
}
return View(activity);
}
That if statement does the check to make sure the current logged-in user was the user who actually created the activity. The CurrentUser.UserID can be replaced with whatever method you use to retrieve the current logged-in user's unique ID. I usually use the ProfileBase class to implement a class that allows me to track the current user's info. The link below to another SO question shows how you can do that.
How can i use Profilebase class?

What would be the best way to handle a system with multiple user types?

I've been given the task of updating an asp system to MVC3. My main issue is that the current system has 2 different kinds of user, each user has their own user table, and in the current asp site, each user is defined by a number of different session held variables.
Because other systems use the two different user tables, I can't merge them. So what would be the best way forward?
I initally thought about keeping them seperate in the system; having a class type for each user which holds the seperate variables mirrored from their asp counterpart. On login, I could push user type to userdata in the auth cookie, then create an extension method on the IPrincipal to return the user type when required.
This feels a bit of a hack, and as the users will be viewing the same pages, there would be a lot of duplication of code.
Would it be better to create some form of facade before the user repository which would attach a role to a common user object which would identify the user type in the system? I could then check this role and pull out the data, that used to be stored in session variables, when needed.
If I would given a chance to do this I would do it in following way:
Implement asp.net membership provider and import all users into it.
Create two different roles for user types
Use profile provider to store additional properties from user type tables.
This way, you can use combination of role and profile to handle any situation related to authorization and restriction.
I would define an interface with methods common to both users, and have both user types implement the interface. So, if you have something like:
interface IUser { bool CanViewPage1(); }
class UserType1 : IUser { }
class UserType2 : IUser { }
Session["user"] = new UserType1();
Then you can do:
var user = (IUser)Session["user"];
For common operations:
if (user.CanViewPage1())
{
...
}
and for operations where you need the user object:
bool CanViewPage2(IUser user)
{
if(user is UserType1)
{
var ut1 = (UserType1)user;
...
} else if (user is UserType2)
{
var ut2 = (UserType2)user;
...
}
}
The last part can be done via extension methods as well, as you said.
Id suggest to use WIF with custom simple STS server and use claims for user types.
http://msdn.microsoft.com/en-us/library/ee748475.aspx
And for checking this stuff - use custom attribute, or simple - Identity.HasClaim("someclaim name or type").
Also this will standartize your approach for authentication/authorization, which can save some time later=)
If I was building this application from the ground up, i'd differentiate user type by role. With this in mind, I've created an anticorruption class between the User builder and reps. This injects/removes a role (id of 0) to distinguish user type. In future, the client hopes to merge tables, so this seemed the most sensible way forward for now.

SQL role security + custom ASP.Net base page

I'm workng on a new, green-field ASP.Net application. We're implementing a base page which all pages will be, er, based on. The application will be running under Integrate Windows Auth, so I'll have the user's account details. With these, I'll be going to several databases (in which the user will exist) to find out what roles they are assigned to in each db. I'll be holding the role yay/nay in a bool array, and key into it via an enum.
There will be a session object that will hold a few things, and the roles assigned for that user. I'm thinking of making the session object available as a property of the base page, as the code would be something like this:
public SessionObject MasterSessionObject
{
get
{
if (Session["SessionObject"] == null)
{
// Create session object, assign user name, etc.
// Do something with roles...
Session["SessionObject"] = sessionObject;
}
return (SessionObject)Session["SessionObject"]
}
}
In order to control what happens on the (sub-classed) page, I want to provide a CheckSecurity method - e.g. if the user is not authorised to a certain part of a page, it can be hidden / disabled, or they could be booted back to a "not yours" page. The logical place for it is the base page, but seeing as the base page is already exposing the SessionObject that holds the roles permissions, would it not make more sense to Create a DatabaseSecurity type object and have the check on that?
Dealing with the latter approach, I've used abstract base classes to get me so far: I have a DatabaseRoles abstract class which contains the bool array, and a method to retrieve the roles for the user. The concrete implementation holds an Enum (as previously mentioned) to key into the array (in the base class). The abstract class also has the CheckRole method which takes in an int, to which I'm intending use a cast of the enum...
The SessionObject contains several of these DatabaseRoles implementations, and essentially does away with the need for a CheckSecurity in the base page class, leading to code like this in the actual page:
if (MasterSessionObject.SampleDatabaseRoles.Check((int)SampleDatabaseRolesEnum.RoleView))
{
// Do something
}
But, I'm sure you'll agree, it looks sucky...
If there was a CheckSecurity method on the base page, it would have to take a concrete DatabaseRoles object, but also an enum of which role to check, which would also look sucky. And finally, there would be a requirement at a later date to add more databases and their security settings...
I'll add code tomorrow if required... :-s
I dunno, I'm not that thick, but I do have a hard time sometimes binding all this together...
Thank you,
Mike K.
IF you happen to use ASP.Net / ASP.Net MVC, I would say the best place to do this would be via a custom HTTP Module by handling the AuthenticateRequest method & continuing with the request only if the request has been authenticated. There are tons of excellent articles online for this code.
Also - have a look at the Roles & Memberships of ASP.Net - it is pretty good & generally satisfies most requirements or you are always free to extend it. Again - tons of articles on custom membership providers...
unless I am missing something - HTH.

Categories