Hey ...
What I did was to create my custom realm that loads user roles from data
source. It's not dynamic and user must first logout for new roles to become
accepted.
public class MyRealm extends AuthorizingRealm {
/**
code for this realm was removed, cause it's not needed
**/
/**
WHEN USER LOGS IN !!!
**/
@Override
protected AuthenticationInfo doGetAuthenticationInfo(final
AuthenticationToken token) {
UsernamePasswordToken upToken = (UsernamePasswordToken) token;
User user = null;
try {
this.userManager.beginTransaction();
user =
this.userManager.loadUserByLoginName(upToken.getUsername());
this.userManager.commitTransaction();
} catch (InvalidDataException idEx) {
throw new AuthenticationException(idEx);
} catch (ResourceException rEx) {
throw new AuthenticationException(rEx);
}
if (user == null) {
throw new AuthenticationException("Login name [" +
upToken.getUsername()
+ "] not found!");
}
log.info("Found user with username [{}]",
upToken.getUsername());
return new SimpleAuthenticationInfo(user, user.getPassword(),
getName());
}
/**
this function loads user authorization data from "userManager" data source
(database)
User, Role are custom POJOs (beans) and are loaded from database.
WildcardPermission implements shiros Permission interface, so my permissions
in database gets accepted by shiro security
**/
@Override
protected AuthorizationInfo doGetAuthorizationInfo(final
PrincipalCollection principals) {
Set<String> roles = new
HashSet<String>();
Set<Permission> permissions = new
HashSet<Permission>();
Collection<User> principalsList =
principals.byType(User.class);
if (principalsList.isEmpty()) {
throw new AuthorizationException("Empty principals
list!");
}
//LOADING STUFF FOR PRINCIPAL
for (User userPrincipal : principalsList) {
try {
this.userManager.beginTransaction();
User user =
this.userManager.loadById(userPrincipal.getId());
Set<Role> userRoles = user.getRoles();
for (Role r : userRoles) {
roles.add(r.getName());
Set<WildcardPermission> userPermissions
= r.getPermissions();
for (WildcardPermission permission :
userPermissions) {
if
(!permissions.contains(permission)) {
permissions.add(permission);
}
}
}
this.userManager.commitTransaction();
} catch (InvalidDataException idEx) { //userManger
exceptions
throw new AuthorizationException(idEx);
} catch (ResourceException rEx) {
throw new AuthorizationException(rEx);
}
}
//THIS IS THE MAIN CODE YOU NEED TO DO !!!!
SimpleAuthorizationInfo info = new
SimpleAuthorizationInfo(roles);
info.setRoles(roles); //fill in roles
info.setObjectPermissions(permissions); //add permisions (MUST
IMPLEMENT
SHIRO PERMISSION INTERFACE)
return info;
}
}
I hope I could help !
Kind regards
Armando
--
View this message in context:
http://shiro-user.582556.n2.nabble.com/How-to-add-a-role-to-the-subject-tp5562700p5562820.html
Sent from the Shiro User mailing list archive at Nabble.com.