Shiro详细配置-基于Spring3.2 shiro2.2

jopen 11年前

项目包图:

web.xml关键配置

<context-param> 
<param-name>contextConfigLocation</param-name>
<param-value>
/WEB-INF/classes/applicationContext.xml
/WEB-INF/classes/spring-shiro.xml
</param-value> 
</context-param>

spring-shiro.xml

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:util="http://www.springframework.org/schema/util"
xmlns:aop="http://www.springframework.org/schema/aop"  
xsi:schemaLocation="http://www.springframework.org/schema/beans 
http://www.springframework.org/schema/beans/spring-beans-3.0.xsd   
    http://www.springframework.org/schema/util 
    http://www.springframework.org/schema/util/spring-util-3.0.xsd">
<description>Shiro 配置</description>

<bean id="shiroFilter" class="org.apache.shiro.spring.web.ShiroFilterFactoryBean">
<property name="securityManager" ref="securityManager" />
<property name="loginUrl" value="/login.jsp" />
<property name="successUrl" value="/login.jsp" />
<property name="unauthorizedUrl" value="/error/noperms.jsp" />

<property name="filterChainDefinitions">
<value>
/login.jsp* = anon
/login.do* = anon
/index.jsp*= anon
/error/noperms.jsp*= anon
/*.jsp* = authc
/*.do* = authc
</value>
</property>
</bean>

<bean id="monitorRealm" class="com.shiro.security.MonitorRealm">
  <property name="credentialsMatcher">
           <bean class="org.apache.shiro.authc.credential.HashedCredentialsMatcher">
               <property name="hashAlgorithmName" value="MD5"/>
             <!--   true means hex encoded, false means base64 encoded -->
               <property name="storedCredentialsHexEncoded" value="true"/>
               <!-- 迭代次数 -->
               <property name="hashIterations" value="2" />
           </bean>
          </property> 
</bean>

<bean id="securityManager" class="org.apache.shiro.web.mgt.DefaultWebSecurityManager">
<!-- 基于ehCache来缓存用户认证信息和授权信息的实现 -->
 <property name="cacheManager" ref="cacheManager"/>
<!-- sessionMode参数设置为native时,那么shrio就将用户的基本认证信息保存到缺省名称为shiro-activeSessionCache 的Cache中 -->
        <property name="sessionMode" value="native" />
<!--设置自定义realm -->
<property name="realm" ref="monitorRealm" />
</bean>

    
<bean id="cacheManager" class="org.apache.shiro.cache.ehcache.EhCacheManager">
        <property name="cacheManager" ref="ehCacheManager"/>
   <property name="cacheManagerConfigFile" value="classpath:shiro_ehcache.xml"/> 
    </bean>


<bean id="ehCacheManager" class="org.springframework.cache.ehcache.EhCacheManagerFactoryBean"/>




<!-- securityManager -->
<bean class="org.springframework.beans.factory.config.MethodInvokingFactoryBean">
<property name="staticMethod" value="org.apache.shiro.SecurityUtils.setSecurityManager" />
<property name="arguments" ref="securityManager" />
</bean>

<!-- 保证实现了Shiro内部lifecycle函数的bean执行 -->
<bean id="lifecycleBeanPostProcessor" class="org.apache.shiro.spring.LifecycleBeanPostProcessor" />

<!-- AOP式方法级权限检查  -->
<bean
class="org.springframework.aop.framework.autoproxy.DefaultAdvisorAutoProxyCreator"
depends-on="lifecycleBeanPostProcessor" />

<bean
class="org.apache.shiro.spring.security.interceptor.AuthorizationAttributeSourceAdvisor">
<property name="securityManager" ref="securityManager" />
</bean>

</beans>


MonitorRealm.java

package com.shiro.security;


import java.util.ArrayList;
import java.util.List;


import org.apache.shiro.authc.AccountException;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.AuthenticationInfo;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.SimpleAuthenticationInfo;
import org.apache.shiro.authc.UnknownAccountException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.cache.Cache;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.apache.shiro.subject.SimplePrincipalCollection;
import org.apache.shiro.util.ByteSource;
import org.springframework.beans.factory.annotation.Autowired;


import com.shiro.mapper.RoleMapper;
import com.shiro.mapper.UserMapper;
import com.shiro.model.Resc;
import com.shiro.model.Role;


public class MonitorRealm extends AuthorizingRealm {


@Autowired
private UserMapper userMapper;
@Autowired
private RoleMapper roleMapper;


public MonitorRealm() {
super();
setAuthenticationTokenClass(UsernamePasswordToken.class);
          System.out.println("monitorRealm");
}


    /**
     * 验证
     */
@Override
protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authcToken) throws AuthenticationException {
 
System.out.println("monitorRealm-验证");
/* 这里编写认证代码 */
UsernamePasswordToken token = (UsernamePasswordToken) authcToken;
        String username = token.getUsername();
        if (username == null) {
            throw new AccountException("Null usernames are not allowed by this realm.");
        }
        String password = userMapper.getPassword(username).getPassword();
        if (password == null) {
            throw new UnknownAccountException("No account found for user [" + username + "]");
        }
        
        SimpleAuthenticationInfo saInfo = new SimpleAuthenticationInfo(username, password, getName());
        //用用户名填盐
        saInfo.setCredentialsSalt(ByteSource.Util.bytes(username));
return saInfo;
}


/**
     * 授权
     */
@Override
protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals) {
  System.out.println("monitorRealm-授权");
  String username = (String) principals.fromRealm( getName() ).iterator().next();
 // System.out.println(username);
  
  if( username != null ){
  SimpleAuthorizationInfo info = new SimpleAuthorizationInfo();
  info.addRole(username);
  info.addStringPermissions(   this.Topermissions( userMapper.selectUserRole(username).getRoles()) );
  
//   for(String str :   this.Topermissions( userMapper.selectUserRole(username).getRoles()) ){
//   System.out.println(str );
//   }
   return info;
  }
      return null;
}
   
   /**
    * 遍历角色得到资源
    */
   public List<String> Topermissions(List<Role> roles ){
  List<String>  permissions= new ArrayList<String>();
  for( Role role : roles ){
       permissions.addAll(   this.ToResc(    roleMapper.selectRoleResc(role.getRoleId()).getRescs()      )    );
  }
  return permissions;
   }

   /**
    * 遍历某个角色的资源
    */
public List<String > ToResc( List<Resc> rescs  ){
List<String > resStrings = new ArrayList<String>();
for ( Resc resc :rescs   ){
resStrings.add(resc.getResString());
}
return resStrings;
}

/**
 * 更新用户授权信息缓存.
 */
public void clearCachedAuthorizationInfo(String principal) {
 SimplePrincipalCollection principals = new SimplePrincipalCollection(principal, getName());
 clearCachedAuthorizationInfo(principals);
}
 
/**
* 清除所有用户授权信息缓存.
*/
public void clearAllCachedAuthorizationInfo() {
Cache<Object, AuthorizationInfo> cache = getAuthorizationCache();
if (cache != null) {
for (Object key : cache.keys()) {
cache.remove(key);
}
}
}
 
 
 
 
public UserMapper getUserMapper() {
return userMapper;
}


public void setUserMapper(UserMapper userMapper) {
this.userMapper = userMapper;
}


public RoleMapper getRoleMapper() {
return roleMapper;
}


public void setRoleMapper(RoleMapper roleMapper) {
this.roleMapper = roleMapper;
}

}




UserController.java

package com.shiro.controller;


import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.ExcessiveAttemptsException;
import org.apache.shiro.authc.IncorrectCredentialsException;
import org.apache.shiro.authc.LockedAccountException;
import org.apache.shiro.authc.UnknownAccountException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.crypto.hash.Md5Hash;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.mvc.multiaction.MultiActionController;


import com.shiro.model.User;
import com.shiro.service.UserService;


@Controller
@RequestMapping("/user")
public class UserController extends MultiActionController {


@Autowired
private UserService userService;


@RequestMapping("/login")
public  ModelAndView login( User user )  {

ModelAndView mv = new ModelAndView();

Subject currentUser = SecurityUtils.getSubject();

       
//前台传过来时应该用JS加密一次
String  minwen=new Md5Hash( user.getPassword() ).toHex();
System.out.println( minwen);

UsernamePasswordToken token = new UsernamePasswordToken( user.getUserName() , minwen);

//记住我功能不是记住密码而是在整个会话过程记住会话ID,对未登录用户时用购物车有点用
/*
if( rememberMe != null ){
if( rememberMe ){
token.setRememberMe(true);
}
}
*/
try {
  currentUser.login(token);
} catch (UnknownAccountException uae ) { 
mv.addObject("info", "用户名不存在系统!");
mv.setViewName("/erro");
} catch (IncorrectCredentialsException ice ) { 
mv.addObject("info", "密码错误!");
mv.setViewName("/erro");
} catch (LockedAccountException lae ) { 
mv.addObject("info", "用户已经被锁定不能登录,请与管理员联系!");
mv.setViewName("/erro");
} catch (ExcessiveAttemptsException eae ) { 
mv.addObject("info", "错误次数过多!");
mv.setViewName("/erro");
} catch (AuthenticationException ae ) {
mv.addObject("info", "其他的登录错误!");
mv.setViewName("/erro");
}
//验证是否成功登录的方法
if(currentUser.isAuthenticated()){
//在session生命周期内有效
System.out.println("进入isAuthenticated");
mv.setViewName("/main");
}   
return mv;

}

@RequestMapping("/do")
public  ModelAndView do_(  )  {
ModelAndView mv = new ModelAndView();

Subject currentUser = SecurityUtils.getSubject();

if( currentUser.hasRole("超级管理员")){
mv.addObject("info", "没有这个角色!");
mv.setViewName("/lognTest");
}else{
if(currentUser.isPermitted("/user/do")){
mv.addObject("info", "do!");
mv.setViewName("/success");
}else{
mv.addObject("info", "do!");
mv.setViewName("/lognTest");
}
}
return mv;
}

@RequestMapping("/out")
public  ModelAndView out(  )  {
ModelAndView mv = new ModelAndView();
Subject currentUser = SecurityUtils.getSubject();
if( currentUser.hasRole("超级管理员")){
mv.addObject("info", "没有这个角色!");
mv.setViewName("/lognTest");
}else{
if(currentUser.isPermitted("/user/out")){
mv.addObject("info", "do!");
mv.setViewName("/success");
}else{
mv.addObject("info", "out!");
mv.setViewName("/lognTest");
}
}
return mv;
}

@RequestMapping("/test")
public  ModelAndView test(  )  {
ModelAndView mv = new ModelAndView();
Subject currentUser = SecurityUtils.getSubject();
if( currentUser.hasRole("超级管理员")){
mv.addObject("info", "没有这个角色!");
mv.setViewName("/lognTest");
}else{
if(currentUser.isPermitted("/user/test")){
mv.addObject("info", "test!");
mv.setViewName("/success");
}else{
mv.addObject("info", "test!");
mv.setViewName("/lognTest");
}
}

return mv;
}


public UserService getUserService() {
return userService;
}


public void setUserService(UserService userService) {
this.userService = userService;
}

}



login.jsp <form id=loginform method=post name=loginform action="<%=path %>/user/login">
用户名:<input type=text id=userName name=userName class="input_border" maxlength=16/> <p/>
密码:<input type=password id=password name=password class="input_border"/>
<br>
<input  type="submit"  value="登录" />
</form>