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;

}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值