天天看點

apache shiro整合struts2+spring+mybatis簡單demo

先上一段shiro中擷取資料源的代碼,Demo見附件

public class AuthenticationRealm extends AuthorizingRealm {

private static final Logger log = LoggerFactory.getLogger(AuthenticationRealm.class);

@Autowired

private UserMapper userMapper;

@Autowired

private RoleMapper roleMapper;

@Override

protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {

UsernamePasswordToken upToken = (UsernamePasswordToken) token;

String username = upToken.getUsername();

// char[] password = upToken.getPassword();

// log.debug(String.valueOf(password));

// Null username is invalid

if (username == null) {

throw new AccountException("使用者名不能為空!");

}

SimpleAuthenticationInfo info = null;

try{

String password = userMapper.getPassword(username);

if (password == null) {

throw new UnknownAccountException("No account found for user [" + username + "]");

}

// if(password.length>2){

// throw new AuthenticationException("More than one user row found for user [" + username + "]. Usernames must be unique.");

// }

info = new SimpleAuthenticationInfo(username, password.toCharArray(), getName());

} catch (RuntimeException e) {

final String message = "There was a SQL error while authenticating user [" + username + "]";

throw new AuthenticationException(message, e);

}

return info;

}

@Override

protected AuthorizationInfo doGetAuthorizationInfo(

PrincipalCollection principals) {

if (principals == null) {

throw new AuthorizationException("PrincipalCollection method argument cannot be null.");

}

String username = (String) getAvailablePrincipal(principals);

Set<String> roleNames = getRoleNameByUserName(username);

Set<String> permissions = new HashSet<String>();

for(String roleName : roleNames){

Role role = roleMapper.getRole(roleName);

for(Permission permission :role.getPermissions()){

permissions.add(permission.getModule()+":"+permission.getPrivilege());

}

}

SimpleAuthorizationInfo info = new SimpleAuthorizationInfo(roleNames);

info.setStringPermissions(permissions);

return info;

}

public Set<String> getRoleNameByUserName(String username){

Set<String> roless = new HashSet<String>();

User user = userMapper.getUser(username);

for(Role role:user.getRoles()){

roless.add(role.getName());

log.debug(role.getName());

}

return roless;

}

繼續閱讀