1. 程式人生 > >shiro安全框架與ssm+maven的整合

shiro安全框架與ssm+maven的整合

1,新建maven 一個ssm的maven工程。在這裡我就不做多餘的介紹了。

下面是我的工程目錄結構

2,我們要整合shiro安全框架,首先要在pom.xml中引入jar包

這是我的截圖,需要在專案中引入可以複製下面藍色字型內容

<!-- shiro -->
        <!-- Spring 整合Shiro需要的依賴 -->
        <dependency>
            <groupId>org.apache.shiro</groupId>
            <artifactId>shiro-core</artifactId>
            <version>1.2.1</version>
        </dependency>
        <dependency>
            <groupId>org.apache.shiro</groupId>
            <artifactId>shiro-web</artifactId>
            <version>1.2.1</version>
        </dependency>
        <dependency>
            <groupId>org.apache.shiro</groupId>
            <artifactId>shiro-ehcache</artifactId>
            <version>1.2.1</version>
        </dependency>
        <dependency>
            <groupId>org.apache.shiro</groupId>
            <artifactId>shiro-spring</artifactId>
            <version>1.2.1</version>

        </dependency>

3.當我們引入完jar包之後,需要在spring的配置檔案中配置  我的檔名是 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"  
    xsi:schemaLocation="http://www.springframework.org/schema/beans   
                        http://www.springframework.org/schema/beans/spring-beans-3.0.xsd"  
    default-lazy-init="true">  

    <description>Shiro Configuration</description>  

    <!-- Shiro's main business-tier object for web-enabled applications -->  
    <bean id="securityManager" class="org.apache.shiro.web.mgt.DefaultWebSecurityManager">  
        <property name="realm" ref="myShiroRealm" />  
        <property name="cacheManager" ref="cacheManager" />  
    </bean>  

    <!-- 專案自定義的Realm -->  
    <bean id="myShiroRealm" class="cn.sh.ideal.web.login.menu.shiro.MyShiroRealm">  
        <property name="cacheManager" ref="cacheManager" />  
    </bean>  

    <!-- Shiro Filter -->  
    <bean id="shiroFilter" class="org.apache.shiro.spring.web.ShiroFilterFactoryBean">  
        <!-- 沒有許可權 或者失敗後跳轉的頁面 -->
        <property name="securityManager" ref="securityManager" />  
        <property name="loginUrl" value="/login" />  
        <property name="successUrl" value="/loginsuccess.jhtml" />  
        <property name="unauthorizedUrl" value="/error.jhtml" />  
        <property name="filterChainDefinitions">  
            <value>  
                /index = authc  <!-- 需要認證的url -->
                /login = anon   <!-- 排除認證url -->
                /checkLogin.json = anon  
                /loginsuccess.jhtml = anon  
                /js/** = anon 
                /css/** = anon
                /images/** = anon
               <!--  /** = authc  --> 
            </value>  
        </property>  
    </bean>  

    <!-- 使用者授權資訊Cache -->  
    <bean id="cacheManager" class="org.apache.shiro.cache.MemoryConstrainedCacheManager" />  

    <!-- 保證實現了Shiro內部lifecycle函式的bean執行 -->  
    <bean id="lifecycleBeanPostProcessor" class="org.apache.shiro.spring.LifecycleBeanPostProcessor" />  

    <!-- AOP式方法級許可權檢查 -->  
    <bean class="org.springframework.aop.framework.autoproxy.DefaultAdvisorAutoProxyCreator"  
        depends-on="lifecycleBeanPostProcessor">  
        <property name="proxyTargetClass" value="true" />  
    </bean>

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

</beans>  

當我們配置完spring-shiro.xml後

我們需要寫一個類去繼承 AuthorizingRealm類

package cn.sh.ideal.web.login.menu.shiro;

import javax.annotation.Resource;

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.UsernamePasswordToken;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.springframework.beans.factory.annotation.Autowired;

import cn.sh.ideal.web.login.menu.dao.MenuMapper;
import cn.sh.ideal.web.login.menu.entity.MenuEntity;
import cn.sh.ideal.web.login.menu.vo.ValidateLoginVo;


public class MyShiroRealm extends AuthorizingRealm{
	
	@Autowired
	private MenuMapper menuMapper;
	
	
    /*	
    private static final String USER_NAME = "luoguohui";  
	private static final String PASSWORD = "123456"; 
	*/
	
	/* 
	 * 授權
	 */
	@Override
	protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals) { 
       /* Set<String> roleNames = new HashSet<String>();  
        Set<String> permissions = new HashSet<String>();  
        roleNames.add("administrator");//新增角色
        permissions.add("newPage.jhtml");  //新增許可權
        SimpleAuthorizationInfo info = new SimpleAuthorizationInfo(roleNames);  
        info.setStringPermissions(permissions);  
        return info;  */
		return null;
	}
	
	
	


	/* 
	 * 登入驗證
	 */
	@Override
	protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authcToken) throws AuthenticationException {
		UsernamePasswordToken token = (UsernamePasswordToken) authcToken;
		MenuEntity loginerPamater = new MenuEntity();
		loginerPamater.setLoginUser(token.getUsername());
	    loginerPamater.setLoginPasswd(new String(token.getPassword()));
		
		ValidateLoginVo result = menuMapper.checkLoginNmAndPasswd(loginerPamater);
		result.getUserName();
		
	if(result.getUserName() != null){
		
			return new SimpleAuthenticationInfo(result, result.getUserPasswd(), getName());  
		}else{
			throw new AuthenticationException();  
		}
	}



	
	
	
}

上面是MyshiroRealm的方法

下面是登陸是進行驗證的方法


package cn.sh.ideal.web.login.menu.controller;

import java.util.HashMap;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;

import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.subject.Subject;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import com.alibaba.druid.support.json.JSONUtils;

import cn.sh.ideal.web.login.menu.util.BusinessException;
import cn.sh.ideal.web.login.menu.util.DecriptUtil;
import cn.sh.ideal.web.login.menu.util.LuoErrorCode;
import cn.sh.ideal.web.login.menu.vo.ValidateLoginVo;

@Controller
public class UserController {
		
	
	//登入頁
  @RequestMapping(value = "/login")
	public String login(){
		return "common/login";
	}
	
   //選單頁
   @RequestMapping(value = "/index")
    public String index(){
	   Subject subject = SecurityUtils.getSubject();
	   System.out.println(subject);
	    return "common/index";
   }
   
	@RequestMapping("/index.jhtml")
	public ModelAndView getIndex(HttpServletRequest request) throws Exception {
		ModelAndView mav = new ModelAndView("index");
		return mav;
	}

	@RequestMapping("/exceptionForPageJumps.jhtml")
	public ModelAndView exceptionForPageJumps(HttpServletRequest request) throws Exception {
		throw new BusinessException(LuoErrorCode.NULL_OBJ);
	}
	
	@RequestMapping(value="/businessException.json", method=RequestMethod.POST)
	@ResponseBody  
	public String businessException(HttpServletRequest request) {
		throw new BusinessException(LuoErrorCode.NULL_OBJ);
	}
	
	@RequestMapping(value="/otherException.json", method=RequestMethod.POST)
	@ResponseBody  
	public String otherException(HttpServletRequest request) throws Exception {
		throw new Exception();
	}
	
	/*//跳轉到登入頁面
	@RequestMapping("/login111.jhtml")
	public ModelAndView login() throws Exception {
		ModelAndView mav = new ModelAndView("login");
		return mav;
	}
	*/
	//跳轉到登入成功頁面
//	@RequestMapping("/loginsuccess.jhtml")
//	public ModelAndView loginsuccess() throws Exception {
//		ModelAndView mav = new ModelAndView("loginsuccess");
//		return mav;
//	}
	
//	@REQUESTMAPPING("/NEWPAGE.JHTML")
//	PUBLIC MODELANDVIEW NEWPAGE() THROWS EXCEPTION {
//		MODELANDVIEW MAV = NEW MODELANDVIEW("NEWPAGE");
//		RETURN MAV;
//	}
//	
//	@REQUESTMAPPING("/NEWPAGENOTADD.JHTML")
//	PUBLIC MODELANDVIEW NEWPAGENOTADD() THROWS EXCEPTION {
//		MODELANDVIEW MAV = NEW MODELANDVIEW("NEWPAGENOTADD");
//		RETURN MAV;
//	}
	
	/** 
     * 驗證使用者名稱和密碼 
     * @param String username,String password
     * @return 
     */  
    @RequestMapping(value="/checkLogin",method=RequestMethod.POST)  
    @ResponseBody  
    public String checkLogin(String username,String password) {  
    	Map<String, Object> result = new HashMap<String, Object>();
    	try{
    		UsernamePasswordToken token = new UsernamePasswordToken(username, password);  
            Subject currentUser = SecurityUtils.getSubject();  
            ValidateLoginVo vo = (ValidateLoginVo) currentUser.getPrincipal();
           if(vo != null){
        	   if(!token.getUsername() .equals(vo.getUserName())){
        		   currentUser.login(token);
        	   }
        	   
           }
            if (!currentUser.isAuthenticated()){
            	//使用shiro來驗證  
               // token.setRememberMe(true);  
                currentUser.login(token);//驗證角色和許可權  
            }
            
    	}catch(Exception ex){
    		throw new BusinessException(LuoErrorCode.LOGIN_VERIFY_FAILURE);
    	}
        result.put("success", true);
        return JSONUtils.toJSONString(result);  
    }  
	
//    /** 
//     * 退出登入
//     */  
//    @RequestMapping(value="/logout.json",method=RequestMethod.POST)    
//    @ResponseBody    
//    public String logout() {   
//    	Map<String, Object> result = new HashMap<String, Object>();
//        result.put("success", true);
//        Subject currentUser = SecurityUtils.getSubject();       
//        currentUser.logout();    
//        return JSONUtils.toJSONString(result);
//    }  
}

在我們登陸前方問checkLogin介面對使用者進行驗證即可。

在這裡有個方法

  Subject currentUser = SecurityUtils.getSubject(); 
通過這個方法可以拿到使用者的資訊。