Spring - Facebook integration without storing connections - java

I've been trying to integrate my application with facebook for a very long time, but I can't find any good example how to do this without storing user connections. I know that there is project called spring-social and I can integrate it by implementing SocialConfigurer methods , but it requires UsersConnectionRepository, which is a bad idea.
I also don't want to redirect my requests since I already have facebook access id ( it's passed from other application ). I simply want to log in and create user in my db ( if didn't exist before )
How can I do this ?
Ideally I would like to have something like this :
facebookService.getUserDetails(facebookAccessId)
facebookService.getPhotos(facebookAccessId, ... )
No sessions etc

So you just want to create a new user in your DB if it does not exist right? And no open connection? Then you can use JPA (When you are working with Java) or Entity-Framework (.NET).
In JPA you can work in combination with objectdb. http://www.objectdb.com/
It's as simple as it sounds. (You can handle all with JPQL (SQL for JPA))
When you are also working with Maven you can implement JPA & Objectdb with this code: http://m2.objectdb.com/

Related

Restrict URL access control by id in jhipster

I have a problem that each user can retrieve other users data from URL.
For instance, I have a rest api like this:
#GetMapping("/getFindByPersonId/{perId}")
#Timed
public List<ComboVahedAmoozeshi> getFindBySkhsIdCombo(#PathVariable Long perId){
return comboVahedAmoozeshiRepository.getFindBySkhsIdCombo(perId);
}
After authorization, each user can change id and get other users data like the image below:
Is there any suggestion to restrict each user to don`t have access to call the method? Or Jhipster have any options to use UUId to hide id?
Thanks from #atomferede for the right answer. I have to add jhi_user_id in other entities and used #postfilter annotation to limit user's access to data.
Although, maybe it`s a good idea to have this option in jhipster generator to enhance the security level and faster implementation.

How to properly filter Spring REST data

I have a Spring Data REST service with a single #Entity and Repository. When I run
$ curl localhost:8080/api
I get all the data stored in my repository and it works as expected. I also have a small React front end and I display that data there.
My question is: Where should I filter the data? For example maybe I want all the entries with id > 10. Should I just filter the response in my front end or should I make the REST call in such a way that it returns just the required entries?
If I should do the latter, then how?
Thanks.
Filter in the backend or - more specifically - with the database query.
The database is optimized for those operations. Thus, you can reduce the data transmitted from the backend to the frontend and reduce the load on the frontend since only data that is requested by the user will be processed by the frontend.
Another benefit is that if you have multiple frontends (e.g. website & mobile app), you have to implement filter functionality only once (in the backend) instead of twice (in each client)
If it is always the case, why would you put extra burden on front-end shoulders to filter the results all the time?
Implement a new method which returns the desired results(e.g id > 10) and annotate it with #Query and provide JPQL or native query inside it
#Query("SELECT c FROM Customer c WHERE c.id > 10")
Collection<Customer> findAllActiveCustomers();
However, if you choose native query do not forget to put nativeQuery = true inside #Query

Create users in Oracle, MySQL databases using Springboot - Spring Data JPA

I am very new to Springboot and Spring Data JPA and working on a use case where I am required to create users in different databases.
The application will receive 2 inputs from a queue - username and database name.
Using this I have to provision the given user in the given database.
I am unable to understand the project architecture.
Since the query I need to run will be of the format - create user ABC identified by password;
How should the project look like in terms of model class, repositories etc? Since I do not have an actual table against which the query will be run, do I need a model class since there will be no column mappings happening as such.
TLDR - Help in architecturing Springboot-Spring Data JPA application configured with multiple data sources to run queries of the format : create user identified by password
I have been using this GitHub repo for reference - https://github.com/jahe/spring-boot-multiple-datasources/blob/master/src/main/java/com/foobar
I'll be making some assumptions here:
your database of choice is Oracle, based on provided syntax: create user ABC identified by password
you want to create and list users
your databases are well-known and defined in JNDI
I can't just provide code unfortunately as setting it up would take me some work, but I can give you the gist of it.
Method 1: using JPA
first, create a User entity and a corresponding UserRepository. Bind the entity to the all_users table. The primary key will probably be either the USERNAME or the USER_ID column... but it doesn't really matter as you won't be doing any insert into that table.
to create and a user, add a dedicated method to your own UserRepository specifying the user creation query within a #NativeQuery annotation. It should work out-of-the-box.
to list users you shouldn't need to do anything, as your entity at this point is already bound to the correct table. Just call the appropriate (and already existing) method in your repository.
The above in theory covers the creation and listing of users in a given database using JPA.
If you have a limited number of databases (and therefore a limited number of well-known JNDI datasources) at this point you can proceed as shown in the GitHub example you referenced, by providing different #Configuration classes for each different DataSource, each with the related (identical) repository living in a separate package.
You will of course have to add some logic that will allow you to appropriately select the JpaRepository to use for the operations.
This will lead to some code duplication and works well only if the needs remain very simple over time. That is: it works if all your "microservice" will ever have to do is this create/list (and maybe delete) of users and the number of datasources remains small over time, as each new datasource will require you to add new classes, recompile and redeploy the microservice.
Alternatively, try with the approach proposed here:
https://www.endpoint.com/blog/2016/11/16/connect-multiple-jpa-repositories-using
Personally however I would throw JPA out of the window completely as it's anything but easy to dynamically configure arbitrary DataSource objects and reconfigure the repositories to work each time against a different DataSource and the above solution will force you to constant maintenance over such a simple application.
What I would do would be sticking with NamedParameterJdbcTemplate initialising it by using JndiTemplate. Example:
void createUser(String username, String password, String database) {
DataSource ds = (new JndiTemplate()).lookup(database);
NamedParameterJdbcTemplate npjt = new NamedParameterJdbcTemplate();
Map<String, Object> params = new HashMap<>();
params.put("USERNAME", username);
params.put("PASSWORD", password);
npjt.execute('create user :USERNAME identified by :PASSWORD', params);
}
List<Map<String, Object>> listUsers() {
DataSource ds = (new JndiTemplate()).lookup(database);
NamedParameterJdbcTemplate npjt = new NamedParameterJdbcTemplate();
return npjt.queryForList("select * from all_users", new HashMap<>());
}
Provided that your container has the JNDI datasources already defined, the above code should cover both the creation of a user and the listing of users. No need to define entities or repositories or anything else. You don't even have to define your datasources in a spring #Configuration. The above code (which you will have to test) is really all you need so you could wire it in a #Controller and be done with it.
If you don't use JNDI it's no problem either: you can use HikariCP to define your datasources, providing the additional arguments as parameters.
This solution will work no matter how many different datasources you have and won't need redeployment unless you really have to work on its features. Plus, it doesn't need the developer to know JPA and it doesn't need to spread the configuration all over the place.

Does Playframework (Ebean ORM ) support managed enties

I started working on a new project using Playframework and thought to try using it with Ebean ORM. What i am wondering now is if Play with the Ebean implementation supports managed entities and if so ..how? Take this example method from the controller:
#Transactional
public Result changePassword() {
Long userId = Long.valueOf(session("id"));
User user = User.find.byId(userId);
user.setName("John Doe");
}
Is there any way to persist the changes to the database when the transaction ends? Currently what i am doing is calling user.save(). This is not much but working with JEE/JPA (and recently Dropwizard) i got used to have my entities changes persisted when the transaction ends.
No, I don't think Play natively supports something like auto save transaction as you want. Explicit save method is the only option.
Ebean.save(xyz);
General suggestion on your code, From Play 2.3.x, In your case, No need to annotate or explicitly mention the transaction, if Save is the only action on User EBean. By default each action on EBeans will be executed in separate transactions. Can specify the transaction explicitly if multiple actions need to be executed in single transaction.

Java – efficient, database-aware instance-level authorization?

In a JPA app I have a scenario in which the app is to
list all accounts the given user is authorized to withdraw from
I have the Account entity and a many-to-many table that lists what authorizations each user has on each account – to implement the above scenario, the app currently just inner-joins the two tables – which is quite quick.
Now, I was planning to add an explicit authorization layer (based on apache shiro / spring security / other) to insulate authorization-related logic from the rest of the code, but...
There are some 10k Accounts in the database and the "average" user is granted "deposit" on all of them, "view" on one half of them and "withraw" on just a few.
Does any security framework allow to implement this scenario efficiently?
Ie: is any of them able to "decorate" a JPA query of the type "select a from Account a" (or the equivalent SQL) and thus get the list of accounts without loading all user grants from the database, and by all means, without having to retrieve all accounts?)
Have a look at Apache Shiro.
It allows you to pull in the User authorization once and cache it for the duration of the session. In addition, if all users can VIEW all ACCOUNTS then you wouldn't need to explicitly define this which would significantly reduce the overhead.
If your solution requires realtime access handlers Shiro has a way to reset the Permissions dynamically during runtime too.
Shiro allows you to implement a typical RBAC and define permissions like this:
domain:action:instance
So in your case permissions might look like this for a user:
account:deposit:* // deposit all accounts
account:view:1111
account:view:2222
account:view:3333 // view on these accounts
account:withdraw:5555
account:withdraw:6666 // withdraw on these accounts
In code you can then do something like this:
if (SecurityUtils.getSubject().isPermitted("account:withdraw:"+account.getAccountNumber() ) {
// handle withdraw
}
Shiro also has annotation driven permissions for additional abstraction.
EDIT
The Shiro permissions is the end result, not where you start. I used a set of tables representing mappings of the user-to-role and role-to-permission along with other mappings to instance. After AuthN its usually a simple set of queries indexed by the User PK to build up the data structures needed to render the permissions.
I have a hope that this is one of the possibilities to implement your requirement with Spring-Security.
Write custom org.springframework.security.acls.Permission like
ViewAccount,DepositToAccount,WithDrawFromAccount
Write custom
org.springframework.security.access.PermissionEvaluator Override
hasPermission(Authentication userAuthentication,Object
accountObject,Object oneOfThePermission) to check if the user has
the defined permission on the accountObject
Get reference to JPA
EntityManager in your custom evaluator and cross check/verify in DB
with user_id,permission_id,account_id
If the user is 'root' you can
staight away return true for hasPermission without verifying with
DB.
Annotate your service calls with
#PreAuthorize("isAuthenticated() and hasPermission(#accountArgument,
'respectivePermission')")
Refer link for custom implementations of Permission & PermissionEvaluator
If you are using EclipseLink there are a few features for this,
one is the #AdditionalCriteria annotation that allow a filter to be applied to all queries for a class,
http://www.eclipse.org/eclipselink/documentation/2.4/jpa/extensions/a_additionalcriteria.htm#additionalcriteria
another is EclipseLink's support for Oracle VPD (row level security in the database),
http://wiki.eclipse.org/EclipseLink/Examples/JPA/Auditing
and finally EclipseLink supports SessionEvents that can allow filter to be appended to any query execution,
http://www.eclipse.org/eclipselink/api/2.4/org/eclipse/persistence/sessions/SessionEventAdapter.html#preExecuteQuery%28org.eclipse.persistence.sessions.SessionEvent%29

Categories