当前位置 : 主页 > 编程语言 > java >

shiro权限实现核心代码(仅备份)

来源:互联网 收集:自由互联 发布时间:2021-06-28
web.xml相关配置 - b2 - index.html - encodingFilter org.springframework.web.filter.CharacterEncodingFilter - encoding UTF-8 + - encodingFilter /* - contextConfigLocation classpath:applicationContext-core.xml - org.springframework.web.con
web.xml相关配置
 

-
 


  



  
   b2
  
  

-
   
   
    index.html
    
  


-
   
   
    encodingFilter
    
   
    org.springframework.web.filter.CharacterEncodingFilter
    -
    
    
     encoding
     
    
     UTF-8
     
    +
    
   
  


-
   
   
    encodingFilter
    
   
    /*
    
  


-
   
   
    contextConfigLocation
    
   
    classpath:applicationContext-core.xml
    
  


-
   
   
    org.springframework.web.context.ContextLoaderListener
    
  


-
   
   
    org.springframework.web.context.ContextCleanupListener
    
  


-
   
   
    mvc-dispatcher
    
   
    org.springframework.web.servlet.DispatcherServlet
    -
    
    
     contextConfigLocation
     
    
     /WEB-INF/config/mvc-dispatcher-servlet.xml
     
    
   
    1
    
  


-
   
   
    mvc-dispatcher
    
   
    /
    
  


  



  



  



  



  



-
   
   
    shiroFilter
    
   
     org.springframework.web.filter.DelegatingFilterProxy 
    -
    
     
    
     targetFilterLifecycle
     
    
     false
     
    
  


-
   
   
    shiroFilter
    
   
    /*
    
  


-
   
   
    500
    
   
    /WEB-INF/jsp/error.jsp
    
  


  



-
  
    -
    
    
     /*
     
    
     DELETE
     
    
     HEAD
     
    
     OPTIONS
     
    
     TRACE
     
    -
    
     
    
  


-
   
   
    FORM
    -
    
    
     /WEB-INF/jsp/error.jsp
     
    
  


  



 
springMVC相关配置
 

	
  
	
	
   
    
     
      
       
       
        text/html;charset=UTF-8
        
       
      
     
    
    
    
     
  
	
    
	
  
	
   
    
   
	
    
    
    
    
    
    
	
  
	
  
	
   
	
   
	
   
	
  
	
  
	
  
	
  
	
  
	
    
     
     
     
	
   
    
    
     /WEB-INF/
     
    
    
    
  
	
	
   
    
    
    
     
     
      error
      
     
    
  
    

	
  
	
  
	    
   
    
  
	
 
spring相关配置
 

 
	
  
	
  

	
  
    
  
    
	
  
	
   
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
  
	
	
   
    
    
    
    
  


	
   
    
    
    
  

	
   
    
  

	
   
    
  

	
   
    
    
    
    
    
    
  

	
   
    
    
    
  

	
   
    
    
  

	
  

	
  
	
	
  

	
  
	
  
	
  
	
  
	
  
	
  
	
  


	
  
	
  
	
	
  
	
  

	
  
	
   
    
     
      
     
      *Dao
      
     
      *Mapper
      
      
      
     
    
    
     
      
     
      exceptionHandler
      
     
    
  
	
  
	

 
shiro配置
 

 
    
   
  
	
  
	
  
	
   
    
   
    
    
    
    
    
    
      /b2b/ana/login = anon 
      /b2b/ana/login.ajax = anon /b2b/ana/logout.ajax = anon /b2b/ana/logout = anon /b2b/ana/getModifyMobileCaptchaCode.ajax = anon /b2b/ana/checkCaptchaCode.ajax = anon /b2b/ana/checkCaptcha.ajax = anon /b2b/ana/captcha-image.do = anon /dictionary/getCommboxDictionaryData.ajax = anon /enterprise/checkEnterprise.ajax = anon /enterprise/registerEnterprise.ajax = anon /enterprise/certificationEnterprise.ajax = anon /common/queryIndustryAtegory.ajax = anon /common/getProvince.ajax = anon /common/getCity.ajax = anon /common/queryDevelopmentArea.ajax = anon /user/getUserbyLoginname.ajax = anon /user/changePassword.ajax = anon /index.htm = anon /portal/login.html = anon /portal/findpassword/findpassword.html = anon /portal/componyregister.html = anon /portal/registerEnterprise.html = anon /resources/** = anon /themes/** = anon /images/** = anon /scripts/** = anon /common/** = anon /portal/** = anon /logout.do = logout 
      /** = authc 
      
     
    
  

  	
  
    
   
    
    
    
    
  
    
   
    
    
    
    
    
     
    
    
   
     
    
    
    
    
   
    
    
  
    
    
    
   
    
    
    
  
	
   
    
    
    
    
    
    
    
    
    
     
      
     
    
  
	
	
    
	
  
	
	

 
自定义realm
package com.creditease.hardess.core.shiro.realm;

 
import javax.annotation.Resource;

import org.apache.activemq.jaas.UserPrincipal;
import org.apache.shiro.authc.AuthenticationInfo;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.IncorrectCredentialsException;
import org.apache.shiro.authc.SimpleAuthenticationInfo;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.apache.shiro.util.ByteSource;

import com.creditease.hardess.core.entity.ana.User;
import com.creditease.hardess.core.service.ana.UserService;   

  
/**** 
 * 自定义Realm 
 *  
 * @author Peter
 *  
 */  
public class MyShiroRealm extends AuthorizingRealm {  
	@Resource
	UserService userService;
	
	@Override 
	public String getName() {
		return"customRealm";
	}


	// 支持什么类型的token
	@Override
	public boolean supports(AuthenticationToken token) {
		return token instanceof UsernamePasswordToken;
	}

    /*** 
     * 获取授权信息 
     */  
    @Override  
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection pc) {  
    	 String u = pc.toString();
         System.out.println(u);
        //根据自己系统规则的需要编写获取授权信息,这里为了快速入门只获取了用户对应角色的资源url信息  
       // String username = (String) pc.fromRealm(getName()).iterator().next();  
         String username = pc.toString();
        if (username != null) {  
           /* List
 
   pers = accountService.getPermissionsByUserName(username);  
            if (pers != null && !pers.isEmpty()) {  
                SimpleAuthorizationInfo info = new SimpleAuthorizationInfo();  
                for (String each : pers) {  
                    //将权限资源添加到用户信息中  
                    //info.addStringPermission(each);  
                    info.addStringPermission("query");
                }  
                info.addStringPermission("query");
                return info;  
            } */ 
            SimpleAuthorizationInfo info = new SimpleAuthorizationInfo();
            info.addStringPermission("query");//没有权限访问
            return info;  
        }  
        
        return null;  
    }  
    /*** 
     * 获取认证信息 
     */  
    @Override  
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken at) {  
        UsernamePasswordToken token = (UsernamePasswordToken) at;  
        // 通过表单接收的用户名  
       // String username = token.getUsername();  
        String username = (String) at.getPrincipal();
        
        if (username != null && !"".equals(username)) {  
            //User user = accountService.getUserByUserName(username); 
        	User user = userService.getUserbyLoginname(token.getUsername());
            if (user != null && user.getUserLoginPassword() != null && user.getUserLoginName().equals(token.getUsername())) {  
            	
            	// 下面两种方式有什么区别,待学习了解????
            	//return new SimpleAuthenticationInfo(user.getUserLoginName(), user.getUserLoginPassword(), getName());              	
            	SimpleAuthenticationInfo authenticationInfo = new SimpleAuthenticationInfo( //
    					//new UserPrincipal(user, token.isMobileLogin()),// principal
    					new UserPrincipal(username),
    					user.getUserLoginPassword(), // Credentials:加密后的凭证,放置在数据库中了
    					getName());//
    			authenticationInfo.setCredentialsSalt(ByteSource.Util.bytes(username));
    			return authenticationInfo;
            }else{
            	 //throw new UnknownAccountException(); //如果用户名错误 
            	throw new IncorrectCredentialsException(); //如果密码错误 
            }
        }  
  
        return null;  
    }  
    
  
}
 
shiro自定义加密方式 (二先一即可)
package com.creditease.hardess.core.shiro.credential;

import org.apache.shiro.authc.AuthenticationInfo;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.authc.credential.SimpleCredentialsMatcher;

import com.creditease.hardess.common.util.SecurityUtil;

/**
 * 通过继承SimpleCredentialsMatcher自定义密码加密方式(也可通过继承HashedCredentialsMatcher)
 * 
 * @author: Peter
 */
public class CustomCredentialsMatcher extends SimpleCredentialsMatcher {

	@Override
	public boolean doCredentialsMatch(AuthenticationToken authcToken, AuthenticationInfo info) {

		UsernamePasswordToken token = (UsernamePasswordToken) authcToken;
		Object accountCredentials = getCredentials(info);
		// String pwd =encrypt32(String.valueOf(token.getPassword()));//md5 32位加密
		String pwdType = String.valueOf(token.getPassword());// 判断一下密码是否是用户输入的,还是JCIS传过来的
		if (pwdType.length() == 32) {
			return equals(pwdType, accountCredentials); // 密码长度=32位,说明是md5加密过,是从xx传进来的 32位加密。
		}
		String pwdUser = SecurityUtil.calcMaskedPassword(SecurityUtil.genSalt(token.getUsername()),
				new String(token.getPassword()));
		// String pwdUser =encrypt32(String.valueOf(token.getPassword()));//不等于32
		// 是用户输入的密码。 如果用户输入的密码长度位32那么里面会有一个bug
		return equals(pwdUser, accountCredentials);
		// 将密码加密与系统加密后的密码校验,内容一致就返回true,不一致就返回false
		// return super.doCredentialsMatch(token, info) ;
	}

}






package com.creditease.hardess.core.shiro.credential;

import org.apache.shiro.authc.AuthenticationInfo;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.SimpleAuthenticationInfo;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.authc.credential.HashedCredentialsMatcher;

import com.creditease.hardess.common.util.SecurityUtil;
/**
 * 通过继承HashedCredentialsMatcher自定义密码加码规则(也可通过继承SimpleCredentialsMatcher实现)
 * @author Peter
 *
 */
public class RetryLimitHashedCredentialsMatcher extends HashedCredentialsMatcher {
	
	@Override
	public boolean doCredentialsMatch(AuthenticationToken token, AuthenticationInfo info) {
		String username = (String) token.getPrincipal();
		UsernamePasswordToken autoken = (UsernamePasswordToken) token;
		SimpleAuthenticationInfo sinfo = (SimpleAuthenticationInfo) info;
		String pwdhash = new String(sinfo.getCredentialsSalt().getBytes());
		// 这个CipherUtil.generatePassword是自定义的static方法,用于生成加密后的密码
		//String inputCredential = CipherUtil.generatePassword(String.valueOf(autoken.getPassword()) + pwdhash);
		String inputCredential = SecurityUtil.calcMaskedPassword(SecurityUtil.genSalt(username), new String(autoken.getPassword()));
		
		// 生成的加密是大写,但mysql不区分大小写,对比会失败
		String accountCredentials = String.valueOf(getCredentials(info)).toUpperCase();
		boolean match = equals(inputCredential, accountCredentials);
		if (match) {
			// passwordRetryCache.remove(username);
		}
		return match;
	}
}
shiro自定义缓存
package com.creditease.hardess.core.shiro.cache;

import org.apache.shiro.cache.Cache;
import org.apache.shiro.cache.CacheException;

/**  
 *   
 * 缓存管理器接口  
 *   
 * @author Peter  
 *   
 */  
public interface SimpleCacheManagerInterface {  
  
    /**  
     * 新增缓存堆到管理器  
     *   
     * @param name  
     * @param cache  
     */  
    public abstract void createCache(String name, Cache
 
   cache) throws CacheException;  
  
    /**  
     * 获取缓存堆  
     *   
     * @param name  
     * @return  
     * @throws CacheException  
     */  
    public abstract Cache
  
    getCache(String name) throws CacheException; /** * 移除缓存堆 * * @param name * @throws CacheException */ public abstract void removeCache(String name) throws CacheException; /** * 更新缓存堆 * * @param name * @param cache */ public abstract void updateCahce(String name, Cache
   
     cache) throws CacheException; /** * 注销管理器 */ public abstract void destroy() throws CacheException; } package com.creditease.hardess.core.shiro.cache; import javax.annotation.Resource; import org.apache.shiro.cache.Cache; import org.apache.shiro.cache.CacheException; import com.alibaba.fastjson.JSON; import com.creditease.hardess.core.service.redis.RedisService; /** * * 缓存管理器实现类 
    
      * * @author Peter * */ public class SimpleCacheManagerImpl implements SimpleCacheManagerInterface { @Resource public RedisService redisService; public SimpleCacheManagerImpl() { } public SimpleCacheManagerImpl(RedisService redisService) { if (redisService == null) { throw new RuntimeException("必须存在Redis客户端实例"); } this.redisService = redisService; } @Override public void createCache(String name, Cache
     
       cache) throws CacheException { try { redisService.set(name, JSON.toJSONString(cache)); } catch (Exception e) { throw new CacheException(e); } } @Override public Cache
      
        getCache(String name) throws CacheException { try { return (Cache
       
        ) JSON.parse(redisService.get(name)); } catch (Exception e) { throw new CacheException(e); } } @Override public void removeCache(String name) throws CacheException { try { redisService.del(name); } catch (Exception e) { throw new CacheException(e); } } @Override public void updateCahce(String name, Cache
        
          cache) throws CacheException { try { redisService.set(name, JSON.toJSONString(cache)); } catch (Exception e) { throw new CacheException(e); } } @Override public void destroy() throws CacheException { try { } catch (Exception e) { throw new CacheException(e); } } }
        
       
      
     
    
   
  
 
网友评论