Accessing the Database via JPA with the Enduser's Credentials in Java EE - sql-server

I am working on a JavaEE project with WildFly, Hibernate (JPA), C3P0 and a MS SQL Server database.
The database is a legacy database with more than a thousand Database Objects like Stored Procedures, Functions, Views, Triggers and so on. All these database Objects have fine grained Permissions set on User Role level.
Now I need to access this database with a JavaEE Web Application. My Problem is, that the usual JPA configuration let me set only one Username/Password for the Database in the configuration file. I can not find any way to configure the JPA layer so that will access the DB with the Enduser's Login.
I ended up to create one EntityManagerFactory per User by calling
EntityManagerFactory entityManagerFactory =
Persistence.createEntityManagerFactory(properties_with_credentials_here)
once per user.
The problem with this approach is, that this will basically instantiate the whole JPA layer per User and eat up way too much memory. I am not using any sort of Cache layer, of course. The memory is used just for the Entities meta information (which is a lot).
Now my original question: Is there any 'standard' way in JavaEE (JPA) to access the database layer with the Enduser's Login and Password?
I can not believe that I am the first person to encounter this situation. It seems to me, that 'impersonation' is quite normal in .net Web Applications. So there must be way to do this in Java, i guess.
Any comments or hints or new approaches are highly welcome.

The 'standard' way in JavaEE is to have an application user for accessing the database and achieve user-based access-rights through roles in your application.
If you need to rely on existing database user, your only chance is to establish a connection per user or per request. The entity manager would then indeed consume some memory as it's designed to be your application's persistence context (and thus some sort of cache).
Maybe you can have some trade-off here by accessing those parts which really have to be user-based by plain JDBC and potential execution of database procedures and others by some application user with extended rights which ensures the necessary user restrictions programmatically.

Related

How to restrict data access based on user login

I am a former Lotus Notes/Domino developer, learning the Microsoft stack. I am building a web application with a SQL server back end. I want to build a basic CRUD application where users register, then login. They should be able to work with data they created or that has been shared with them. I am unsure how to achieve that result.
One of the cool features of the Domino database was the ability to add reader and or author fields to each record with user IDs, or roles and the server would automatically filter out those records when a user accesses the database. So if the user opened a View or Queried the database, the server would never let them see records they were not assigned access to.
Does SQL server have similar functionality? I've seen some information on row-level security, is that the best way to secure data? If not, what is the best practice to secure data so users can only see their data?
Thanks for any help you can offer.
Yes. SQL server has Row Level Security:
Row-Level Security enables you to use group membership or execution
context to control access to rows in a database table.
Row-Level Security (RLS) simplifies the design and coding of security
in your application. RLS helps you implement restrictions on data row
access. For example, you can ensure that workers access only those
data rows that are pertinent to their department. Another example is
to restrict customers' data access to only the data relevant to their
company.
The access restriction logic is located in the database tier rather
than away from the data in another application tier. The database
system applies the access restrictions every time that data access is
attempted from any tier. This makes your security system more reliable
and robust by reducing the surface area of your security system.
But it's more common to embed the authorization logic in a server-side application like a web server or web API. Row-Level Security is more common where users connect directly to the database, like in reporting and analytics, and client/server desktop applications.

Using Windows Authentication with Sql Server with Windows applications

Microsoft recommends using Windows authentication when connecting a Windows application to an SQL server database.
http://msdn.microsoft.com/en-us/library/89211k9b.aspx
I understand this to mean that the database must have a user with enough permissions to manipulate data and that user links to the currently logged in Windows user. If this is true, how do I prevent the user from bypassing the application and simply modifying data directly in the database?
It seems like I am stuck between using Windows Authentication and potentially allowing users to modify data directly in the database, or attempting to hide the connection string password somewhere so only the app can modify this data.
If you're that concerned about it, you can implement a logon trigger on the server that for certain people (e.g. members of a certain Windows group), they can't log in unless the application name has a certain value. Note that this is weak security since it's pretty easy to set the application name (even in SSMS). It can/will slow down the logon process, though. So keep that in mind if that's a concern for you.
Alternatively, you can have your application authenticate to and interact with an application server, after which the application server connects to and interacts with the database. The application server can run as a service account, to which you'd grant the permissions you need. This way, the end users' accounts aren't in the database to do raw DML against the db.
But I agree with the other answer here: stored procedures are the classic answer to this question.
It is possible to create stored procedures / views etc and only allow the user permission on those. This prevents the user from accessing the database structure directly, and you maintain control over what the user can do (via creating the functionality in the stored procedures / views). If using windows credentials, I think that this would be the best solution.
This site explains how to grant there permission on stored procedures.
http://msdn.microsoft.com/en-us/library/ms345484.aspx
Here is the list of options, for posterity:
Windows authentication only
Pros: simple, No secret to hide.
Cons: user can easily modify data bypassing your app
Password in connection string
Pros: simple, prevents user meddling in your db's.
Cons: have to hide a password yourself, which is always the worst option.
Sprocs access
Create sprocs to access your data, grant access only to those sprocs. No one but the dbo can alter tables.
Pros: Tightest control over what both the user and the application can do to the data
Cons: Higher coupling of database and application; more expensive than the first 2 options.
Proxy
Create a second executable, whether a web or a windows service, with which your GUI application communicates. The 2nd executable can run with different, securely hidden credentials (IIS, Windows Services).
Pros: Decoupled database and executable, securely hidden secrets.
Cons: By far the most expensive solution.

WPF with arbitrary, unknown databases - Client/Server or Desktop app?

My company is planning to turn an older Winforms application into a WPF/Silverlight Client/Server app.
The idea of having a small server app is to have a list of the accessible data bases combined with the user type that may access each of the databases, instead of having to manage databases in each client's admin control. Additionally, it would be great if the SQL request would be handled by the server which would then return the result.
The app is supposed to work on a arbitrary set of databases which will be "registered" with the server and users get a list of databases according to their authentication rights. They can then do practically everything on those databases what one can imagine. The system should be able to handle up to 2 million rows.
The databases are very different, there can be many of them, they can be MS Access, Oracle, SQL Server etc., so no way for me to specify them all before. On top of that, communication with a SQLite cache is needed.
I already have everything I need for the SQL queries from the Winforms app.
I was thinking:
1) A simple WCF server specifying in a config file the available databases per user type.
2) Interface that specifies all necessary SQL queries that can be made to the server.
3) Client...
The idea is:
a client-server application, where the client uses WCF services to execute SQL queries (INSERT, UPDATE, SELECT, etc.) on tables by invoking services methods.
The service should ideally be consumable for both the WPF and the Silverlight app.
Is that the way to go? Which exisiting technologies might I want to make use of regarding formats, communication, services etc.
If that is problematic, I would consider going back to a desktop app, but then how to ease the user type/database access problem for each client?
I would stick with ADO.NET and start with the DbProviderFactory class. This will let you determine the proper database access based on information supplied by the provider using the Factory Design Pattern. So instead of having to create a specialized objects for each database type and database, you can abstract that logic with the DbProviderFactory.
Here's a link that shows some examples: http://msdn.microsoft.com/en-us/library/wda6c36e(v=VS.100).aspx

SQL Server Authentication or Integrated Security?

We have some corporate intranet users using a WinForms app to work on a system with SQL server behind. Integrated Security is setup, allowing all users update and delete permissions, where application security limits how and where table updates take place.
However, some users are power users with SQL query tools at their disposal, and access the DB directly for building reports. However, with integrated security, they have default update rights on tables where they should not have, as the application apply rules to the updates.
Is this an example of where it's more appropriate providing the app with a central SQL authenticated login, whilst users get read only rights for integrated security?
As Jon mentioned stored procedures would give you the protection over direct table modifications. There are other options too. You can use SQL Server's "Application Role" (via sp_setapprole proc). This enables you to continue to use a separate ID for everyone but only at application connection time (through the front-end) are the user's rights elevated.
A major downside to using a shared ID is you lose track of who is submitting SQL to the server though if they're all internal you can get to the machine name.
Something else is concerning though. It sounds as if your users can connect to the database and run queries at will. You run a major risk of downtime in the application due to user behavior in the directly connected SQL sessions. If you can pull it off you may want to try to have a reporting database created that is updated at intervals that your business can tolerate, i.e., daily. HTH
I presume from the way that you've worded your question that your app executes sql statements directly. If you could refactor it so that it executes stored procedures, you could grant exec rights on the procedures and deny direct updating of the tables. This might not be possible though, depending on what your app does.
sql authentication is one option. Stored procedures are another. However, building more granular roles for assigning just the appropriate permissions to just the appropriate user types is where you should really be looking.
Additionally, I would really avoid giving these users direct access to the DB at all. Security reasons aside, it doesn't take much for a user who isn't proficient in SQL to accidentally execute a query that will swamp your database server and create an effective denial of service. Even pros can do this accidentally from time to time.
Instead, give them access to a reporting services or analysis services type solution, or use replication to give them access to a clone of the data. This way your production system is protected.
Personally I would do all application data access through stored procedures. I would set Integrated security to only allow users to run the SP's and not manipulate the data directly.
Advanced access can be given to DB admins to manipulate the data directly when needed.
Group based permissions will provide you with much more flexibility for access rights, and less administrative burden when controlling these with integrated security.

What are the best practices on MS-SQL when Windows Authentications is not an option?

What is the best option for a windows application that uses SQL server authentication? Should I create a single SQL account and manage the users inside the application (using a users table). Or should I create a SQL server account for each user. What is your experience? Thank you!
Depends on whether the username/password for the SQL server would be exposed to the user, and whether that would be a problem. Generally for internal apps (in smaller organisations), one would trust the users not too log in directly to the sql server. If you have a middleware layer (ie webservices) the password can be hidden from user.
I prefer to use a general login for the DB and manage users in the application. Even if you do create a login to sql for each application user, they could still connect directly, so why not just use a generic sql login that is easier to manage. This is of course assuming all users have the same accesses.
One good practice, if the users potentially can get direct access to the db, would be to grant access only through Stored Procedures and not directly to tables, so that only certain actions can be performed. Steer away from writing business logic or security checks (except basic ones) within the stored procs.
One way I would solve your problem is to write some webservices that check security and does your CRUD (via datasets, etc), but again it depends on the app and environment.
In summary if you have a middle layer or all users have the same access manage the user within the application and use a single user login. Otherwise use a login per user or role.
One option that I have used in the past is to use the ASP.NET Membership Provider. It makes authentication a breeze to use. The only drawback that I saw was that it added a bunch of tables to your database.
The code for using it is very straight-forward.
Here's a blog post about using this in a Windows app. http://msmvps.com/blogs/theproblemsolver/archive/2006/01/12/80905.aspx Here's another article with more details. http://www.c-sharpcorner.com/UploadFile/jmcfet/Provider-basedASP.NET10162006104542AM/Provider-basedASP.NET.aspx
Here's another article that talks about using it with Windows applications: http://www.theproblemsolver.nl/usingthemembershipproviderinwinforms.htm
Google for "ASP.NET 2.0 Membership Provider", and you will get plenty of hits.
What about having SQL accounts based on the level of permissions needed for the task. For example you could have a read only account just used for reporting if your system has a lot of reporting. You would also need an account what has write access for people to change their passwords and other user admin tasks.
If you have situations where certain users are only going to have access to certain data I would have separate accounts for that data. The problem with using 1 account is you are saying that there is no SQL injection anywhere in your application. That is something everyone would strive for but sometimes perfect security is not possible, hence the multi-pronged approach.

Resources