1

I'm having a set of Sping Data Repositories which are all exposed over Rest by using Spring-data-rest project. Now I want to secure the HTTP, so that only registered users can access the http://localhost:8080/rest/ So for this purpose I add @Secured(value = { "ROLE_ADMIN" }) to all the repositories and I also enable the security by specifying the

@EnableGlobalMethodSecurity(securedEnabled = true, jsr250Enabled = true, prePostEnabled = true)

So now what happens is I go to the rest and it's all good - i'm asked to authenticate. Next thing I do is I go to my website (which uses all the repositories to access the database) but my request fails with

nested exception is org.springframework.security.authentication.AuthenticationCredentialsNotFoundException: An Authentication object was not found in the SecurityContext

which is correct because i'm browsing my website as anonymous user.

So my question is: is there a way to provide method authentication for the REST layer only? To me it sounds like a new annotation is needed (something like @EnableRestGlobalMethodSecurity or @EnableRestSecurity)

Petar Tahchiev
  • 4,336
  • 4
  • 35
  • 48

1 Answers1

2

I don't know if this will solve your problem, however I managed to get something similar, working for me by creating an event handler for my specific repository, and then used the @PreAuthorize annotation to check for permissions, say on beforeCreate. For example:

@RepositoryEventHandler(Account.class)
public class AccountEventHandler {

    private final Logger logger = LoggerFactory.getLogger(getClass());

    @PreAuthorize("isAuthenticated() and (hasRole('ROLE_USER'))")
    @HandleBeforeCreate
    public void beforeAccountCreate(Account account) {
        logger.debug(String.format("In before create for account '%s'",     account.getName()));
    }

    @PreAuthorize("isAuthenticated() and (hasRole('ROLE_ADMIN'))")
    @HandleBeforeSave
    public void beforeAccountUpdate(Account account) {
        logger.debug(String.format("In before update for account '%s'", account.getName()));
    //Don't need to add anything to this method, the @PreAuthorize does the job.
    }
}
Ruaghain
  • 135
  • 1
  • 14