Shiro詳細配置-基于Spring3.2 shiro2.2

jopen 11年前發布 | 77K 次閱讀 Shiro 安全相關

項目包圖:

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;
    }

    } </p>




    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;
    }

    } </p>



    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>
 本文由用戶 jopen 自行上傳分享,僅供網友學習交流。所有權歸原作者,若您的權利被侵害,請聯系管理員。
 轉載本站原創文章,請注明出處,并保留原始鏈接、圖片水印。
 本站是一個以用戶分享為主的開源技術平臺,歡迎各類分享!