shiro篇:使用Shiro對一個SSM專案進行身份加密驗證

2020-10-16 12:00:45

Apache Shiro是一個強大且易用的Java安全框架,執行身份驗證、授權、密碼和對談管理

1.設定環境

1.1pom依賴

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>

    <groupId>org.example</groupId>
    <artifactId>1014_1_shirowebspring</artifactId>
    <version>1.0-SNAPSHOT</version>
    <packaging>war</packaging>

    <dependencies>
        <dependency>
            <groupId>org.apache.shiro</groupId>
            <artifactId>shiro-all</artifactId>
            <version>1.4.0</version>
            <type>pom</type>
        </dependency>
        <dependency>
            <groupId>org.slf4j</groupId>
            <artifactId>slf4j-api</artifactId>
            <version>1.7.12</version>
        </dependency>
        <dependency>
            <groupId>org.slf4j</groupId>
            <artifactId>slf4j-log4j12</artifactId>
            <version>1.7.12</version>
        </dependency>
        <dependency>
            <groupId>log4j</groupId>
            <artifactId>log4j</artifactId>
            <version>1.2.16</version>
        </dependency>
        <dependency>
            <groupId>commons-logging</groupId>
            <artifactId>commons-logging</artifactId>
            <version>1.2</version>
        </dependency>
        <!--spring-->
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-webmvc</artifactId>
            <version>4.3.5.RELEASE</version>
        </dependency>
        <dependency>
            <groupId>com.fasterxml.jackson.core</groupId>
            <artifactId>jackson-databind</artifactId>
            <version>2.9.8</version>
        </dependency>
    </dependencies>
</project>

1.2web.xml設定spring+spingMVC+亂碼過濾+shiroFilter過濾

<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns="http://xmlns.jcp.org/xml/ns/javaee"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_3_1.xsd"
         version="3.1">
    <!--spring-->
    <context-param>
        <param-name>contextConfigLocation</param-name>
        <param-value>classpath:applicationContext*.xml</param-value>
    </context-param>
    <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:springmvc-servlet.xml</param-value>
        </init-param>
    </servlet>
    <servlet-mapping>
        <servlet-name>springmvc</servlet-name>
        <url-pattern>/</url-pattern>
    </servlet-mapping>
<!--    亂碼處理-->
    <!--3.處理亂碼-->
    <filter>
        <filter-name>encodingFilter</filter-name>
        <filter-class>org.springframework.web.filter.CharacterEncodingFilter</filter-class>
        <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>

<!--    shiroFilter-->
    <filter>
        <filter-name>shiroFilter</filter-name>
        <filter-class>org.springframework.web.filter.DelegatingFilterProxy</filter-class>
    </filter>
    <filter-mapping>
        <filter-name>shiroFilter</filter-name>
        <url-pattern>/*</url-pattern>
    </filter-mapping>

    
    
    
    
</web-app>

1.3 Spring的設定:applicationContext-shiro.xml

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:context="http://www.springframework.org/schema/context"
       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
        http://www.springframework.org/schema/context
        http://www.springframework.org/schema/context/spring-context.xsd">

    <!--shiro+spring整合的核心設定-->
    <!--1.SecurityManager-->
    <bean id="securityManager" class="org.apache.shiro.web.mgt.DefaultWebSecurityManager">
        <!--設定realm-->
        <property name="realms" ref="myUerRealm"></property>
    </bean>
    <!--2.設定自定義realm,走資料庫  不用預設的iniRealm shiro.ini,不利於後期維護-->
    <bean id="myUerRealm" class="realm.MyRealm"></bean>

    <!--3.shiroFilter,shiro攔截後會把請求,交給該過濾器處理,id需要和web.xml中設定的名字一致-->
    <bean id="shiroFilter" class="org.apache.shiro.spring.web.ShiroFilterFactoryBean">
<!--        登入介面-->
        <property name="loginUrl" value="/login.jsp"></property>
<!--        沒有許可權的跳轉-->
        <property name="unauthorizedUrl" value="/unauthorized.jsp"></property>

        <property name="securityManager" ref="securityManager"></property>
        <property name="filterChainDefinitions">
<!--
            1.順序問題:  嚴格的(/** = authc)過濾器往後設定
            2.anon:     匿名存取,不登入就可以存取
            3.authc :   認證後存取
-->
            <value>
                /doLogin = anon
                /js/** = anon
                /** = authc
            </value>
        </property>
    </bean>


</beans>

1.4SpringMVC的環境springmvc-servlet.xml

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:context="http://www.springframework.org/schema/context"
       xmlns:mvc="http://www.springframework.org/schema/mvc"
       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
        http://www.springframework.org/schema/context
        http://www.springframework.org/schema/context/spring-context.xsd
        http://www.springframework.org/schema/mvc
        http://www.springframework.org/schema/mvc/spring-mvc.xsd">

    <context:component-scan base-package="controller"></context:component-scan>

    <mvc:annotation-driven></mvc:annotation-driven>

    <!--    靜態資源放行問題1-->
    <mvc:default-servlet-handler></mvc:default-servlet-handler>

    <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
        <property name="prefix" value="/"></property>
        <property name="suffix" value=".jsp"></property>
    </bean>
</beans>

2.建立一個自定義realm類

package realm;

import org.apache.shiro.authc.*;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;

/**
 * zt
 * 2020/10/14
 * 11:08
 */
public class MyRealm extends AuthorizingRealm {
    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals) {
        System.out.println("---------->授權");
        return null;
    }

    /**
     *subject.login(token);  在controller中查詢執行認證方法
     * @param token
     * @return
     * @throws AuthenticationException
     */
    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {
        System.out.println("---------->認證,登入");

        String username = (String) token.getPrincipal();
        String password = new String((char[])token.getCredentials());

        String u = "admin";//資料庫的,寫死
//        String p = "123";//資料庫
        String p = "3cb336337a3bdceb3c0b65bdcc5f122c";
        int isLock = 1;
        if(!username.equals(u)) {//賬號錯誤
            throw new UnknownAccountException("賬號異常");
        }
        if(!password.equals(p)) {//密碼錯誤
            throw new IncorrectCredentialsException("密碼錯誤");
        }
        if(isLock!=1){
            throw new LockedAccountException("賬戶鎖定");
        }

        SimpleAuthenticationInfo info = new SimpleAuthenticationInfo(username,password,this.getName());

        return info;
    }
}

3.建立controller

package controller;

import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.crypto.hash.Md5Hash;
import org.apache.shiro.subject.Subject;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;

/**
 * zt
 * 2020/10/14
 * 11:28
 */
@Controller
public class MyController {
    @RequestMapping("/doLogin")
    public String doLogin(String username,String password){
        System.out.println("登入");
        //1.shiro認證
        Subject subject = SecurityUtils.getSubject();
        //加密
        password = new Md5Hash(password, username, 2014).toString();
        System.out.println(password);
        //2.把使用者輸入的使用者名稱和密碼封裝成一個usernamePasswordToken物件
        UsernamePasswordToken token = new UsernamePasswordToken(username,password);
        //3.登入  查詢,執行認證方法
        subject.login(token);

        System.out.println(subject.isAuthenticated()?"登入成功":"登入失敗");
        return "success";
    }

}

4.寫一個頁面測試

login.jsp

<%--
  Created by IntelliJ IDEA.
  User: 49841
  Date: 2020/10/14
  Time: 11:40
  To change this template use File | Settings | File Templates.
--%>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
    <title>Title</title>
</head>
<body>

<form action="/doLogin" method="post">
    <input type="text" name="username" id="id"><br>
    <input type="text" name="password"  id="name"><br>

    <input type="submit" value="提交" id="btn">
</form>
</body>
</html>

success.jsp

<%--
  Created by IntelliJ IDEA.
  User: 49841
  Date: 2020/10/14
  Time: 11:31
  To change this template use File | Settings | File Templates.
--%>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<%--shiro標籤--%>
<%@taglib prefix="shiro" uri="http://shiro.apache.org/tags"%>
<html>
<head>
    <title>Title</title>
</head>
<body>
success
<shiro:principal></shiro:principal>,歡迎您!!!!!!
<shiro:authenticated>success</shiro:authenticated>
<shiro:guest>guest</shiro:guest>
</body>
</html>