Spring data rest deleting using id in url is not calling deleteById method - spring

I am implementing Spring Data Rest and my resource has the default delete endpoint of /table/{id} when called with the DELETE method. My repository interface extends PagingAndSortingRepository and QuerydslPredicateExecutor and thus has the following overriden methods for delete:
deleteById(#NonNull ID id);
delete(#NonNull T entity);
deleteAll(#NonNull Iterable entities);
deleteAll();
On calling the above mentioned endpoint I find that Spring is making a call to findById and then calling delete(entity) somehow passing entity as the result of findById. This is causing me trouble with security as this requires the user to have permission over findById, which is permitted to only certain roles, and delete, which is permitted by different roles.
What can I do to tell spring to use deleteById instead when a DELETE method call is made to the deafult endpoint with ID in the path?

Related

Why is the JPA repository called from spring schedular not able to get the authentication from Security Context

I have a springboot application where with authentication available in SecurityContext post login. Any call from Rest Controller to persist any entity, getCurrentAuditor() method is called which returns the current principle which is used for auto updating the created date column.
I created an schedular using spring "awaitility" dependency. However, this schedular calls an update on a entity. When update is called and spring authentication is checked, it comes as null, even though i have logged in from front end. From front end i am able to persist other entities and gets the authentication object as well.
As per my understanding, this might be happening because the schedular starts as soon as Springboot kicks in and making save request independently. If that understanding is correct, how should i resolve this?
If the Scheduler can use a "system" user for update the entity, you can do something like the following and in the scheduler code perform the authentication:
public void authenticate() {
Authentication auth = authenticationManager.authenticate(getBatch());
SecurityContext sc = SecurityContextHolder.getContext();
sc.setAuthentication(auth);
}
public UsernamePasswordAuthenticationToken getBatch() {
return UsernamePasswordAuthenticationTokenBuilder.anUsernamePasswordAuthenticationToken()
.withCredentials(batchProperties.getPassword()).withUserCode(batchProperties.getUser()).withUserDto(
userDtoFactory.getBatch()).build();
}

Retrieve operational LDAP attributes with Spring Security

I am using spring-security-ldap to add LDAP authentication to my application. It is configured like so:
auth.ldapAuthentication()
.userSearchBase(ldapConfigProperties.getUserSearchBase())
.userSearchFilter(ldapConfigProperties.getUserSearchFilter())
.contextSource()
.managerDn(ldapConfigProperties.getManagerDn())
.managerPassword(ldapConfigProperties.getManagerPassword())
.url(ldapConfigProperties.getUrl())
.and()
.userDetailsContextMapper(ldapContextMapper);
The ldapContextMapper is an instance of a custom class called LdapUserContextMapper that implements UserDetailsContextMapper.
Inside mapUserFromContext() I use the DirContextOperations to retrieve several attributes from the LDAP user to construct a concrete User POJO. However, I just can't get access to operational attributes like memberOf. I tried every solution I could possible find on the web, but nothing seems to have worked.
For instance, ctx.getObjectAttributes("memberOf") returns null. Attempting to call ctx.search("", "", searchControls) with custom SearchControls with SUBTREE_SCOPE yields a not implemented exception from DirContextAdapter.
Any ideas?
I eventually ended up instantiating my own ContextSource and then using a custom ObjectPostProcessor, just as described in this issue.

Custom principal and scopes using Spring OAuth 2.0

I am using SpringBoot 2.0.5 and Spring Security OAuth to implement an OAuth 2.0 server and a set of client microservices.
In the AuthServer:
I have implemented the UserDetailsService so I can provide my custom enriched principal.
For the userInfoUri controller endpoint, I return user (my principal) and authorities as a map.
In the Client:
I have implemented PrincipalExtractor to extract and create my custom principal.
For each of the methods I require the principal, I use the following notation:
public List<Message> listMessages(#AuthenticationPrincipal MyPrincipal user)
This works (and I hope it's the right way) but now I'm having an issue to secure methods using scopes.
For example, if I want to have a controller method which is only accessible by another server (using client_credentials), I mark the method with the following annotation:
#PreAuthorize("#oauth2.hasScope('trust')")
But this results in an access error as I think the scope is not being transferred. I have added the scope to the userInfoUri endpoint but am unsure what I need to do on the client side so the scope is picked up.
Any pointers or example code would be very much appreciated.

Spring #PreAuthorize not working in RestController

I have GrantedAuthorities as [admin, player, user]
To test this I have injected Authentication object in method and invoked authentication.getAuthorities().
but when at REST Controller Method I put #PreAuthorize("hasRole('ROLE_player')")I am getting response for my REST web service as 403 forbidden.
I have custom roles defined which I am picking from database. I want to authorize REST call before execution of any business logic.
Tried with #Secured but still not working.
The default prefix for hasRole is ROLE_. If a prefix isn't supplied, spring will automatically add it. Since your roles in your database aren't prefixed with ROLE_ they will not match with hasRole.
// will be checking for ROLE_admin, your role in DB is admin
#PreAuthorize("hasRole('admin')")
You can update your roles in your db to prefix them with ROLE_ or you can alter the prefix spring uses on DefaultWebSecurityExpressionHandler. You should also be able to use hasAuthority rather than hasRole. The hasAuthority will not add any prefix to the supplied parameter.
#PreAuthorize("hasAuthority('admin')")
http://docs.spring.io/spring-security/site/docs/current/reference/html/el-access.html

Nullify some properties when getting the response from a method - Spring Security

I have the bellow apis in my application. My application manages spring security and in the logic there are some rules like based on the user's role , the user might be able to see or not certain attributes.
So my requirement it is to make null some attributes of the CustomObject based on the user's role.
Is there a way to accomplish this based with Spring Security ? There is the #PostFilter annotation but I think it will be useful to discard objects in the method's response , but not to make some attributes of the object null
public List<CustomObject> getCustomObjects()
public CustomObject getCustomObject()
If this is not possible with only spring security, I am thinking to create a custom annotation , mixed with some AOP to do the work, what do you think ?

Resources