Best practices to convert a NHibernate app as multi-tenant? - asp.net-mvc

I have a simple ASP.NET MVC + OpenID + NHibernate app (on top of MSSQL Server DB). The app is strictly single tenant and supports multiple users with only 2 roles (Admin and User).
I would like to convert this app into a multi-tenant app. My requirements are limited: I just need to introduce the notion of Accounts, each account having its own set of users and behaving exactly like the original non-multi-tenant app. There is no interactions between accounts.
What are the best practices to do this migration the most simple way? In particular, I am can manually update all entities and repositories with an Account_id field, and upload the logic too. But, I am wondering if there are no smarter approaches that would somehow abstract this aspect.
Ps: the app is very light, I do not wish to introduce a new DB instance for each account.

Probably the best thing I could think of is to embrace the Filter feature of NHibernate. It allows you to easily enable a filter on the query you're running and you can optionally enable them on tables that are setup to be multi-tenanted

Related

Link between separate Application database and Users database in ASP.NET MVC5

I’m currently building an ASP.NET MVC 5 EF6 blogging web application.
I have two databases and contexts :
-a database for the actual data of my application (blog posts, blog categories, tags, etc) .
-a database for authentification and membership purpose (users and roles).
I am able to authorize a given user the right to add/edit/delete blog posts, using the authorize attribute in the BlogPostcontroller :
[Authorize(Roles=”Administrator,Author”)]
and it works pretty well..
MY GOAL : let’s imagine I want to grant an user the right to add/edit/delete a subset of all the blog post or blog categories (let’s say only to the “Cooking” and “travel” blog categories).
I started to think about creating a navigation property between the user and the blog category entities, but apparently foreign keys between two separate databases are not supported by the entity framework.
Do you guys have an idea of a walk-around for this problem?
Your help will be much appreciated.
This is what you need.
http://typecastexception.com/post/2014/02/19/ASPNET-MVC-5-Identity-Implementing-Group-Based-Permissions-Management-Part-I.aspx
Basically, the privileges is what you will need to configure and associate user roles.
If you want to keep your authorization data separate from your business data, i.e. in 2 separate databases where one contains user information and permissions and the other contains your blog data, then what you actually want to achieve is externalized authorization. That's actually a great intent. After all, do you keep authentication information with your application data? Of course you don't.
Different frameworks give you externalized authorization capabilities. For instance, in .NET, you have claims-based authorization.
You can also take a generic approach and use XACML, the eXtensible Access Control Markup Language. XACML uses attributes (it's an attribute-based access control model as opposed to simply role-based) and combines them into policies & rules to define what can happen. For instance, with XACML, you can write the following rule: A user can edit blog posts he/she owns.
In XACML, you have the notion of an authorization engine called the Policy Decision Point (PDP). That PDP links together all the information it needs to make decisions. In your case, it will use the 2 separate databases and create the relationships on them.
Now, if your use case is simple, using XACML might prove too much. In that case, just use claims-based authorization.

MVC 3 ASP.NET and Connecting 2 Databases

Currently working on a web application in ASP.NET, MVC3 that allows people to view items, and change anything. This is with using my own database that I have created, but this I have found is good for generally viewing anything on the application but not good for security purposes to prevent them seeing particular things, and I do not want to waste my time removing tables and re-adding them.
So... Is there a way to communicate between the ASPNETDB and my own Database which would allow users to login to the web application but also sign up as a customer?
I would solve this using database roles, and only grant the appropriate roles to the user used to login to the two databases.
You have very granular control over what you want a db user to have access to.
Read up on databases and db roles

How should I do authentication in a ASP.Net MVC site?

I have a site which has an area that requires authentication. Right now I use the roles attribute on all the controllers in that area, and I run a query to retrieve that users ID, and all their settings.
It seems like a code or design smell to me that I am retrieving the userid and settings each time a controller in that area loads up? I'm not sure if I should be using sessions, or if ASP.Net MVC 2.0 provides some unique way to handle this. Another concern is security.
Overall, I don't really know which way to turn. Design wise I would like the userId and settings retrieved only once when the user logs into the area. Right now I grab the userId each time a controller loads up, and then if required, I query the database for their settings each time as well.
One of the rules about security is that you shouldn't try to do it yourself. There are many pitfalls in doing an authentication system correctly without leaving loopholes or backdoors. Thus, in that regard, you might consider the SqlMembershipProvider that comes with .NET. It can be used with MVC and provides the means to get roles and the current security context, is easy to setup and configure and will be more secure than rolling your own.
If you are not using SQL Server, you have a couple of choices. One solution would be to use something like SQL Server Express or SQL Server Compact Edition to maintain the credentials. Another solution would be to mimic the SqlMembrershipProvider database schema and then write a custom provider that communicates with that schema.
The last choice would be to write a custom MembershipProvider class. While this is still rolling your own, it forces you into the structure of the MembershipProvider so that you can swap it out at a later date for a different one (e.g. ActiveDirectoryMembershipProvider) and provides a common interface for interacting with credentials and logins which for example enables easy use of the built-in Login control.
If you are already using a MembershipProvider and are asking about storing additional user-specific data, then I would suggest the SqlProfileProvider with all the caveats I mentioned above about the SqlMembershipProvider. the ProfileProvider provides a structure for maintain user-specific data with the currently logged on user.
For more information:
Introduction to Membership
Implementing a MembershipProvider
ASP.NET Profile Providers
You could also implement a custom identity. They are very easy to implement, and they let you store whatever user information you want in Identity, which is then stored in the cookies that Identity puts down, so you're not hitting the DB every time to get that info.
Just create a new class that inherits from GenericIdentity, and you'll be on your way.
You of course have to be careful how much info you put there since it's in a cookie, but usually user related information in the case you're talking about here isn't so big.
We use a custom identity to store a few bits of info about the user, and it works out pretty well.
You could store an object in session that holds all the required user information. You will just need to add a property in the Controllers, Views or other base classes where you want to retrieve the user information/profile. This would be the authorisation info as opposed to any authentication info (eg Forms authentication)
You might try "Windows Identity Foundation". I've been using it on one of my projects for a while. It allows for "claims-based authentication", which basically means that you get to designate "claims", strings of information that describe the user when she logs on.
Once logged on, the user's claims can be read from the HttpContext.Current.User field. You can also use "Role" claims that seamlessly integrate with a role-based authentication schema; meaning that you can give the user a "manager" role claim and then use `if (User.IsInRole("manager")).
As an added bonus, WIF makes it very easy to re-use your login screen in other applications.
All in all, it's very flexible, but the documentation is very poor. I've asked and answered a number of questions about "Windows Identity Foundation" on StackOverflow.
We have done this quite a few times in the past. Similar to what Thomas mentions, what we have generally done is implemented a new Membership provider based on the Microsoft SQL Memberhsip provider to do this. We inherit from the base MembershipUser class and add any custom properties we would want to have on the user object. You have to implement a database read for the Membership provider on the GetUser implementation, so you can consolidate your extra properties you need into that database read.
If you are using SQL server, Microsoft has release the 2.0 code for it. You can get more information at Scott Gu's blog.
http://weblogs.asp.net/scottgu/archive/2006/04/13/442772.aspx
If you want to start from scratch, they also have good resources at MSDN.
http://msdn.microsoft.com/en-us/library/f1kyba5e.aspx
and
http://msdn.microsoft.com/en-us/library/6tc47t75.aspx
Once you have implemented your provider, you can then add the Membership user to the Items collection of the current web context to get access to it from your code. The non extended properties from the base base user class are also available on the Request thread like normal.
With the Microsoft release of the 2.0 version of the source code , we found it helped us alleviate some concerns that exist about reinventing. Another thing to consider for your implementations is based on your scenario, you can bypass implementing some of the code. An example of this would be the CreateUser code if you are hitting a back end system that already has the credential information.
It seems like you're relatively happy with your authentication process but you want to explore other options for session/settings.
My suggestion has to do with settings only (roles, preferences, etc.)
In my opinion, having to traverse the whole technology stack from UI to Business Tier to DB tier to DB is sometimes a bit overkill.
For data that isn't likely to change during a session, this adds a lot of overhead... There are potentially several data transformations happening (DB (Relational Format) -> ORM -> Web Service XML Serialization -> Web Tier deserialization).
You might consider a session system that doesn't rely on a heavy RDBMS system or on the ASP.NET Caching / Session model. There are options that are very performant and that scale well.
You could use RavenDB by Ayende Rahien (Built for .NET). Its main goal is to provide low latency, high performance access to schema-less JSON documents.
Using this solution, you would set up ravenDB in the web tier so that access to data is very quick.
The first time you authenticate and retrieve settings, you would store the userID and settings information in this session DB.
Every time you load your controller after that, the settings data is accessible without having to go back to the RDBMS.
This DB could also be used to cache other web related data.
As for security, the settings data makes it to the web tier regardless of the method you use. This solution would be no more or less secure than the other options (more secure than an unencrypted cookie). If you needed to, you could encrypt the session data - but that will increase your overhead again.
Just another one of the million options to consider.
Good Luck,
Let us know what you decide!
Patrick.

Adopting the "aspnet_ ..." sql tables from ASP.NET MVC

I'm just starting a new project on ASP.NET MVC and this will be the first project actually using this technology. As I created my new project with Visual Studio 2010, it created to my sql server a bunch of tables with "aspnet_" prefix. Part of them deal with the built-in user accounts and permission support.
Now, I want to keep some specific information about my users. My question is "Is it a good practice changing the structure of this aspnet_ tables, to meet my needs about user account's information?".
And as i suppose the answer is "No." (Why exactly?), I intend to create my own "Users" table. What is a good approach to connect the records from aspnet_Users table and my own custom Users table.
I want the relationship to be 1:1 and the design in the database to be as transparent as possible in my c# code (I'm using linq to sql if it is important). Also, I don't want to replicate the usernames and passwords from the aspnet_ tables to my table and maintain the data.
I'm considering using a view to join them. Is this a good idea?
Thanks in advance!
EDIT: From the answer, I see that I may not be clear enough, what I want. The question is not IF to use the default asp.net provider, but how to adopt it, to my needs.
I would create custom membership provider and omit those aspnet_x tables completely. I've seen what happens when one joins these tables and custom ones with nhibernate mappings - pure nightmare.
If you are choosing to use the Membership API for your site, then this link has information regarding how to add extra information to a user.
I was faced with the same scenario recently and ended up ditching the membership functionality and rolled my own db solution in tandem with the DotNetOpenAuth library.
Using the membership system in asp.net has its advantages and drawbacks. It's easy to start, because you don't have to worry about validation, user registration, resetting passwords. (Be careful if you plan to modify the table structures, you will have to change them in the views/store procedures generated
However there are drawbacks to using Membership
You will have to maintain 2 separated systems, because the Membership API has restrictions, for example, you cannot perform operations inside a transaction with the membership api. (Unless you use TransactionScope i think, but you don't have other choices).
A valid alternative would be to implement your own security validation routines, and using FormsAuthentication. This way you will have total control over your users tables, and remove dependency to the membership API.

How should I handle Authorization/Authentication in my Asp.net MVC app?

I am creating an Asp.net MVC application and I'm currently using the built in Authentication/Authorization code that comes with the sample MVC app. For the most part this is working ok and I kinda understand what's going on.
What's concerning me though, is that now I kind of have my users stored in two different tables across two databases. i.e. I have users in my App's database that represent the "Customer" entity in the application, as well as the "User" in the Authentication database that's used to log in someone to the app.
Should I take the logged in user's User.Identity.Name value and do look up in my Customers table or should I merge them into one table? What's the best practice way of handling this?
Please forgive my ignorance - this is the first time I'm working with a system like this.
Any feedback is greatly appreciated!
It's helpful to think of credentials and the records that associate a person to application data as two very different things. Depending on the application, your Customer may not have credentials to log in or you may have an administrative User that logs in but isn't related to your application data.
Separate credentials are also useful if Users access more than one application with different rights for each.
For these reasons, I'd keep Customer and User separate and look one up from the other where appropriate.
You can extend the .Net Membership Provider to take all the information you want and post back in a single model I think.
See this one ASP.net Profiles and Membership - Custom Providers or should completely I roll my own?
And this one How to implement ASP.NET membership provider in my domain model

Resources