ASP.NET MVC Authorize by Subdomain - asp.net-mvc

I have what seems like a common issue with SaaS applications, but have not seen this question on here anywhere.
I am using ASP.NET MVC with Forms Authentication. I have implemented a custom membership provider to handle logic, but have one issue (perhaps the issue is in my mental picture of the system).
As with many SaaS apps, customers create accounts and use the app in a way that looks like they are the only ones present (they only see their items, users, etc.). In reality, there are generic controllers and views presenting data depending on the customer represented in the URL. When calling something like the MembershipProvider.ValidateUser, I have access to the user's customer affiliation in the User object - what I don't have is the context of the request to compare whether it is a data request for the same customer as the user.
As an example,
One company called ABC goes to abc.mysite.com
Another company called XYZ goes to xyz.mysite.com
When an ABC user calls
http://abc.mysite.com/product/edit/12
I have an [Authorize] attribute on the Edit method in the ProductController to make sure he is signed in and has sufficient permission to do so.
If that same ABC user tried to access
http://xyz.mysite.com/product/edit/12
I would not want to validate him in the context of that call. In the ValidateUser of the MembershipProvider, I have the information about the user, but not about the request. I can tell that the user is from ABC, but I cannot tell that the request is for XYZ at that point in the code.
How should I resolve this?

Because Authorize is on the same thread as the request you could determine the subdomain by inspecting:
System.Web.HttpContext.Current.Request.Url.DnsSafeHost
Doing so on each call would certainly keep things in order, however this is a purely cosmetic check during authorization. I recommend that you simply look at this information during authentication. Once you know they are requesting XYZ and authenticate them into it, authorization should be only concerned about controlling features/data they have access to as XYZ. Their being from XYZ should be stored as part of the CurrentUser from that point.

Related

Multiple user tiers Google+ API?

The question is fairly simple, but I've yet to find an answer to it. Is it possible to use Google+ API in an asp.net-mvc web app that requires multiple tiers of users?
For example, this app basically needs three sets of users and permissions associated with each: Admins, Members, Guests. Mind you, I've never handled user authentication of any type before, so I'm happy to hear suggestions for other frameworks if you think those would be better.
I think its going to be very hard for you to get three sets of user credentials in a single app.
For you to be able to authenticate as user one your going to need user one to authenticate your application then you will have access to that users data. If you need access to user twos data your going to have to have that user authenticate your application. If you need access to both users the same time its going to be very hard for you to get this access unless they are both using the same computer together.
While it is possible to get a refresh token for user one returned which you could store on your server some place and then use that to access user ones data when user two is on their machine. This becomes a gray area as you are responsible of holding user ones data private especially from user two.
as for your different leaves of users thats just part of your system it should just be a matter of strong the users ids associated with their role within the system.
None of this has anything to do with doing this in .net. You could probably work it all out using the .net client library. Web applications (ASP.NET MVC)

ASP.NET MVC4 How to post and retrieve data unique to a specific user

I have been learning how to use ASP.NET MVC4 and have been getting my head around authenticating users and user roles and posting data using the entity framework to SQL.
However I have not been able to find any guides/resources (maybe I don't know the correct term) for posting and retrieving data that is unique to an specific user. For example how would a user only see the entries that they created if it was a site that stored data that is personal to each user.
What patterns/designs does one use when trying to do this?
Creating a sandbox of data for a specific is usually tied to authentication. You can access this many ways through ASP.Net.
First of all, every user gets identified even if they never log in. They get a session identifier. It essentially creates a small place in memory for this user where you can store any user related information. Think of Sessions as walled gardens for each user.
Session["UserFullname"]
This works, but realize Session is limited by time, so it is very volatile. Utilize it, but don't depend on it.
The next method is to authenticate a User. This is done using Cookies, but usually handled transparently for you by ASP.Net Membership or other authentication providers. To access the authenticated User you just need to use a simple line in your Controller actions.
// User is the property
User.Identity.Name
Both these methods can store information about your user that you would use to query data specific to them.
Select * From Orders Where UserId = *User.Identity.Name*
Note that both Session and User are accessible through HttpContext.Current as well, as long as you are in a web environment.
HttpContext.Current.User
HttpContext.Current.Session
You won't need to access them this way unless you are not inside your Controller, or inside of another class that doesn't already give you access to the HttpContext. I don't recommend this way either, since your code could be used outside of a web application where HttpContext is not available.
I hope that makes sense, and please feel free to ask me questions.
This is not so much about mvc, but more about the problem of relating data to a specific user. You have to ask yourself, how would you identify a piece of data to a user.
The way you would do this is to tie the data to the user in the data store somehow.
In a relational database you would do this by having a User table and using the unique key on that table to insert data into another table such as Order. Order would then have a User Id.
When a user logs in, you could store that ID in session and use that to filter out orders based on the id.

Determining and persisting the current tenant in multi tenant web app in Rails

I'm contemplating a multi tenant application - shared database, shared schema. A tenant identifier (tenant key) associates every row with the right tenant.
What i'm not sure about is how to go about loading the tenant_id into some sort of global scope. How should this happen? I assume that I would parse the domain and then look up the tenant_id based on the domain.
My questions:
Where would the lookup happen in a rails application? In an initializer? Is there a better point to do this?
Once I have determined the tenant_id, what is the best way to persist it - a simple session_id?
I use a before filter for the controllers for this function.
You can also sub-class the controller class to DRY out duplicate code in the controllers.
Be careful to remember that access to a given tenant's information needs to be authenticated on a per-user basis. You need to decide if a given user will have access to more than one tenant. Eg should user "joe" have access to tenants 1 and 2? Or should Joe need a per-tenant login?
The login's authorization should control access to the tenant info. Don't rely on the domain name to grant authorization.
Re: where to persist the tenant_id? Store in the session. If access to the session is expensive (stored in DBMS), then make an in-memory copy as an instance variable during the controller startup. Google for how user_ids are often stored.
You also should determine the user experience for if/when a user wants to access a different tenant.
Added To see which welcome screen to load before the user has logged in, looking at the subdomain name is a good choice. To see which subdomain the incoming request used, parse request.fullpath() Docs. Do this in a controller filter.
Since the authorization comes from the user_id, remember to test the case where joe logs in at tenant1.app.com but only has access to tenant2.app.com
Bonus answer Looking for a templating system that will enable your customers to have full control over their tenancy's user interface? Check out Liquid templates. I was very successful in using them to enable my customers to have full control over their look and feel in a safe way.
Re additional questions in comment
See superuser for configuring the web server. The config is web server-specific.
If you want the welcome screen to not be generic, then you must know from the request url how to customize it. Tenant-specific subdomain is the nicest. If no subdomain, then show the generic welcome--when the person logs in you can determine the tenant and how to customize.
Re helper--if you mean a view helper, then I would not recommend it as the primary place where the tenant is determined. Make the #user and #tenant be light-weight models that you look up once and then retrieve from the session during additional requests for the same session. The models will be used by the controllers and, perhaps, passed to the models. The View layer will also be able to see them and use them as necessary.
If the UI may look/will look completely different for the different tenants, then add a "tenant-display" layer in addition to the view. Eg have the view gather the instance variables, find the right Liquid template, then express the view via the template.
You don't want the view to be computing "if tenant_a then x else y"

AuthorizeAttribute MVC - restrict access to user created content

So I read about how implementing your own authorization routines are bad!
http://www.nashcoding.com/2011/02/05/using-the-forms-authentication-membership-provider-on-appharbor/
And I got scared, because I've been implementing my actions as such (example, preventing access to account details if authenticated user is not the logged in user)
public ActionResult DisplayAccount(int someid){
Account a = context.Accounts.Single(a => a.id == someid);
// currentUserId() returns userid from FormsAuthentication
if (!a.owner == currentUserId()){
/* Not Authorised! */
}
}
Which apparently means it will break if ASP decides to cache my action (so the action doesn't even get executed).
So I'm now looking into using AuthorizeAttribute to do what I need to do, which is
prevent access to an action if not authenticated
check if authenticated user has access to the retrieved resource
However whenever I think about it, I can't think about how to implement the 2nd point. Roles don't work because its on a site wide level, but within the application there users have roles as well (e.g. Owner, Moderator, Contributor, User etc.), and they only have these roles within their respective parts of the application (e.g. owner of thread, contributor to wiki, moderator of forum etc.)
I have run into several examples of overriding AuthorizeCore. I can sort of imagine creating multiple AuthorizeAttribute subclasses for each resource I have (luckily not many), But just by looking at it, does that mean I have to query the database everytime I hit that action to ensure that the logged in user should be able to access that data, then query the database in my action to get the model, instead of doing that in my query?
So my questions are
am I getting too worried about caching too much? Will any of the following happen
website caches user A details, which is rendered on user B's screen?
website caches admin version of a page (with edit controls), and normal user sees cached version?
Using AuthorizeAttribute is a given, but how do I achieve what I need to do in point 2 without having to hit the database prior to the Action? Or what is the best way to achieve it in any case.
Or do I only use AuthorizeAttribute to determine if the user is logged in, and do other checking logic in my action?
Anyway, I hope this post isn't treading on any old paths (I couldn't find anything on this that I found definitive)
Edit: I guess, if I don't enable caching this problem wouldn't occur, is this correct?
Edit: for now, I am going to going to use vanilla AuthorizeAttribute, then check resource level access in my actions, then make sure I don't use caching for any authenticated actions. Hopefully will get more answers for this over the week.
I used the following approach in a recent project, by creating a DataRightsAttribute that used an enumeration for each supported model type. It works by first extracting the id from the route data, formcollection or querystring. Then it queried up the model type determined by the enum, and did the appropriate check to see if the current user is authorized to access it.
Usage was like this:
[DataRights(ModelType.Customer)]
This was used alongside AuthorizeAttribute (which we overrided), and never noticed any problems with caching.

Asp.NET MVC Customer Application

I'm designing (and developing) web software that will allow the general public to sign up for a service, become a customer, and exchange fairly sensitive data.
I'm working through the documentation and the tutorials, and of course the RESTful pattern adopted by the default routing in ASP.NET MVC is to do URL's like this: /customer/edit/3487.
I guess I am a little squeamish about displaying such technical details as customer ID in the URL bar.
What do the smart kids do these days? Does RESTful have to mean "put your record ID's on display"?
Edit: In an ASP.NET WebForm I would have stored this in the session, I think. But I'm finding that this is discouraged in ASP.NET MVC.
Edit:
I do not intend to rely on security through obscurity.
That still doesn't mean its a good idea to give the users any ideas, or any information about the underlying data. Let's say I have an app that's publishing information about the different business in a Chamber of Commerce, to be arbitrary. Once you are logged in, you have an administrative right to click on every business in the directory and see them all - but the application is supposed to spoon feed them to you as search results or the like. Just because the user technically is allowed to access all records, this doesn't mean it should be trivial for you to write a screen scraper that downloads all of my content in a few minutes. As well, the user can just look at customer ID's and make a guess about how many customers I might have. There's lots of good reasons not to display this.
As long is there is proper authentication and authorization being done on server side then displaying ids is not an issue.
Otherwise just try to encrypt the particular id or username in the URL, this way it will be difficult for the attacks.
You don't have to put the Id in the Url, you just need to use a unique value or unique combination of values to find the data you want to display.
I'd think that the actual bussinesses name would be good and also look good in the Url. So you would have something like this:
/Business/View/theouteredge/
Or if the business name is not unique you could use a combination of business name and zip/postal code.
/Business/View/theouteredge/78665/
You would have to write a new route to handle this.
routes.MapRoute(
"Bussiness",
"Business/{Action}/{name}/{zip}/",
new { controller = "Business", action = "Index", Name = "", PostalCode = "" }
);
All this action would need to be secured with the [authorize] attribute, or the controller its self.
If you also decorate your actions with [authorise] then if another user does use the id from another user, they will automatically be challenged for a login.
It's 6 of one and 1/2 dozen of the other as to whether you use an ID or a Name. Eventually they both resolve to a record.
The important thing is to only allow authorised persons to view the data by allowing them to log in.
I've got a site which has sensitive data but only if you are the holder of that info can you see it and I do that by decorating my actions and checking rights etc.
I think that putting an ID in a url is fine -- as long as it is a Surrogate Key. The key has no value, except to identify a record. Just make sure that the requester is authorized before you send sensitive data back to the client.
Update:
I can see how having a number as part of your URL is undesirable. After all, a URL for a web app is part of the user interface, and exposing such internal details can take away from the UI's elegance. However, you are faced with limited options.
Somehow, you have to identify the resource that you want to get. The crux of REST (IMO) is that a request to a server for a particular resource must be described entirely by the request. The key for the item you want has to be encoded into the HTTP GET somehow. Your options are: put it into the URL somehow, or add it to a cookie. However, adding a key to a cookie is frowned upon.
If you look at this site you will see the question id in the url. If you view your profile you will see your username. So you would probably want to use usernames intead of an id.
If you're really concerned about it you can use a Guid, which isn't very user friendly but would be very hard to guess. :)
If you use some other way than customer id simply because you're concerned about security, then that means you're using security through obscurity, which is a bad idea. Proper authorization would require something like you either 1) have to be logged in with that customer id, or 2) be logged in as an admin, to have that request succeed.

Resources