Pregunta

Spring Data REST exposes data and actions through the methods defined in respositories. This is all good and dandy. However we have a use case where in we need to control the contents and actions(HTTP methods) that could be invoked based on the user and roles. Any pointers on how to approach this?

Adding security to REST API could be done using Oauth2.

¿Fue útil?

Solución

There is an example in the Spring Data Github.
Please look at https://github.com/spring-projects/spring-data-examples/tree/master/rest/security.

Otros consejos

In adition to the @JR Utily correct's answer which secures at Spring Security Configuration level, another option is to use the Spring DATA Rest Event Handlers which allows adding more operations like the following example.

Just define and annotated Handler with PrePost Spring's security annotations in the annotated

@Component
@RepositoryEventHandler(Item.class)
public class ItemEventHandler {

    private Logger logger = LoggerFactory.getLogger(ItemEventHandler.class);

    @HandleBeforeCreate
    @Preauthorize("hasRole('ROLE_ADMIN') or hasAuthority('ACTION_CREATE_ITEM')")
    public void handleItemBeforeCreate(Item item) {
        //POST operation available for ADMINs and Users with ACTION_CREATE_ITEM privilege
        logger.info("Creating item: " + item.toString());
        //more stuff if neccessary
    }

    @HandleBeforeSave
    @Preauthorize("hasRole('ROLE_ADMIN') or hasAuthority('ACTION_UPDATE_ITEM')")
    public void handleItemBeforeSave(Item item) {
        //PUT operation available for ADMINs and Users with ACTION_UPDATE_ITEM privilege
        logger.info("Updating item: " + item.toString());
        //more stuff if neccessary
    }

    @HandleBeforeDelete
    @Preauthorize("hasRole('ROLE_ADMIN') or hasAuthority('ACTION_DELETE_ITEM')")
    public void handleItemBeforeDelete(Item item) {
        //DELETE operation available for ADMINs and Users with ACTION_DELETE_ITEM privilege
        logger.info("Deleting item: " + item.toString());
        //more stuff if neccessary
    }
}

This is the full list of Spring DATA Rest event handlers:

  • BeforeCreateEvent
  • AfterCreateEvent
  • BeforeSaveEvent
  • AfterSaveEvent
  • BeforeSaveEvent
  • BeforeLinkSaveEvent
  • AfterLinkSaveEvent
  • BeforeDeleteEvent
  • AfterDeleteEvent

More information found in Spring DATA Rest Reference for event handling

Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow
scroll top