spring整合shiro框架

上一篇文章已经对shiro框架做了一定的介绍,这篇文章讲述使用spring整合shiro框架,实现用户认证已经权限控制

1.搭建环境

这里不在赘述spring环境的搭建,可以简单的搭建一个ssm框架,整合后进行简单的测试

1.1 添加依赖

<dependency>
    <groupId>org.apache.shiro</groupId>
    <artifactId>shiro-spring</artifactId>
    <version>1.3.2</version>
</dependency>
<!--shiro核心包-->
<dependency>
    <groupId>org.apache.shiro</groupId>
    <artifactId>shiro-core</artifactId>
    <version>1.3.2</version>
</dependency>

1.2 web.xml配置

在web.xml中添加如下过滤器,注意filter-name的值是shiroFilter

<!-- Shiro Security filter filter-name这个名字的值将来还会在spring中用到-->
 <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>

这个过滤器拦截所有的请求,根据filter-name也就是shiroFilter转发到shiro的配置文件中的一个名字也为shiroFilter的ShiroFilterFactoryBean,在下面的配置文件中有体现

1.3 Spring整合shiro

在export_manager_web的resources下的spring文件夹创建配置文件applicationContext-shiro.xml

这是我的项目下的配置,这个配置文件应该在resources下,在项目启动是被加载

<?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:aop="http://www.springframework.org/schema/aop"
       xsi:schemaLocation="
        http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
        http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop.xsd">
    
<!-- filter-name这个名字的值来自于web.xml中filter的名字 -->
  <bean id="shiroFilter" class="org.apache.shiro.spring.web.ShiroFilterFactoryBean">
    <property name="securityManager" ref="securityManager"/>
    <!--登录页面 如果没有登录 访问项目的方法或页面 直接跳转到这个页面 -->
    <property name="loginUrl" value="/login.jsp"></property>
    <!--登录后 在访问没有经过授权的方法或页面时 直接跳转到这个页面 -->
    <property name="unauthorizedUrl" value="/unauthorized.jsp"></property>
    <property name="filterChainDefinitions">
      <!-- /**代表下面的多级目录也过滤 -->
      <value>
        /login.jsp = anon
        /css/** = anon
        /img/** = anon
        /plugins/** = anon
        /make/** = anon
        /login.do = anon        
        /** = authc
      </value>
    </property>
  </bean> 

<!-- 引用自定义的realm -->
  <bean id="saasRealm" class="cn.test.realm.SaasRealm"/>

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

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

  <!-- 生成代理,通过代理进行控制 -->
  <bean class="org.springframework.aop.framework.autoproxy.DefaultAdvisorAutoProxyCreator"
     depends-on="lifecycleBeanPostProcessor">
    <property name="proxyTargetClass" value="true"/>
  </bean>

  <aop:aspectj-autoproxy proxy-target-class="true"/>
</beans>

2.完成shiro认证操作

2.1 在LoginController编写login登录方法

@RequestMapping("/login")
   public String login(String email, String password) {
//     做非空判断
        if(StringUtils.isEmpty(email)||StringUtils.isEmpty(password)){
            request.setAttribute("error","邮箱或密码不能为空");
            return "forward:login.jsp";
        }
//        使用shiro的认证方式:1、创建令牌  2、获取主题  3、开始认证
//              Md5Hash也是shiro框架提供的加密方式     
        password = new Md5Hash(password, email, 2).toString();//把页面上输入的明文的密码转成密文的
        UsernamePasswordToken token = new UsernamePasswordToken(email,password);//创建令牌
        Subject subject = SecurityUtils.getSubject();//获取主题
        try {
          //开始认证,会进入用户自定义的realm中的认证方法完成认证,认证失败会抛出异常
            subject.login(token);
        } catch (AuthenticationException e) {
//            e.printStackTrace();
            request.setAttribute("error","邮箱或者密码有误");
            return "forward:login.jsp";
        }       
        User user = (User) subject.getPrincipal(); //从shiro中获取当前登录人
//        把当前登录人放入到session
        session.setAttribute("loginUser",user);
//              下面是对权限的管理     
        List<Module> moduleList = moduleService.findModuleListByUser(user);
        session.setAttribute("modules",moduleList);
        return "home/main";
  }

2.2 自定义realm

创建一个类继承一个父类AuthorizingRealm,实现父类的两个方法,一个关于认证,一个关于授权的,这个类就是自定义的realm,下面是我自定义realm的内容

import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.*;
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 java.util.List;

public class SaasRealm extends AuthorizingRealm {

    @Autowired
    private UserService userService;

//    认证 ,在方法中完成email和password的校验
    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authenticationToken) throws AuthenticationException {
        System.out.println("+++++进入了认证方法AuthenticationInfo");
//          通过参数获取用户输入的用户名和密码
        UsernamePasswordToken token = (UsernamePasswordToken) authenticationToken;
        String email = token.getUsername();
        String password_page = new String(token.getPassword());
        User user = userService.findByEmail(email); //从数据库中查询
        if(user!=null){
//            匹配密码
            String password_db = user.getPassword();
            if(password_db.equals(password_page)){
              //Object principal, Object credentials 密码, String realmName 当前realm的类名
                return new SimpleAuthenticationInfo(user,password_db,getName()); 
            }
        }
        return null; //没有用户
    }

//    授权
    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {
        return null;
    }

}

定义过realm之后将Realm交给IOC容器并且受securityManager的管理

<!-- 引用自定义的realm-->
    <bean id="saasRealm" class="com.itheima.controller.realm.SaasRealm"/>


    <bean id="securityManager" class="org.apache.shiro.web.mgt.DefaultWebSecurityManager">
         <property name="realm" ref="saasRealm"/>
        <!--将缓存对象添加到管理者的属性中-->
        <property name="cacheManager" ref="cacheManager"/>
    </bean>

2.3 退出登录

在LoginController中的写logout方法

@RequestMapping(value="/logout",name="用户登出")
public String logout(){
  SecurityUtils.getSubject().logout();//登出
  return "forward:login.jsp";
}

到这里,使用shior框架完成用户的认证已经完成,下面来实现使用shiro框架进行授权管理

3.基于shiro的用户授权

控制权限主要有两种方式,xml配置和注解

3.1.xml配置

3.2注解配置

最后:

1.可以使用shiro的标签库实现细颗粒度的控制,使用的时候可以参考我上一篇文章中介绍的每一个标签的作用来实现,记得引入标签库

2.如果shiro自带的十个过滤器不能满足你的需求,你可以自定义过滤器,实现自己的功能

猜你喜欢

转载自www.cnblogs.com/changchangchang/p/12023508.html