ssm的shiro实际应用

开始之前一定要先看一下大神的:

Shiro学习--与SpringMVC整合(数据库,Shiro注解和Shiro标签

http://blog.csdn.net/frankcheng5143/article/details/50836619

 

 

1.使用maven,配置pom:

<!-- https://mvnrepository.com/artifact/org.apache.shiro/shiro-core -->
      <dependency>
          <groupId>org.apache.shiro</groupId>
          <artifactId>shiro-core</artifactId>
          <version>1.2.2</version>
      </dependency>

      <!-- https://mvnrepository.com/artifact/org.apache.shiro/shiro-web -->
      <dependency>
          <groupId>org.apache.shiro</groupId>
          <artifactId>shiro-web</artifactId>
          <version>1.2.2</version>
      </dependency>

      <!-- https://mvnrepository.com/artifact/org.apache.shiro/shiro-spring -->
      <dependency>
          <groupId>org.apache.shiro</groupId>
          <artifactId>shiro-spring</artifactId>
          <version>1.2.2</version>
      </dependency>

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-4.2.xsd">

	<!-- 导入数据库的相关配置 -->
	<import resource="classpath:spring/spring-database.xml"/>

	<!-- 对应于web.xml中配置的那个shiroFilter -->
	<bean id="shiroFilter" class="org.apache.shiro.spring.web.ShiroFilterFactoryBean">
		<!-- Shiro的核心安全接口,这个属性是必须的 -->
		<property name="securityManager" ref="securityManager"/>
		<!-- 要求登录时的链接(登录页面地址),非必须的属性,默认会自动寻找Web工程根目录下的"/login.jsp"页面 -->
		<property name="loginUrl" value="/base/Shiro/login.html"/>
		<!-- 登录成功后要跳转的连接(本例中此属性用不到,因为登录成功后的处理逻辑在LoginController里硬编码) -->
		<!-- <property name="successUrl" value="/" ></property> -->
		<!-- 用户访问未对其授权的资源时,所显示的连接 -->
		<property name="unauthorizedUrl" value="/error/unauthorized"/>

		<!--<property name="filterChainDefinitions">-->
			<!--<value>-->
				<!--/admin/**=authc-->
			<!--</value>-->
		<!--</property>-->

	</bean>


	<bean id="lifecycleBeanPostProcessor" class="org.apache.shiro.spring.LifecycleBeanPostProcessor"></bean>
	<!-- 数据库保存的密码是使用MD5算法加密的,所以这里需要配置一个密码匹配对象 -->
	<!--<bean id="credentialsMatcher" class="org.apache.shiro.authc.credential.Md5CredentialsMatcher"></bean>-->
	<!-- 缓存管理 -->
	<!--<bean id="shiroCacheManager" class="org.apache.shiro.cache.MemoryConstrainedCacheManager"></bean>-->

	<!--
    使用Shiro自带的JdbcRealm类
    指定密码匹配所需要用到的加密对象
    指定存储用户、角色、权限许可的数据源及相关查询语句
    -->
	<bean id="jdbcRealm" class="org.apache.shiro.realm.jdbc.JdbcRealm">
		<!--<property name="credentialsMatcher" ref="credentialsMatcher"></property>-->
		<property name="permissionsLookupEnabled" value="true"></property>
		<property name="dataSource" ref="dataSource"></property>
<!---->

<property name="authenticationQuery" value="SELECT password FROM base_user WHERE login_name = ?"></property>

<!--数据库查询role角色信息-->

<property name="userRolesQuery" value="

<!--数据库查询权限信息-->

SELECT t.role_code from base_role t left join base_user tt on t.ROLE_CODE=tt.DEFAULT_ROLE_CODE WHERE LOGIN_NAME = ? "></property><property name="permissionsQuery" value="SELECT PT.PERMISSION_NAME from PERMISSION_WITH pw LEFT JOIN PERMISSION_TEST pt on pw.P_ID = pt.PERMISSION_ID LEFT JOIN BASE_ROLE t on t.ROLE_ID = pw.ROLE_ID where t.role_code = ?"></property></bean><!-- Shiro安全管理器 --><bean id="securityManager" class="org.apache.shiro.web.mgt.DefaultWebSecurityManager"><property name="realm" ref="jdbcRealm"></property><!--<property name="cacheManager" ref="shiroCacheManager"></property>--></bean><!-- Shiro的注解配置一定要放在spring-mvc中 --></beans>

 

3.spring-mvc配置:

 <!-- 未认证或未授权时跳转必须在springmvc里面配,spring-shiro里的shirofilter配不生效 -->
    <bean
            class="org.springframework.web.servlet.handler.SimpleMappingExceptionResolver">
        <property name="exceptionMappings">
            <props>
                <!--表示捕获的异常 -->
                <prop key="org.apache.shiro.authz.UnauthorizedException">
                    <!--捕获该异常时跳转的路径 -->
                    /error/unauthorized
                </prop>
                <!--表示捕获的异常 -->
                <prop key="org.apache.shiro.authz.UnauthenticatedException">
                    <!--捕获该异常时跳转的路径 -->
                    /error/unauthorized
                </prop>
            </props>
        </property>
    </bean>

 

 

controller层:
 

package org.szd.base.controller;


import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;

import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.DisabledAccountException;
import org.apache.shiro.authc.ExcessiveAttemptsException;
import org.apache.shiro.authc.ExpiredCredentialsException;
import org.apache.shiro.authc.IncorrectCredentialsException;
import org.apache.shiro.authc.LockedAccountException;
import org.apache.shiro.authc.SimpleAuthenticationInfo;
import org.apache.shiro.authc.UnknownAccountException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.authz.AuthorizationException;
import org.apache.shiro.authz.UnauthorizedException;
import org.apache.shiro.authz.annotation.Logical;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.apache.shiro.authz.annotation.RequiresRoles;
import org.apache.shiro.subject.Subject;
import org.apache.shiro.web.tags.HasPermissionTag;
import org.apache.shiro.web.util.SavedRequest;
import org.apache.shiro.web.util.WebUtils;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.szd.base.entity.BaseUser;
import org.work.util.MD5;

import java.io.IOException;
import java.io.PrintWriter;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
import java.util.Set;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

@Controller
@RequestMapping(value = "base/Shiro")
public class ShiroController {

    @RequestMapping(value="/doShiroLogin",method= RequestMethod.POST)
    @ResponseBody
    public String doShiroLogin(@RequestBody BaseUser user, HttpServletRequest request){
        String msg = null;
        user = (BaseUser) request.getSession().getAttribute("wsBaseUser");
        UsernamePasswordToken token = new UsernamePasswordToken(user.getLoginName(), user.getPassword());
        token.setRememberMe(true);
        Subject subject = SecurityUtils.getSubject();
        try {
            subject.login(token);//登录
            if (subject.isAuthenticated()) {
                BaseUser baseUser2 = (BaseUser)SecurityUtils.getSubject().getPrincipals();
//                new SimpleAuthenticationInfo(user,user.getPassword(),user.getLoginName());
//                Set<String> roles = new HashSet<>();
//                Iterator<String> roleIterator=roles.iterator();
//                boolean flag=false;
//                while(roleIterator.hasNext()) {
//                    if (subject.hasRole(roleIterator.next())) {
//                        roles.add(subject)
//                    }
//                }
                if (subject.hasRole("role.admin")){
                    System.out.println("ok");
                }
                if(subject.isPermitted("create")){
                    System.out.println("ok");
                }
            }else{
                System.out.println("no");
            }
        } catch (IncorrectCredentialsException e) {
            msg = "登录密码错误. Password for account " + token.getPrincipal() + " was incorrect.";
            System.out.println(msg);
        } catch (ExcessiveAttemptsException e) {
            msg = "登录失败次数过多";
            System.out.println(msg);
        } catch (LockedAccountException e) {
            msg = "帐号已被锁定. The account for username " + token.getPrincipal() + " was locked.";
            System.out.println(msg);
        } catch (DisabledAccountException e) {
            msg = "帐号已被禁用. The account for username " + token.getPrincipal() + " was disabled.";
            System.out.println(msg);
        } catch (ExpiredCredentialsException e) {
            msg = "帐号已过期. the account for username " + token.getPrincipal() + "  was expired.";
            System.out.println(msg);
        } catch (UnknownAccountException e) {
            msg = "帐号不存在. There is no user with username of " + token.getPrincipal();
            System.out.println(msg);
        } catch (UnauthorizedException e) {
            msg = "您没有得到相应的授权!" + e.getMessage();
            System.out.println(msg);
        }
        return "success";
    }


    @RequestMapping(value="/ShiroDemoPermission",method= RequestMethod.GET)
//    权限为create和query
    @RequiresPermissions(value={"create","query"}, logical= Logical.OR)
    @ResponseBody
    public void ShiroDemoPermission(){
        System.out.println("权限为create或者query");
    }

    @RequestMapping(value="/ShiroDemoPermission2",method= RequestMethod.GET)
    @RequiresPermissions("other")
    @ResponseBody
    public void ShiroDemoPermission2(){
        System.out.println("权限为other");
    }

    @RequestMapping(value="/ShiroDemoRole",method= RequestMethod.GET)
    //    角色为admin或者test
    @RequiresRoles(value={"role.admin","role.test"}, logical= Logical.OR)
    @ResponseBody
    public void ShiroDemoRole(){
        System.out.println("角色为:role.admin或者role.test");
    }

    @RequestMapping(value="/ShiroDemoRole2",method= RequestMethod.GET)
    @RequiresRoles("role.test")
    @ResponseBody
    public void ShiroDemoRole2(){
        System.out.println("角色为:role.test");
    }



    /**
     * 权限异常
     */
//    配置权限异常返回json,否则跳转至在shiro.xml配置的路径
    @ExceptionHandler({ UnauthorizedException.class, AuthorizationException.class })
    public String authorizationException(HttpServletRequest request, HttpServletResponse response) {
        System.out.println( SecurityUtils.getSubject().getPrincipal());
        PrintWriter out = null;
        try {
            response.setCharacterEncoding("UTF-8");
            response.setContentType("application/json; charset=utf-8");
            out = response.getWriter();
            JSONObject jsonObject = new JSONObject();
            jsonObject.put("msg","没有权限");
            out.write(jsonObject.toString());
        } catch (IOException e) {
            e.printStackTrace();
        }
        return null;
    }
}

页面:

<%@ taglib prefix="shiro" uri="http://shiro.apache.org/tags" %>
<%@ page contentType="text/html; charset=UTF-8" %>
<!DOCTYPE html>
<html xmlns:v-on="http://www.w3.org/1999/xhtml" xmlns:v-bind="http://www.w3.org/1999/xhtml">

<head>
  <title>vueJs.html</title>
  <meta charset="UTF-8">
  <!--<link rel="stylesheet" type="text/css" href="./styles.css">-->
<meta name="renderer" content="webkit|ie-comp|ie-stand">
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<%--<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />--%>
<meta http-equiv="pragma" content="no-cache"/>
<meta http-equiv="cache-control" content="no-cache"/>
<meta http-equiv="expires" content="0"/>
<title>${appName}</title>
<script type="text/javascript" src="/js/jquery/jquery-1.9.1.min.js"></script>
<script type="text/javascript" src="/js/vue/vue.js"></script>

</head>
<body>
<%--<shiro:hasPermission name={"create","query"}>--%>
<%--create permssion,query permssion  <br>--%>
<%--</shiro:hasPermission>--%>
<div id="test">



  <shiro:hasRole name="role.admin">
    admin role  <button v-on:click="adminRole()">adminRoleTest</button><br>
  </shiro:hasRole>

  <shiro:hasRole name="role.user">
    user role <button v-on:click="userRole()">userRoleTest</button><br><br>
  </shiro:hasRole>

  <shiro:hasPermission name="create">
    create permssion  <button v-on:click="createPermssion()">createPermssionTest</button><br><br>
  </shiro:hasPermission>

  <shiro:hasPermission name="query">
    query permssion <button v-on:click="queryPermssion()">queryPermssionTest</button><br><br>
  </shiro:hasPermission>

  <shiro:hasPermission name="ok">
    ok permssion <button v-on:click="okPermssion()">okPermssionTest</button><br><br>
  </shiro:hasPermission>

  <button v-on:click="okPermssion()">okPermssionTest</button><br><br>
</div>

</body>

<script type="text/javascript">

    Vue.config.debug = true;//开启vue的debug模式
    var vm = new Vue({
                         el:"#test",
                         data : {
                             user : {}



                         },
                         methods : {
                             adminRole : function() {
                                 $.ajax({
                                            type : "get",
                                            url : "/base/Shiro/ShiroDemoRole",
//                                            data : JSON.stringify(),
                                            contentType:"application/json",
                                            success : function(data) {
                                            },
                                            error : function() {
                                                alert("请求失败");
                                            }
                                        });
                             },
                             userRole : function() {
                                 $.ajax({
                                            type : "get",
                                            url : "/base/Shiro/ShiroDemoRole",
                                            contentType:"application/json",
                                            success : function(data) {
                                            },
                                            error : function() {
                                                alert("请求失败");
                                            }
                                        });
                             },createPermssion : function() {
                                 $.ajax({
                                            type : "get",
                                            url : "/base/Shiro/ShiroDemoPermission",
                                            contentType:"application/json",
                                            success : function(data) {
                                            },
                                            error : function() {
                                                alert("请求失败");
                                            }
                                        });
                             },queryPermssion : function() {
                                 $.ajax({
                                            type : "get",
                                            url : "/base/Shiro/ShiroDemoPermission",
                                            contentType:"application/json",
                                            success : function(data) {
                                            },
                                            error : function() {
                                                alert("请求失败");
                                            }
                                        });
                             },okPermssion : function() {
                                 $.ajax({
                                            type : "get",
                                            url : "/base/Shiro/ShiroDemoPermission2",
                                            contentType:"application/json",
                                            success : function(data) {
                                                alert(data.msg);
                                            },
                                            error : function(data) {
                                                alert(data);
                                                alert("请求失败");
                                            }
                                        });
                             }
                         }
                     });

</script>


</html>

 

具体配置文件放置如下:

其他参考资料“:

https://www.sojson.com/shiro

http://blog.csdn.net/frankcheng5143/article/details/50836619(Shiro学习--与SpringMVC整合(数据库,Shiro注解和Shiro标签)

http://blog.csdn.net/kaka0509/article/details/70196884(使用shiro实现权限控制学习总结)

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值