Security context for serialization
kleiram opened this issue · comments
An issue I run into from time to time is that some links should only be visible when an user has certain permissions. For example, let's say I created a blog API and only admins should be able to delete comments. Something like this could be shown in the _links
object like so:
{
"_links": {
"delete": {
"href": "http://example.org/api/posts/14"
}
}
}
If I only want this route to be visible for users that have the ROLE_ADMIN
role, there's no easy way to do this at the moment besides creating a relation provider that only acts as a sort of proxy for the SecurityContextInterface
.
I propose adding something like an granted
attribute to the @RelationProvider
annotation:
/**
* @Hateoas\Relation(
* "delete",
* href = @Hateoas\Route(
* "post_delete",
* parameters = { "id" = "expr(object.getId())" }
* ),
* granted={"ROLE_ADMIN"}
* )
*/
class Post
{
// properties
}
Is this something that might be worth looking into?
PS: Clearly, this can be labeled as an enhancement.
You have to use exclusion rules https://github.com/willdurand/Hateoas#exclusion and the https://github.com/willdurand/Hateoas#the-expression-language .
/**
* @Hateoas\Relation(
* "delete",
* href = @Hateoas\Route(
* "post_delete",
* parameters = { "id" = "expr(object.getId())"
* }),
* exlusion = @Hateoas\Exclusion(
* excludeIf = "expr(not service('security.context')->isGranted(['ROLE_ADMIN']))"
* )
* )
*/
class Post
{
// properties
}
An expression function is_granted
could also be contributed!
👍 for the is_granted()
function.
Well, this is fixed in PR #30. Thanks for merging!
oops