您的位置:首页 > 编程语言 > Java开发

Shiro+Spring整合(超详细,有demo)

2017-11-02 16:22 162 查看
刚刚看了Shiro的入门视频,学习了了Shiro的一些知识,感谢Java_小锋老师的学习视频,在这里我分享一下我的学习心得,同时算对自己这俩天学习的总结,同时将Shiro整合到Spring中。

好了,我简单说一下大概需要学习的东西吧。Shiro的官网上的知识点很多。作为入门,可以先记住Shiro核心的点

1、权限认证



2、授权



3、permissions权限



4、Realm

现在开始配置:

第一步:配置Web.xml, shiro核心的配置就是第一个。所有的过滤都会经过org.springframework.web.filter.DelegatingFilterProxy

<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://java.sun.com/xml/ns/javaee" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" id="WebApp_ID" version="2.5">
<display-name>MyWeb</display-name>
<welcome-file-list>
<welcome-file>index.jsp</welcome-file>
</welcome-file-list>

<!-- shiro过滤器定义 ,一定要放在最前面-->
<filter>
<filter-name>shiroFilter</filter-name>
<filter-class>org.springframework.web.filter.DelegatingFilterProxy</filter-class>
<init-param>
<!-- 该值缺省为false,表示生命周期由SpringApplicationContext管理,设置为true则表示由ServletContainer管理 -->
<param-name>targetFilterLifecycle</param-name>
<param-value>true</param-value>
</init-param>
</filter>
<filter-mapping>
<filter-name>shiroFilter</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>

<!-- Spring配置文件 -->
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>classpath:applicationContext.xml</param-value>
</context-param>
<!-- 编码过滤器 -->
<filter>
<filter-name>encodingFilter</filter-name>
<filter-class>org.springframework.web.filter.CharacterEncodingFilter</filter-class>
<async-supported>true</async-supported>
<init-param>
<param-name>encoding</param-name>
<param-value>UTF-8</param-value>
</init-param>
</filter>
<filter-mapping>
<filter-name>encodingFilter</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
<!-- Spring监听器 -->
<listener>
<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>

<!-- 添加对springmvc的支持 -->
<servlet>
<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>
<async-supported>true</async-supported>
</servlet>
<servlet-mapping>
<servlet-name>springMVC</servlet-name>
<url-pattern>*.do</url-pattern>
</servlet-mapping>

</web-app>


第二步:配置applicationContext.xml,都有注释,其中Shiro连接约束配置就体现了,Shiro中的权限认证

和permissions权限的问题,请注意shiro过滤器里面的内容,后面我们会按照身份验证,角色验证和权限验证去演示。我已经提前在shiro过滤器里面配置好了。

<?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:p="http://www.springframework.org/schema/p"
xmlns:aop="http://www.springframework.org/schema/aop"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:jee="http://www.springframework.org/schema/jee"
xmlns:tx="http://www.springframework.org/schema/tx"
xsi:schemaLocation=" http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-4.0.xsd http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-4.0.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.0.xsd http://www.springframework.org/schema/jee http://www.springframework.org/schema/jee/spring-jee-4.0.xsd http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-4.0.xsd">

<!-- 自动扫描 -->
<context:component-scan base-package="com.web.*.service" />

<!-- 配置数据源 -->
<bean id="dataSource"
class="org.springframework.jdbc.datasource.DriverManagerDataSource">
<property name="driverClassName" value="com.mysql.jdbc.Driver"/>
<property name="url" value="jdbc:mysql://localhost:3306/tes_shiro"/>
<property name="username" value="root"/>
<property name="password" value="123456"/>
</bean>

<!-- 配置mybatis的sqlSessionFactory -->
<bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
<property name="dataSource" ref="dataSource" />
<!-- 自动扫描mappers.xml文件 -->
<property name="mapperLocations" value="classpath:com/web/mapper/*.xml"></property>
<!-- mybatis配置文件 -->
<property name="configLocation" value="classpath:mybatis-config.xml"></property>

</bean>

<!-- DAO接口所在包名,Spring会自动查找其下的类 -->
<bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
<property name="basePackage" value="com.web.*.dao" />
<property name="sqlSessionFactoryBeanName" value="sqlSessionFactory"></property>
</bean>

<!-- (事务管理)transaction manager, use JtaTransactionManager for global tx -->
<bean id="transactionManager"
class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
<property name="dataSource" ref="dataSource" />
</bean>

<!-- 继承自AuthorizingRealm的自定义Realm,即指定Shiro验证用户登录的类为自定义的MyRealm.java -->
<bean id="myRealm" class="com.web.demo.util.MyRealm"/>

<!-- 安全管理器 -->
<bean id="securityManager" class="org.apache.shiro.web.mgt.DefaultWebSecurityManager">
<property name="realm" ref="myRealm"/>
</bean>

<!-- Shiro过滤器 -->
<bean id="shiroFilter" class="org.apache.shiro.spring.web.ShiroFilterFactoryBean">
<!-- Shiro的核心安全接口,这个属性是必须的 -->
<property name="securityManager" ref="securityManager"/>
<!-- 身份认证失败,则跳转到登录页面的配置 -->
<property name="loginUrl" value="/index.jsp"/>
<!-- 权限认证失败,则跳转到指定页面 -->
<property name="unauthorizedUrl" value="/unauthor.jsp"/>
<!-- Shiro连接约束配置,即过滤链的定义 -->
<property name="filterChainDefinitions">
<value>
<!-- 执行/login的时候不需要任何身份 -->
/login=anon
<!-- 访问/admin*需要身份认证(既登录),admin*有点通配符的意思,就是admin或者admin1,admin2等,任何以admin开头的都需要身份认证-->
/admin*=authc
<!-- 访问/student需要角色为teacher才行 -->
/user/student=roles[teacher]
<!-- 访问/teacher需要有创建权限 -->
/teacher=perms["user:create"]
</value>
</property>
</bean>

<!-- 保证实现了Shiro内部lifecycle函数的bean执行 -->
<bean id="lifecycleBeanPostProcessor" class="org.apache.shiro.spring.LifecycleBeanPostProcessor"/>

<!-- 开启Shiro注解 -->
<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>

<!-- 配置事务通知属性 -->
<tx:advice id="txAdvice" transaction-manager="transactionManager">
<!-- 定义事务传播属性 -->
<tx:attributes>
<tx:method name="insert*" propagation="REQUIRED" />
<tx:method name="update*" propagation="REQUIRED" />
<tx:method name="edit*" propagation="REQUIRED" />
<tx:method name="save*" propagation="REQUIRED" />
<tx:method name="add*" propagation="REQUIRED" />
<tx:method name="new*" propagation="REQUIRED" />
<tx:method name="set*" propagation="REQUIRED" />
<tx:method name="remove*" propagation="REQUIRED" />
<tx:method name="delete*" propagation="REQUIRED" />
<tx:method name="change*" propagation="REQUIRED" />
<tx:method name="check*" propagation="REQUIRED" />
<tx:method name="get*" propagation="REQUIRED" read-only="true" />
<tx:method name="find*" propagation="REQUIRED" read-only="true" />
<tx:method name="load*" propagation="REQUIRED" read-only="true" />
<tx:method name="*" propagation="REQUIRED" read-only="true" />
</tx:attributes>
</tx:advice>

<!-- 配置事务切面 -->
<aop:config>
<aop:pointcut id="serviceOperation"
expression="execution(* com.web.*.service.*.*(..))" />
<aop:advisor advice-ref="txAdvice" pointcut-ref="serviceOperation" />
</aop:config>

</beans>


第三步:我们需要自定义的MyRealm,代码如下:

package com.web.demo.util;

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

import com.web.demo.model.User;
import com.web.demo.service.UserService;

public class MyRealm extends AuthorizingRealm{

@Autowired
private UserService userService;

/**
* 为当前登录的账号授予角色和权限
* 描述:此方法是继承AuthorizingRealm,所有的信息都是封装
*/
@Override
protected AuthorizationInfo doGetAuthorizationInfo(
PrincipalCollection principals) {
String userName = (String) principals.getPrimaryPrincipal();
SimpleAuthorizationInfo authorizationInfo = new SimpleAuthorizationInfo();
// 封装角色信息
authorizationInfo.setRoles(userService.getRoles(userName));
// 封装权限信息
authorizationInfo.setStringPermissions(userService
.getPermissions(userName));
return authorizationInfo;
}

/**
* 验证当前登录的用户
*/
@Override
protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {
String userName=(String)token.getPrincipal();
User user=userService.getByUserName(userName);
if(user!=null){
//参数说明,参数1:数据库获取用户名 ,参数2:数据库获取的密码,参数3:RealmName,这个随便起,无所谓。将这些参数传入,与用户输入的进行对比
AuthenticationInfo authcInfo=new SimpleAuthenticationInfo(user.getUserName(),user.getPassword(),"xx");
return authcInfo;
}else{
return null;
}
}

}


第四步:controller层的测试代码

package com.web.demo.controller;

import javax.servlet.http.HttpServletRequest;

import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.session.Session;
import org.apache.shiro.subject.Subject;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;

import com.web.demo.model.User;

/**
* 用户Controller层
* @author Administrator
*
*/
@Controller
@RequestMapping("/user")
public class UserController {

/**
* 用户登录
* @param user
* @param request
* @return
*/
@RequestMapping("/login")
public String login(User user,HttpServletRequest request){
Subject subject=SecurityUtils.getSubject();
UsernamePasswordToken token=new UsernamePasswordToken(user.getUserName(), user.getPassword());
try{
subject.login(token);
Session session=subject.getSession();
System.out.println("sessionId:"+session.getId());
System.out.println("sessionHost:"+session.getHost());
System.out.println("sessionTimeout:"+session.getTimeout());
session.setAttribute("info", "session的数据");
return "redirect:/success.jsp";
}catch(Exception e){
e.printStackTrace();
request.setAttribute("user", user);
request.setAttribute("errorMsg", "用户名或密码错误!");
return "index";
}
}

@RequestMapping("/student")
public String student(User user,HttpServletRequest request){
return "redirect:/demo/jsp/student.jsp";
}

}


第五步:success.jsp和student.jsp页面,

<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<%@ taglib prefix="shiro" uri="http://shiro.apache.org/tags" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Insert title here</title>
</head>
<body>
${info }
欢迎你!
<shiro:hasRole name="admin">
欢迎有admin角色的用户!<shiro:principal/>
</shiro:hasRole>
<shiro:hasPermission name="student:create">
欢迎有student:create权限的用户!<shiro:principal/>
</shiro:hasPermission>
</body>
</html>


上面是success.jsp代码。注意shiro也有jsp标签,比如就是判断当前页面用户是否是admin角色,比如判断当前用户是否拥有教师角色下的创建权限

student.jsp

<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<%@ taglib prefix="shiro" uri="http://shiro.apache.org/tags" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title></title>
</head>
<body>

您好,老师!我是role为teacher才能进入的页面
<%-- <shiro:hasRole name="admin">
欢迎有admin角色的用户!<shiro:principal/>
</shiro:hasRole>
<shiro:hasPermission name="student:create">
欢迎有student:create权限的用户!<shiro:principal/>
</shiro:hasPermission> --%>
</body>
</html>


好了,核心代码基本是贴完了,我这边演示一下,主要从身份验证,角色验证,权限验证三个方面去演示。

1、身份验证,测试。

我们先不登陆,直接访问controller,试试,会发现强制进入登陆页面,这就是身份验证





2、角色验证,我们写了一个只有拥有teacher的过滤,(见applicationContext.xml中的shiro过滤配置)。只有role为teacher的可以进入,测试。

我们先用role为admin的用户进入。



然后在浏览器里面直接输入:http://localhost:8080/MyWeb/user/student 会出现下面情况(权限不足),



unauthor.jsp是只有权限不足的情况下才会提示的页面。

我们再换role为teacher的用户登录、



然后再访问http://localhost:8080/MyWeb/user/student (权限验证成功,可以访问)



3.权限验证。在success.jsp中就有体现,发现admin和tea俩个用户登录之后的页面显示内容是不一样的。

admin登录后的样子:



tea登录后的样子



好了,暂时就到这么多了,我把我测试的Deam和数据库表上传上来,有兴趣的可以下载看看。我的项目是Maven的。如果本地没有配置Maven的需要先提前配置好Maven环境。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: