robin 发表于 2016-11-28 09:12:33

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;

}

yunweieye 发表于 2018-6-20 11:47:14

附件,,,
页: [1]
查看完整版本: apache shiro整合struts2+spring+mybatis简单demo