Shiro整合Spring

首先需要添加shiro的spring整合包。

要想在WEB应用中整合Spring和Shiro的话,首先需要添加一个由spring代理的过滤器如下:

<!-- The filter-name matches name of a ‘shiroFilter‘ bean inside applicationContext.xml -->
<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>

...

<!-- Make sure any request you want accessible to Shiro is filtered. /* catches all -->
<!-- requests.  Usually this filter mapping is defined first (before all others) to -->
<!-- ensure that Shiro works in subsequent filters in the filter chain:             -->
<filter-mapping>
    <filter-name>shiroFilter</filter-name>
    <url-pattern>/*</url-pattern>
</filter-mapping>

其次,就是在spring的配置文件中,加入shiro的配置。

<bean id="shiroFilter" class="org.apache.shiro.spring.web.ShiroFilterFactoryBean">
    <property name="securityManager" ref="securityManager"/>
    <!-- override these for application-specific URLs if you like:
    <property name="loginUrl" value="/login.jsp"/>
    <property name="successUrl" value="/home.jsp"/>
    <property name="unauthorizedUrl" value="/unauthorized.jsp"/> -->
    <!-- The ‘filters‘ property is not necessary since any declared javax.servlet.Filter bean  -->
    <!-- defined will be automatically acquired and available via its beanName in chain        -->
    <!-- definitions, but you can perform instance overrides or name aliases here if you like: -->
    <!-- <property name="filters">
        <util:map>
            <entry key="anAlias" value-ref="someFilter"/>
        </util:map>
    </property> -->
    <property name="filterChainDefinitions">
        <value>
            # some example chain definitions:
            /admin/** = authc, roles[admin]
            /docs/** = authc, perms[document:read]
            /** = authc
            # more URL-to-FilterChain definitions here
        </value>
    </property>
</bean>

<!-- Define any javax.servlet.Filter beans you want anywhere in this application context.   -->
<!-- They will automatically be acquired by the ‘shiroFilter‘ bean above and made available -->
<!-- to the ‘filterChainDefinitions‘ property.  Or you can manually/explicitly add them     -->
<!-- to the shiroFilter‘s ‘filters‘ Map if desired. See its JavaDoc for more details.       -->
<bean id="someFilter" class="..."/>
<bean id="anotherFilter" class="..."> ... </bean>
...

<bean id="securityManager" class="org.apache.shiro.web.mgt.DefaultWebSecurityManager">
    <!-- Single realm app.  If you have multiple realms, use the ‘realms‘ property instead. -->
    <property name="realm" ref="myRealm"/>
    <!-- By default the servlet container sessions will be used.  Uncomment this line
         to use shiro‘s native sessions (see the JavaDoc for more): -->
    <!-- <property name="sessionMode" value="native"/> -->
</bean>
<bean id="lifecycleBeanPostProcessor" class="org.apache.shiro.spring.LifecycleBeanPostProcessor"/>

<!-- Define the Shiro Realm implementation you want to use to connect to your back-end -->
<!-- security datasource: -->
<bean id="myRealm" class="...">
    ...
</bean>

下面就通过一个简单的实例来说明下shiro和spring的整合。

首先,web.xml文件如下:

<?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_3_0.xsd" id="WebApp_ID" version="3.0">
    <display-name>spring-shiro</display-name>
    <welcome-file-list>
        <welcome-file>login.jsp</welcome-file>
    </welcome-file-list>
    <!-- 定义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>/*</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如下:

<?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.fuwh.dao" />
    <context:component-scan base-package="com.fuwh.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/db_shiro"/>
        <property name="username" value="root"/>
        <property name="password" value="rootadmin"/>
    </bean>

    <!-- 自定义Realm -->
    <bean id="myJdbcRealm" class="com.fuwh.realm.MyJdbcRealm"/>  

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

    <!-- Shiro过滤器 -->
    <bean id="shiroFilter" class="org.apache.shiro.spring.web.ShiroFilterFactoryBean">
        <!-- Shiro的核心安全接口,这个属性是必须的 -->
        <property name="securityManager" ref="securityManager"/>
        <!-- 身份认证失败,则跳转到登录页面的配置 -->
        <property name="loginUrl" value="/login.jsp"/>
        <!-- Shiro过滤链的定义 -->
        <property name="filterChainDefinitions">
            <value>
                 /user/login**=anon
                 /user/info=perms["bumen:*"]
                 /**=authc
            </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>  

</beans>

自定义的realm如下:

package com.fuwh.realm;

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 org.springframework.stereotype.Component;

import com.fuwh.entity.User;
import com.fuwh.service.UserService;

@Component
public class MyJdbcRealm extends AuthorizingRealm{

    @Autowired
    private UserService userService;

    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals) {
        // TODO Auto-generated method stub
        SimpleAuthorizationInfo info=new SimpleAuthorizationInfo();
        info.setRoles(userService.getRoles(principals.getPrimaryPrincipal().toString()));
        info.setStringPermissions(userService.getPermissions(info.getRoles()));
        return info;
    }

    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {
        // TODO Auto-generated method stub
        User user=new User();
        user.setUsername(token.getPrincipal().toString());
        User currUser=userService.getUser(user);
        if(currUser!=null) {
            SimpleAuthenticationInfo info=new SimpleAuthenticationInfo(currUser.getUsername(),currUser.getPassword(),"xx");
            return info;
        }else{
            return null;
        }
    }

}

dao层如下:

package com.fuwh.dao.impl;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.LinkedHashSet;
import java.util.Set;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.datasource.DriverManagerDataSource;
import org.springframework.stereotype.Component;

import com.fuwh.dao.UserDao;
import com.fuwh.entity.User;

@Component("userDao")
public class UserDaoImpl implements UserDao{

    @Autowired
    DriverManagerDataSource dataSource;

    private Connection conn;
    private PreparedStatement ps;
    private ResultSet rs;

    public User getUser(User user) {
        // TODO Auto-generated method stub
        User currUser=new User();
        String sql="select * from users where username=?";
        try {
            conn=dataSource.getConnection();
            ps=conn.prepareStatement(sql);
            ps.setString(1, user.getUsername());
            rs=ps.executeQuery();
            while(rs.next()) {
                currUser.setUsername(rs.getString("username"));
                currUser.setPassword(rs.getString("password"));
            }
        } catch (SQLException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }finally {
            try {
                rs.close();
                ps.close();
            } catch (Exception e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
        }
        return currUser;
    }

    public Set<String> getRoles(String username) {
        // TODO Auto-generated method stub
        Set<String> roleSet=new LinkedHashSet<String>();
        String sql="select role_name from user_roles where username=?";
        try {
            conn=dataSource.getConnection();
            ps=conn.prepareStatement(sql);
            ps.setString(1, username);
            rs=ps.executeQuery();
            while(rs.next()) {
                roleSet.add(rs.getString("role_name"));
            }
        } catch (SQLException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }finally {
            try {
                rs.close();
                ps.close();
            } catch (Exception e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
        }
        return roleSet;
    }

    public Set<String> getPermissions(Set<String> roles) {
        // TODO Auto-generated method stub
        Set<String> permissionSet=new LinkedHashSet<String>();
        String sql="select permission from  roles_permissions where role_name=?";

        try {
            conn=dataSource.getConnection();
            ps=conn.prepareStatement(sql);
            for (String role : roles) {
                ps.setString(1, role);
                rs=ps.executeQuery();
                while(rs.next()) {
                    permissionSet.add(rs.getString("role_name"));
                }
            }
        } catch (SQLException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }finally {
            try {
                rs.close();
                ps.close();
            } catch (Exception e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
        }
        return permissionSet;
    }

}

controller层如下:

package com.fuwh.controller;

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 com.fuwh.entity.User;

@Controller
@RequestMapping("/user")
public class UserController {

    @RequestMapping("/login")
    public String login(User user,HttpServletRequest request) {
        Subject subject=SecurityUtils.getSubject();
        UsernamePasswordToken token=new UsernamePasswordToken(user.getUsername(), user.getPassword());
        subject.login(token);
        return "redirect:/static/success.jsp";
    }

    @RequestMapping("/info")
    public String info() {
        return "redirect:/static/info.jsp";
    }
}

详细代码可以参考:https://github.com/oukafu/shiro

时间: 2024-12-29 01:44:56

Shiro整合Spring的相关文章

shiro整合spring配置

shiro应用到项目中,一般都是通过spring来管理.下面就如何把shiro整理到spring中进行了讲解,及给出了配置的步骤: 一.pom.xml文件配置 本例子主要是介绍maven管理的web项目进行配置介绍,因此,首先需建立好一个maven管理的web项目(可参考本博客创建maven管理的web项目). pom.xml文件配置,主要是添加相关依赖的jar支持.因为整合到spring中需添加spring支持.具体配置参考配置代码: 1 <project xmlns="http://m

Spring+SpringMVC+Hibernate 与 shiro 整合步骤

通过这篇文章你可以了解到: SSH 三大框架(spring + springMVC + Hiberante) 与 shiro 安全验证框架如何整合: 通过一个示例,快速理解 shiro 框架. [TOC] 1. 业务需求分析 用户 N - 角色 N - 权限 N 我们可以想象一下,在平时工作中的职务,比如:业务经理,部门主管等,他们拥有很多的权力,而一个公司中不会只有一个业务经理,也不会只有一个部门主管,如果我们要给不同的人分配职务权力时,每次都是具体的条条框框去分配,人累心也累.而如果我们事先

项目一:第十四天 1.在realm中动态授权 2.Shiro整合ehcache 缓存realm中授权信息 3.动态展示菜单数据 4.Quartz定时任务调度框架—Spring整合javamail发送邮件 5.基于poi实现分区导出

1 Shiro整合ehCache缓存授权信息 当需要进行权限校验时候:四种方式url拦截.注解.页面标签.代码级别,当需要验证权限会调用realm中的授权方法   Shiro框架内部整合好缓存管理器,整合ehcache环境,只需要配置即可.     <dependency> <groupId>net.sf.ehcache</groupId> <artifactId>ehcache-core</artifactId> <version>

Shiro与Spring整合

Shiro引入Spring 添加jar包/maven配置 <!-- shiro支持 --> <dependency> <groupId>org.apache.shiro</groupId> <artifactId>shiro-core</artifactId> <version>1.2.4</version> </dependency> <dependency> <groupId&

Mybatis整合Spring 【转】

根据官方的说法,在ibatis3,也就是Mybatis3问世之前,Spring3的开发工作就已经完成了,所以Spring3中还是没有对Mybatis3的支持.因此由Mybatis社区自己开发了一个Mybatis-Spring用来满足Mybatis用户整合Spring的需求.下面就将通过Mybatis-Spring来整合Mybatis跟Spring的用法做一个简单的介绍. MapperFactoryBean 首先,我们需要从Mybatis官网上下载Mybatis-Spring的jar包添加到我们项

springMvc和shiro整合,shiro的realm不能自动注入的问题

最近研究shiro,一开头就遇到了大困难,调试了3小时.问题描述如下:shiro和spring mvc整合,shiro自定义了realm.其中自定义的realm里面居然不能使用@Autowired注解标签注入相关的用户service.百思不得其解,一项项跟踪,发现原来shiro 自定义realm的认证阶段属于filter,当时的spring bean还没有读取进来. 最后通过配置web.xml文件,把spring mvc的xml提高一点优先级,才最终解决了这个问题. 1 <!-- 配置sprin

业务逻辑:五、完成认证用户的动态授权功能 六、完成Shiro整合Ehcache缓存权限数据

一. 完成认证用户的动态授权功能 提示:根据当前认证用户查询数据库,获取其对应的权限,为其授权 操作步骤: 在realm的授权方法中通过使用principals对象获取到当前登录用户 创建一个授权信息对象 根据用户查询角色列表,并遍历角色列表 在循环体中将角色关键字添加到授权信息对象的角色属性中 根据用户查询权限列表,并遍历权限列表 在循环体中将权限关键字添加到授权信息对象的权限属性中 在角色与权限service类的根据用户查询角色与权限方法中判断用户是否为系统管理员 如果是系统管理员就查询出所

教你 Shiro 整合 SpringBoot,避开各种坑

最近搞了下 Shiro 安全框架,找了一些网上的博客文章,但是一到自己实现的时候就遇到了各种坑,需要各种查资料看源码以及各种测试. 那么这篇文章就教大家如何将 Shiro 整合到 SpringBoot 中,并避开一些小坑,这次实现了基本的登陆以及角色权限,往后的文章也讲解了其他的功能,如 <教你 Shiro + SpringBoot 整合 JWT> 附上源码:https://github.com/HowieYuan/shiro 依赖包 <dependency> <groupI

Spring Boot:整合Spring Security

综合概述 Spring Security 是 Spring 社区的一个顶级项目,也是 Spring Boot 官方推荐使用的安全框架.除了常规的认证(Authentication)和授权(Authorization)之外,Spring Security还提供了诸如ACLs,LDAP,JAAS,CAS等高级特性以满足复杂场景下的安全需求.另外,就目前而言,Spring Security和Shiro也是当前广大应用使用比较广泛的两个安全框架. Spring Security 应用级别的安全主要包含两