eg_shiro_springMVC

此次主要使用点为:
前端:html,js,jquery
后端:spring,MVC,mybatis,shiro,mysql

本文主要是记录shiro的整合

1、web.xml中配置shiro过滤器

<context-param>
        <description>设置Spring容器加载所有的配置文件的路径</description>
        <param-name>contextConfigLocation</param-name>
        <param-value>classpath:applicationContext.xml,classpath:spring-shiro.xml</param-value>
    </context-param>

<!-- shiro过滤器 -->
    <filter>
        <filter-name>shiroFilter</filter-name>
        <filter-class>org.springframework.web.filter.DelegatingFilterProxy</filter-class>
        <init-param>
            <param-name>targetFilterLifecycle</param-name>
            <param-value>true</param-value>
        </init-param>
    </filter>
    <filter-mapping>
        <filter-name>shiroFilter</filter-name>
        <url-pattern>*.jhtml</url-pattern>  
        <url-pattern>*.json</url-pattern> 

<servlet>
        <description>配置SpringMVC核心控制器</description>
        <servlet-name>springMvc</servlet-name>
        <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
        <init-param>
            <param-name>contextConfigLocation</param-name>
            <param-value>classpath:spring-mvc.xml</param-value>
        </init-param>
        <!-- 启动加载一次 -->
        <load-on-startup>1</load-on-startup>
    </servlet>
    <servlet-mapping>
        <servlet-name>springMvc</servlet-name>
        <url-pattern>*.json</url-pattern>
    </servlet-mapping>

2、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="com.htp.shiro.UserRealm">  
        <property name="cacheManager" ref="cacheManager" />  
    </bean>  

    <!-- Shiro Filter --> 
    <!-- anon匿名用户 
         authc需认证
     --> 
    <bean id="shiroFilter" class="org.apache.shiro.spring.web.ShiroFilterFactoryBean">  
        <property name="securityManager" ref="securityManager" />  
        <property name="loginUrl" value="/login.jhtml" />  
        <property name="successUrl" value="/loginsuccess.jhtml" />  
        <property name="unauthorizedUrl" value="/error.jhtml" />  
        <property name="filterChainDefinitions">  
            <value>  
                /index.jhtml = authc  
                /login.jhtml = anon
                /checkLogin.json = anon 
                /loginsuccess.jhtml = anon  
                /logout.json =  anon
                /** = anon  
            </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>  

3、Controller

 public String checkLogin(String username,String password) {  
        Map<String, Object> result = new HashMap<String, Object>();
        System.out.println("enter checkLogin...username【"+username+"】");

        try{
            UsernamePasswordToken token = new UsernamePasswordToken(username, password);  
            Subject currentUser = SecurityUtils.getSubject();  
            if (!currentUser.isAuthenticated()){
                //使用shiro来验证  
                token.setRememberMe(true);  
                currentUser.login(token);//验证角色和权限  
                System.out.println("principals["+currentUser.getPrincipals()+"]");
                System.out.println("admin["+currentUser.hasRole("admin")+"]");
                System.out.println("administrator["+currentUser.hasRole("administrator")+"]");
                System.out.println("secret["+currentUser.isPermitted("secret.html")+"]");
                System.out.println("newpage["+currentUser.isPermitted("newPage.html")+"]");

            }
        }catch(Exception ex){
            System.out.println("fail login exception");
            result.put("success", false);
            result.put("errorMsg", "用户身份认证失败");
            System.out.println("result"+result);
            return JSONUtils.valueToString(result);
        }
        result.put("success", true);
        System.out.println("result"+result);
        return JSONUtils.valueToString(result);
    }  

    /** 
     * 退出登录
     */  
    @RequestMapping(value="/logout.json",method=RequestMethod.POST)    
    @ResponseBody    
    public String logout() {  
        System.out.println("enter logout");
        Map<String, Object> result = new HashMap<String, Object>();
        result.put("success", true);
        Subject currentUser = SecurityUtils.getSubject();       
        currentUser.logout();  
        System.out.println("logout...");
        return JSONUtils.valueToString(result);
    }  

4、自定义Realm

package com.htp.shiro;

import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;

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.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;

import com.htp.serviceImpl.UserServiceImpl;

public class UserRealm  extends AuthorizingRealm {

    //这里因为没有调用后台,直接默认只有一个用户
    private static final String USER_NAME = "hutp";  
    private static final String PASSWORD = "123456"; 

    //需要添加注解才可使用,否则报空指针异常
    @Resource
    private UserServiceImpl userService;

    //权限认证
    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection arg0) {
        // TODO Auto-generated method stub

    String username = (String) arg0.getPrimaryPrincipal();  
    System.out.println("principal username["+username+"]");

        System.out.println("enter doGetAuthorizationInfo ");
        Set<String> roleNames = new HashSet<String>();  
        Set<String> permissions = new HashSet<String>();  
        roleNames.add("admin");//添加角色

        permissions.add("secret.html");  //添加权限
        SimpleAuthorizationInfo info = new SimpleAuthorizationInfo(roleNames);  
        info.setStringPermissions(permissions);  
        return info;  
    }

    //doGetAuthenticationInfo  身份认证
    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(
            AuthenticationToken arg0) throws AuthenticationException {
        // TODO Auto-generated method stub
        System.out.println("enter doGetAuthenticationInfo ");
        UsernamePasswordToken token = (UsernamePasswordToken) arg0;
        String username = token.getUsername();
        List<Map<String,String>> rst = userService.getUsers();
        for(int i=0; i<rst.size();i++){
            if(rst.get(i).get("name").equals(username))
            {
                System.out.println("succcess...getname["+getName()+"]");
                return new SimpleAuthenticationInfo(username, token.getPassword(), getName());
            }
        }
       System.out.println("user not found");
       throw new AuthenticationException();  
    }

}

5、界面

<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
<script type="text/javascript" src="js/jquery-3.3.1.js"></script>
<script type="text/javascript" src="js/login.js"></script>

</head>
<body>

<div>

username: <input type="text" id="username"><br><br>  
password: <input type="password" id="password"><br><br>
<button id="loginbtn">登录</button>
<button id="logoutbtn">注销</button>
</div>

</body>
</html>


/**
 * 
 */


$(document).ready(function(){
  $("#loginbtn").click(function(){
     alert("loginbtn test.....");
     var param = {
                username : $("#username").val(),
                password : $("#password").val()
            };
     $.ajax({ 
            type: "post", 
            url: "/DemoShiro/checkLogin.json", 
            data: param, 
            dataType: "json", 
            success: function(data) { 

                if(data.success == "false"){
                    alert(data.errorMsg);
                    window.location.href = "/DemoShiro/error.html";
                }else if(data.success == "true"){
                    //登录成功
                    window.location.href = "/DemoShiro/successLogin.html";
                }
                else{
                    alert("true/false");
                }
            },
            error: function(data) { 
                alert("调用失败...."); 
            }
        });
  });

  $('#logoutbtn').click(function(){
      var param = {
                username : $("#username").val(),
                password : $("#password").val()
            };
      $.ajax({

            type: "post", 
            url: "/DemoShiro/logout.json",
            data: param,
            success: function(data) { 
               alert("退出系统")
            },
            error: function(data) { 
                alert("调用失败...."); 
            }

      });  
    });
  });

6、效果
这里写图片描述

这里写图片描述

页面点击登录按钮,调用checkLogin.json;MVC控制器接收到请求后,调用login验证方法,从而进入doGetAuthenticationInfo;从库中查找是否存在此用户,成功则new SimpleAuthenticationInfo对象,继而调用doGetAuthorizationInfo,增加权限。返回后调用hasRole(),isPermitted(),输出对应结果。

shiro的使用还可以将权限写进年配置文件或者通过哭数据库来实现,继续学习。。。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值