03 shiro integrated into the spring

This article describes the integration of shiro and spring.

1, environmental constraints

  • win10 64-bit operating system
  • idea2018.1.5
  • jdk-8u162-windows-x64
  • spring4.2.4

    Premise constraints

  • Project to build a ssm

    2, Procedure

  • Add the following dependence in 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>
  • The following were added in web.xml filter 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>
  • Add a file applicaitonContext-shiro.xml in src / main / resources folder, as follows:
<?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>
  • Net.wanho.security.MyRealm.java added in src / main / java with the following contents:
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());
    }
}
  • Net.wanho.controller.UserController.java added in src / main / java with the following contents:
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();
    }
}
  • Net.wanho.controller.LoginController.java added in src / main / java with the following contents:
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";
    }
}

  • Net.wanho.entity.User.java added in src / main / java with the following contents:
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;
    }
}
  • In the src \ main \ added index1.html webapp folder, index2.html, index.jsp, the content will be able to distinguish.
  • In the src \ main \ webapp folder added login.jsp, reads as follows:
<%--
  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, start the test project as follows

  • Enter in your browser localhost: 8888 / asdfgh, Enter
    This is an invalid url, but the reader will see the page to jump to the login screen. This is the filter to shiro unregistered requests, forcing jump to the login screen
  • Enter in your browser localhost: 8888 / user / query, carriage return
    this is a valid url, but the reader will see the page to jump to the login screen. This is the filter to shiro unregistered requests, forcing jump to the login screen
  • In the login page, click on the "Login"
    page to jump to the index.jsp
  • In the browser again enter localhost: 8888 / user / query, Enter
    At this point the reader will see that this can detect data because the user has logged on.
  • In the browser re-enter localhost: 8888 / index1.html, carriage return
    at this time to jump to the index1.html, because "user: add" permission has been given the currently logged in user.
  • In the browser re-enter localhost: 8888 / index2.html, carriage return
    at this time to jump to the nopermission.jsp page because index2.html need to "admin" role, and our role is required to index2.html admin1, this restriction doGetAuthorizationInfo completion method of real MyRealm.

Guess you like

Origin www.cnblogs.com/alichengxuyuan/p/12519987.html