Instance based login in spring security core

26 / Sep / 2012 by Shaurav 1 comments

Spring security loads the roles of user from user role table based on all roles assigned to user and that role is application specific.
But In my project i require to assign roles to user based on instance . So when the instance is changed roles should be changed .In grails we can overide the methods of plugin. So when instance change i reauthenticate the user and overrided the “loadAuthorities ” method of spring security. So instead of fetching roles from spring security loadAuthorities method , it loads from this overided loadAuthorities method…

class UserRole implements Serializable {

    User user
    Role role
    BootCamp bootCamp

class CustomUserDetailsService extends GormUserDetailsService {

protected Collection loadAuthorities(user, String username, boolean loadRoles) {
		if (!loadRoles) {
			return []
def conf = SpringSecurityUtils.securityConfig
String authoritiesPropertyName = conf.userLookup.authoritiesPropertyName
String authorityPropertyName = conf.authority.nameField
Bootcamp bootCamp=BootCamp.get(RequestContextHolder.currentRequestAttributes().getSession()?.bootCampId))      
  User loggedInUser = User.findByEmail(username)
 //Write your query for loading roles here for ex.

Collection<?> userAuthorities =UserRole.findAllByUserAndBootCamp(loggedInUser, bootCamp)?.role

def authorities = userAuthorities.collect { new GrantedAuthorityImpl(it."$authorityPropertyName") }
authorities ?: NO_ROLES

for example i am reloading the role by calling this method…

def getAuthoritiesBasedOnBootCamp() {
        session.bootCampId = params.bootCampId
        springSecurityService.reauthenticate(, "")
        redirect(action: 'dashBoard')


comments (1 “Instance based login in spring security core”)

Leave a comment -