Spring Security with roles and permissions

2022-08-31 12:23:02

I'm trying to set up role-based Security with permissions. I'm trying to do this together with Spring-Security.

I don't want to set up ACL as it seems it's an overkill for my requirements.

I just want to have simple permissions and roles as described in this article. Unfortunately the article does not describe how to implement the given solution.

Has someone already tried this and can point me in the right direction? Maybe there is another blog entry that describes the implementation?

Thank you very much.


答案 1

I'm the author of the article in question.

No doubt there are multiple ways to do it, but the way I typically do it is to implement a custom that knows about roles and permissions. and are just custom classes that you write. (Nothing fancy-- has a name and a set of instances, and has a name.) Then the returns objects that look like this:UserDetailsRolePermissionRolePermissionPermissiongetAuthorities()GrantedAuthority

PERM_CREATE_POST, , PERM_UPDATE_POSTPERM_READ_POST

instead of returning things like

ROLE_USER, ROLE_MODERATOR

The roles are still available if your implementation has a method. (I recommend having one.)UserDetailsgetRoles()

Ideally you assign roles to the user and the associated permissions are filled in automatically. This would involve having a custom that knows how to perform that mapping, and all it has to do is source the mapping from the database. (See the article for the schema.)UserDetailsService

Then you can define your authorization rules in terms of permissions instead of roles.

Hope that helps.


答案 2

To implement that, it seems that you have to:

  1. Create your model (user, role, permissions) and a way to retrieve permissions for a given user;
  2. Define your own and configure it (set its providers) to a custom . This last one should return on its authenticate method a Authentication, which should be setted with the , in your case, all the permissions for the given user.org.springframework.security.authentication.ProviderManagerorg.springframework.security.authentication.AuthenticationProviderorg.springframework.security.core.GrantedAuthority

The trick in that article is to have roles assigned to users, but, to set the permissions for those roles in the object.Authentication.authorities

For that I advise you to read the API, and see if you can extend some basic ProviderManager and AuthenticationProvider instead of implementing everything. I've done that with setting a custom LdapAuthoritiesPopulator, that would retrieve the correct roles for the user.org.springframework.security.ldap.authentication.LdapAuthenticationProvider

Hope this time I got what you are looking for. Good luck.


推荐