I have a grails application that uses spring-security-core and spring-security-ldap, with authentication against Active Directory. I have a custom UserDetails and UserDetailsContextMapper.
I have a use case where a user can temporarily take on additional responsibilities for a single session. I would like to be able to assign a role to the user after they have already logged in (i.e. mid-session), and then remove that role when the session expires.
I have a user_role database table that stores relationships between users and roles. In this case, it does not matter whether the relationship is added to the database and then removed when the session expires, or simply exists in memory only. Either way, I am looking for a way to assign the role (and have it immediately apply) at a point after the user has logged in. Is this possible?
The
UserDetails.getAuthorities()holds all roles of currently logged in user. As You already have a customUserDetailsYou only need to add the additional role to the values returned by(see edit below)getAuthorities()on the mid-session start, and then remove it on the mid-session end.ie:
Or You could create a wrapper around the original UserDetails that will hold the extra authorities and wrap it and set to the current Authentication object on the mid-session start and unwrap on the mid-session end.
Edit:
As Ben pointed out in the comment the
UserDetails.getAuthorities()does get called only once, at the login, when theAuthenticationobject is created – I forgot about that. But that brings us to the right answer, and this time I’m sure it’s gonna work, cause I did it myself this way. TheAuthentication.getAuthorities()is the method to attend to, not theUserDetails.getAuthorities(). And I really recommend a wrapper for that, not the custom implementaion ofAuthenticationinterace, as it’ll be more flexible and allow to transparentlysupport diffrent authentication mechanisms underneath.ie:
Then all You need to do is on the mid-session start:
And on the mid-session end: