03 shiro整合到spring

本文将介绍shiro与spring的整合。

1、环境约束

  • win10 64位操作系统
  • idea2018.1.5
  • jdk-8u162-windows-x64
  • spring4.2.4

    前提约束

  • 搭建一个ssm工程

    2、操作步骤

  • 在pom.xml中加入以下依赖:
        <dependency>
            <groupId>org.apache.shiro</groupId>
            <artifactId>shiro-ehcache</artifactId>
            <version>1.2.2</version>
        </dependency>
        <dependency>
            <groupId>org.apache.shiro</groupId>
            <artifactId>shiro-web</artifactId>
            <version>1.3.2</version>
        </dependency>
        <dependency>
            <groupId>org.apache.shiro</groupId>
            <artifactId>shiro-spring</artifactId>
            <version>1.3.2</version>
        </dependency>
        <dependency>
            <groupId>org.slf4j</groupId>
            <artifactId>slf4j-log4j12</artifactId>
            <version>1.6.4</version>
        </dependency>
        <dependency>
            <groupId>commons-logging</groupId>
            <artifactId>commons-logging</artifactId>
            <version>1.1.1</version>
        </dependency>
  • 在web.xml中加入以下shiro过滤器
    <!--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>
  • 在src/main/resources文件夹下加入一个文件applicaitonContext-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.xsd">
       <!--自定义realm-->
    <bean id="userRealm" class="net.wanho.security.MyRealm">
    </bean>

    <!--缓存管理-->
    <bean id="cacheManager" class="org.apache.shiro.cache.MemoryConstrainedCacheManager"/>

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

    <!--shiro的上下文(securityUtils.setSecurityManager)-->
    <bean class="org.springframework.beans.factory.config.MethodInvokingFactoryBean">
        <property name="staticMethod" value="org.apache.shiro.SecurityUtils.setSecurityManager"/>
        <property name="arguments" ref="securityManager"/>
    </bean>



    <!--shiro的web过滤器-->
    <bean id="shiroFilter" class="org.apache.shiro.spring.web.ShiroFilterFactoryBean">
        <property name="securityManager" ref="securityManager"/>
        <!-- loginUrl认证提交地址,如果没有认证将会请求此地址进行认证-->
        <property name="loginUrl" value="/login.jsp"/>
        <!-- 通过unauthorizedUrl指定没有权限操作时跳转页面-->
        <property name="unauthorizedUrl" value="/nopermission.jsp"/>
        <property name="filterChainDefinitions">
            <value>
                /login = anon
                /index1.html = perms[user:add]
                /index2.html = roles[admin]
                /** = user
            </value>
        </property>
    </bean>

    <!--    异常处理-->
    <bean class="org.springframework.web.servlet.handler.SimpleMappingExceptionResolver">
        <property name="exceptionMappings">
            <props>
                <prop key="org.apache.shiro.authc.UnknownAccountException">/unknownaccount</prop>
                <prop key="org.apache.shiro.authc.IncorrectCredentialsException">/incorrectpwd</prop>
                <prop key="org.apache.shiro.authz.UnauthorizedException">/nopermission</prop>
            </props>
        </property>
    </bean>

    <bean class="org.apache.shiro.spring.security.interceptor.AuthorizationAttributeSourceAdvisor">
        <property name="securityManager" ref="securityManager"/>
    </bean>

    <bean class="org.springframework.aop.framework.autoproxy.DefaultAdvisorAutoProxyCreator" depends-on="lifecycleBeanPostProcessor">
        <property name="proxyTargetClass" value="true" />
    </bean>

    <!--shiro生命周期-->
    <bean id="lifecycleBeanPostProcessor" class="org.apache.shiro.spring.LifecycleBeanPostProcessor"/>
</beans>
  • 在src/main/java中加入net.wanho.security.MyRealm.java,内容如下:
package net.wanho.security;

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;

public class MyRealm extends AuthorizingRealm {

    //授权
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {
        SimpleAuthorizationInfo info = new SimpleAuthorizationInfo();
        //这里暂时为了代替数据库查询而将数据写死,实际使用中,要去数据库查询角色是否是admin1,权限是否是user:add
        info.addRole("admin1");
        info.addStringPermission("user:add");
        return info;
    }

    //认证
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authenticationToken) throws AuthenticationException {
        UsernamePasswordToken token = (UsernamePasswordToken) authenticationToken;
        String pwd = new String((char[]) token.getCredentials());
        String username = (String) token.getPrincipal();
        //这里暂时为了代替数据库查询而将数据写死,实际使用中,要去数据库查询账号密码是否是zhangli以及123456
        if (!"zhangli".equals(username)) {
            throw new UnknownAccountException();
        }
        if (!"123456".equals(pwd)) {
            throw new IncorrectCredentialsException();
        }
        return new SimpleAuthenticationInfo(username, pwd, getName());
    }
}
  • 在src/main/java中加入net.wanho.controller.UserController.java,内容如下:
package net.wanho.controller;

import net.wanho.entity.User;
import net.wanho.service.UserService;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.annotation.Resource;
import java.util.List;

@Controller
public class UserController {

    @Resource
    UserService userService;

    @RequestMapping("/user/query")
    @ResponseBody
    public List<User> queryUsers() throws Exception {
        return userService.queryUsers();
    }
}
  • 在src/main/java中加入net.wanho.controller.LoginController.java,内容如下:
package net.wanho.controller;

import net.wanho.entity.User;
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 org.springframework.web.bind.annotation.RequestMethod;

@Controller
public class LoginController {
    @RequestMapping(value="/login",method = RequestMethod.POST)
    public String login(User user)
    {
        UsernamePasswordToken token = new UsernamePasswordToken(user.getAccount(), user.getPassword());
        Subject subject = SecurityUtils.getSubject();
        subject.login(token);
        return "redirect:index.jsp";
    }
}

  • 在src/main/java中加入net.wanho.entity.User.java,内容如下:
package net.wanho.entity;

import java.io.Serializable;

public class User implements Serializable {
    private int id;
    private String name;
    private String account;
    private String password;

    public User(int id, String name) {
        this.id = id;
        this.name = name;
    }

    public User() {
    }

    public int getId() {
        return id;
    }

    public void setId(int id) {
        this.id = id;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public String getAccount() {
        return account;
    }

    public void setAccount(String account) {
        this.account = account;
    }

    public String getPassword() {
        return password;
    }

    public void setPassword(String password) {
        this.password = password;
    }
}
  • 在src\main\webapp文件夹下加入index1.html,index2.html,index.jsp,内容能区分就可以。
  • 在src\main\webapp文件夹下加入login.jsp,内容如下:
<%--
  Created by IntelliJ IDEA.
  User: zhangli
  Date: 2017/11/6
  Time: 11:05
  To change this template use File | Settings | File Templates.
--%>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
    <title></title>
</head>
<body>
<form action="/user/query" method="post">
  <input type="text" name="account" value="zhangli" />
  <input type="text" name="password" value="123456" />
  <input type="submit" value="提交" />
</form>
</body>
</html>

3、启动项目按如下步骤测试

  • 在浏览器中输入localhost:8888/asdfgh,回车
    这是无效的url,但读者会看到页面跳转到了登录界面。这就是shiro对未登录的请求进行的过滤,强制跳转到登录界面
  • 在浏览器中输入localhost:8888/user/query,回车
    这是有效的url,但读者会看到页面跳转到了登录界面。这就是shiro对未登录的请求进行的过滤,强制跳转到登录界面
  • 在登录页面,直接点击“登录”
    页面跳转到了index.jsp
  • 在浏览器中再次输入localhost:8888/user/query,回车
    此时读者便会看到这次能查出数据,因为用户已经登录过。
  • 在浏览器中再次输入localhost:8888/index1.html,回车
    此时跳转到了index1.html,因为"user:add"的权限已经被赋予了当前登录用户。
  • 在浏览器中再次输入localhost:8888/index2.html,回车
    此时跳转到了nopermission.jsp页面,因为index2.html需要"admin"角色,而我们给index2.html要求的角色是admin1,这个限制实在MyRealm的doGetAuthorizationInfo方法中完成。

猜你喜欢

转载自www.cnblogs.com/alichengxuyuan/p/12519987.html
今日推荐