Skip to content
Advertisement

Spring security : How to use @RolesAllowed with @RequestBody

I have a method like this:

@RolesAllowed("ROLE_A")
@RequestMapping(value = "/",
        method = RequestMethod.POST,
        produces = MediaType.APPLICATION_JSON_VALUE)
public MRSData modifyMarketData(@RequestBody RequestObject body){
    return repository.save(collection, body);
}

@Document
@Data
public class RequestObject {
    @Id
    @JsonInclude(JsonInclude.Include.NON_NULL)
    private String _id;
    private Object metadata;
    private Object body;
}

Request looks like this:

{
    "_id": "5f4ba6b3d93a8c1452f596a0",
    "metadata": {
        "data_type":"A" 
    }
}

Now only certain roles are allowed to access “data_type=A”.

I want to use @RolesAllowed or equivalent to block the request based on @RequestBody

How should i achieve this?

Tx in advannce

Advertisement

Answer

If you want to filter based on request value, you can use @PreAuthorize.

Docs: https://docs.spring.io/spring-security/site/docs/current/reference/html5/#method-security-expressions

Some examples: https://www.baeldung.com/spring-security-method-security

Old answer:

You can use @PostAuthorize (or maybe @PostFilter) to restrict access based on the method’s return value.

User contributions licensed under: CC BY-SA
7 People found this is helpful
Advertisement