Instance based login in spring security core

26 / Sep / 2012 by Shaurav 2 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…

[java]
class UserRole implements Serializable {

User user
Role role
BootCamp bootCamp

[/java]

[java]
class CustomUserDetailsService extends GormUserDetailsService {

@Override
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
}
}
[/java]

for example i am reloading the role by calling this method…
[java]
def getAuthoritiesBasedOnBootCamp() {
session.bootCampId = params.bootCampId
springSecurityService.reauthenticate(User.loggedInUser.email, "")
redirect(action: ‘dashBoard’)
}

[/java]

Shaurav@intelligrape.com

FOUND THIS USEFUL? SHARE IT

comments (2)

Leave a Reply

Your email address will not be published. Required fields are marked *