简体   繁体   中英

Spring Security - How to change user roles dynamically?

I have a question about changing role dynamically in runtime. Suppose that we have a social network application (like Facebook) and we are using Spring security for authentication/authorization purpose.

When a person open his Homepage this person has the ADMIN role and can do everything with his Homepage. However, when he is visiting another friend's Homepage he should only have the role USER which can only do some restricted actions (he cannot delete posts in the Homepage of his friend, for example). If we use AuthenticationManagerBuilder then we can only set one fixed role for each user.

Can anyone help me with this question?

Thank you.

I think you should overthink your concept. Users are always users. Users with homepages are userWithHomepage and real admins are admins.

You need to check on the page, whether the currentUser is privileged for the current page - and give him his roles on this site.

So "UserWithHomepage" comes to his own Homepage, you check: is this user privileged on this site? If yes: activate admin things on this site. If you add a role to his userContext, he could get access as this role to other sites, too. I think, this is a security flaw.

So simply set a marker on your controller or check each time, something happens (instantiation, button click etc.) if the user has the privilege to do so.

You shouldn't change your user roles based on what page they are visiting. In your case, when visiting the homepage, you should check if the user is the owner of the homepage, and if so, give him the option to edit/delete and if not, just don't give them the option (don't show the links for editing/deletion, throw an exception if they try to execute that request anyway).

谢谢大家,实际检查用户是否是主页的所有者正是我们需要做的!

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM