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(); 
通过这个方法可以拿到用户的信息。

















评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值