Using C# and MySQL, is it possible to create individual user accounts to access the database, and only allow users to view/modify/delete their own data?
-
I guess the idea is hardening the application in case the C# code contains flaws. Therefore it may look like a good idea to establish the database connection as the user. One big problem I see here is, that you cannot just easily pool and reuse database connections like that. The connection of user Joe cannot be reused by user Jane. Establishing the connection on each user request can be costly (even when application and database run on the same system) and can completely stall your server when you are dealing with a lot of simultaneous requests.tiguchi– tiguchi2014-10-22 19:05:30 +00:00Commented Oct 22, 2014 at 19:05
1 Answer
In SQL you can grant privileges for users or user groups to all SIDU access types (Select, Insert, Delete, Update) on Tables and Views.
If you are talking about a finer granularity at the row level, I think you will need to store this information somewhere; the most direct way is to add something like an owner field and/or a privilege field to each Table you need to restrict.
Another way would be be to create one or more Tables which hold keys of restricted or of non-restricted records or contents, like projects or regions..
The first solution would be not terribly hard to code, provided you have a well-designed concept of ownership & privileges, sufficiently flexible both for now and for later on.
You would add a layer of access logic, which adds an extra where clause, in the simplest case like: ..AND WHERE table.ownerID = @ownerid or the like to every SELECT. And for every INSERT it would fill the field with the current user ID or group ID and/or his current access rights..
Plan for user groups, as one user will often need to do the work of another one, at least partially..
Extra privileges-tables will need even better planning..
Also consider tools & functions to manage these data..
Update
Since it is clear now, that you want to set up a Web based data access you could either create separate Tables for each user with the user name or a hash or encrypted version of it, used as a prefix to each Table; or, more common, you can set up a separate DataBase for each user, again, with a DB name somehow derived from the user name or user ID.
The versiom with a separated DB for each user is easier to write, since after the login, everything will work the same for each user, i.e. no need to inject anything into the SQL.
The only possible consideration may come in with technical or monetary restrictions coming from the provider. Some packages only allow for a small number of DataBases. In such a case the Table-prefix method is the next most likely solution.
So the number of users you expect may be a deciding factor, too..