基于Spring整合Shiro安全框架
Shiro安全框架
Shiro網(wǎng)址
「http://shiro.apache.org/」
Shiro下載地址
「http://www.apache.org/dyn/closer.cgi/shiro/1.5.1/shiro-root-1.5.1-source-release.zip(jdk1.8+ maven3.03+)」
添加相應(yīng)的依賴
<packaging>pom</packaging>
<name>Shiro_Dome Maven Webapp</name>
<!-- FIXME change it to the project's website -->
<url>http://www.example.com</url>
<properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<maven.compiler.source>1.7</maven.compiler.source>
<maven.compiler.target>1.7</maven.compiler.target>
<spring.versions>5.1.0.RELEASE</spring.versions>
<shiro.version>1.5.1</shiro.version>
</properties>
<dependencies>
<!-- shiro安全權(quán)限框架依賴 -->
<dependency>
<groupId>org.apache.shiro</groupId>
<artifactId>shiro-core</artifactId>
<version>${shiro.version}</version>
</dependency>
<dependency>
<groupId>org.apache.shiro</groupId>
<artifactId>shiro-web</artifactId>
<version>${shiro.version}</version>
</dependency>
<dependency>
<groupId>org.apache.shiro</groupId>
<artifactId>shiro-spring</artifactId>
<version>${shiro.version}</version>
</dependency>
<!-- configure logging -->
<dependency>
<groupId>org.slf4j</groupId>
<artifactId>slf4j-log4j12</artifactId>
<version>1.6.1</version>
</dependency>
<dependency>
<groupId>log4j</groupId>
<artifactId>log4j</artifactId>
<version>1.2.17</version>
</dependency>
<!-- ehcache-core 依賴 -->
<!-- https://mvnrepository.com/artifact/org.apache.shiro/shiro-ehcache -->
<dependency>
<groupId>org.apache.shiro</groupId>
<artifactId>shiro-ehcache</artifactId>
<version>1.4.0</version>
</dependency>
<!-- spring整合shiro-->
<dependency>
<groupId>org.apache.shiro</groupId>
<artifactId>shiro-all</artifactId>
<version>${shiro.version}</version>
</dependency>
<!-- spring和 springmvc 依賴-->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context</artifactId>
<version>${spring.versions}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-aop</artifactId>
<version>${spring.versions}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-web</artifactId>
<version>${spring.versions}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-webmvc</artifactId>
<version>${spring.versions}</version>
</dependency>
<dependency>
<groupId>commons-logging</groupId>
<artifactId>commons-logging</artifactId>
<version>1.2</version>
</dependency>
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>servlet-api</artifactId>
<version>2.5</version>
</dependency>
</dependencies>
<build>
<finalName>Shiro_Dome</finalName>
<pluginManagement><!-- lock down plugins versions to avoid using Maven defaults (may be moved to parent pom) -->
<plugins>
<plugin>
<artifactId>maven-clean-plugin</artifactId>
<version>3.1.0</version>
</plugin>
<!-- see http://maven.apache.org/ref/current/maven-core/default-bindings.html#Plugin_bindings_for_war_packaging -->
<plugin>
<artifactId>maven-resources-plugin</artifactId>
<version>3.0.2</version>
</plugin>
<plugin>
<artifactId>maven-compiler-plugin</artifactId>
<version>3.8.0</version>
</plugin>
<plugin>
<artifactId>maven-surefire-plugin</artifactId>
<version>2.22.1</version>
</plugin>
<plugin>
<artifactId>maven-war-plugin</artifactId>
<version>3.2.2</version>
</plugin>
<plugin>
<artifactId>maven-install-plugin</artifactId>
<version>2.5.2</version>
</plugin>
<plugin>
<artifactId>maven-deploy-plugin</artifactId>
<version>2.8.2</version>
</plugin>
</plugins>
</pluginManagement>
</build>
<pluginManagement><!-- lock down plugins versions to avoid using Maven defaults (may be moved to parent pom) -->
<plugins>
<plugin>
<artifactId>maven-clean-plugin</artifactId>
<version>3.1.0</version>
</plugin>
<!-- see http://maven.apache.org/ref/current/maven-core/default-bindings.html#Plugin_bindings_for_war_packaging -->
<plugin>
<artifactId>maven-resources-plugin</artifactId>
<version>3.0.2</version>
</plugin>
<plugin>
<artifactId>maven-compiler-plugin</artifactId>
<version>3.8.0</version>
</plugin>
<plugin>
<artifactId>maven-surefire-plugin</artifactId>
<version>2.22.1</version>
</plugin>
<plugin>
<artifactId>maven-war-plugin</artifactId>
<version>3.2.2</version>
</plugin>
<plugin>
<artifactId>maven-install-plugin</artifactId>
<version>2.5.2</version>
</plugin>
<plugin>
<artifactId>maven-deploy-plugin</artifactId>
<version>2.8.2</version>
</plugin>
</plugins>
</pluginManagement>
搭建運(yùn)行的環(huán)境
創(chuàng)建Spring配置文件
<?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">
<!-- 配置SecurityManager-->
<bean id="securityManager" class="org.apache.shiro.web.mgt.DefaultWebSecurityManager">
<property name="cacheManager" ref="cacheManager"/>
<property name="realm" ref="jdbcRealm"></property>
<!-- 授權(quán)需要去讀配置SecurityManager的realms 所以要把realm 編寫在securityManager中-->
<!-- <property name="realms">-->
<!-- <list>-->
<!-- <ref bean="jdbcRealm"></ref>-->
<!-- </list>-->
<!-- </property>-->
</bean>
<!-- 配置cacheManager 會起到緩存效果-->
<bean id="cacheManager" class="org.apache.shiro.cache.ehcache.EhCacheManager">
<!-- 創(chuàng)建ehcache.xml文件 -->
<property name="cacheManagerConfigFile" value="classpath:ehcache.xml"/>
</bean>
<!--
配置realm
配置了自己編寫的實(shí)現(xiàn)realm的類
-->
<bean id="jdbcRealm" class="com.stone.shiro.web.realm.ShiroRealm">
<!-- 通過credentialsMatcher屬性進(jìn)行密碼加密操作-->
<property name="credentialsMatcher">
<!-- 通過HashedCredentialsMatcher來選擇加密方法-->
<bean class="org.apache.shiro.authc.credential.HashedCredentialsMatcher">
<!-- hashAlgorithmName指定加密方法-->
<property name="hashAlgorithmName" value="MD5"></property>
<!-- hashIterations指定加密次數(shù)-->
<property name="hashIterations" value="2"></property>
</bean>
</property>
</bean>
<!--
配置LifecycleBeanPostProcessor 可以自動的來調(diào)用配置在spring ioc 容器中 shiro bean的生命周期
-->
<bean id="lifecycleBeanPostProcessor" class="org.apache.shiro.spring.LifecycleBeanPostProcessor"/>
<!--
啟動ioc 容器中使用shiro的注解 ,并且要再配置了 LifecycleBeanPostProcessor才可以使用
-->
<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>
<!--
配置 ShiroFilter
loginUrl 沒有認(rèn)證時即沒有登錄時頁面
successUrl 登錄成功頁面
unauthorizedUrl 沒有權(quán)限頁面
注意點(diǎn) :
1. ShiroFilterFactoryBean的id必須和web.xml中配置的DelegatingFilterProxy <filter-name>標(biāo)簽值一致
-->
<bean id="shiroFilter" class="org.apache.shiro.spring.web.ShiroFilterFactoryBean">
<property name="securityManager" ref="securityManager"/>
<property name="loginUrl" value="/login.jsp"/>
<property name="successUrl" value="/index.jsp"/>
<property name="unauthorizedUrl" value="/unauthorized.jsp"/>
<!-- filterChainDefinitionMap控制shiro框架的訪問資源和權(quán)限管理-->
<property name="filterChainDefinitionMap" ref="filterChainDefinitionMap"></property>
<!--
配置哪些頁面收保護(hù),并且訪問這些頁面的權(quán)限
格式 :url = 訪問權(quán)限
anon 可以被匿名訪問
authc 必須認(rèn)證之后才能訪問
logout 退出登錄
采取的第一次優(yōu)先匹配,及有順序,編寫時需要注意
-->
<!-- 配死在xml中-->
<property name="filterChainDefinitions">
<value>
/login.jsp = anon
/shiro/login = anon
/shiro/logout = logout
/user.jsp = roles[user]
/admin.jsp = roles[admin]
/** =authc
</value>
</property>
</bean>
<!-- 配置一個LinkedHashMap bean 用來處理資源和權(quán)限 代替filterChainDefinitions, 通過實(shí)例工廠方式-->
<bean id="definitionMapBuilder" class="com.stone.shiro.web.factory.FilterChainDefinitionMapBuilder"></bean>
<!-- 實(shí)例工廠 -->
<bean id="filterChainDefinitionMap" factory-bean="definitionMapBuilder"
factory-method="buildfilterChainDefinitionMap"></bean>
<!-- 添加注解shiro權(quán)限bean-->
<bean class="com.stone.shiro.web.service.ShiroService"></bean>
</beans>
創(chuàng)建SpringMvc配置文件
<?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:context="http://www.springframework.org/schema/context"
xmlns:aop="http://www.springframework.org/schema/aop"
xmlns:mvc="http://www.springframework.org/schema/mvc"
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-4.3.xsd
http://www.springframework.org/schema/aop
http://www.springframework.org/schema/aop/spring-aop.xsd
http://www.springframework.org/schema/mvc
http://www.springframework.org/schema/mvc/spring-mvc-4.3.xsd">
<!-- mvc掃描包 -->
<context:component-scan base-package="com.stone.shiro.web"></context:component-scan>
<!-- mvc視圖解析器 -->
<bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name="prefix" value="/"></property>
<property name="suffix" value=".jsp"></property>
</bean>
<!-- mvc基礎(chǔ)配置 -->
<mvc:annotation-driven></mvc:annotation-driven>
<mvc:default-servlet-handler></mvc:default-servlet-handler>
</beans><?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:context="http://www.springframework.org/schema/context"
xmlns:aop="http://www.springframework.org/schema/aop"
xmlns:mvc="http://www.springframework.org/schema/mvc"
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-4.3.xsd
http://www.springframework.org/schema/aop
http://www.springframework.org/schema/aop/spring-aop.xsd
http://www.springframework.org/schema/mvc
http://www.springframework.org/schema/mvc/spring-mvc-4.3.xsd">
<!-- mvc掃描包 -->
<context:component-scan base-package="com.stone.shiro.web"></context:component-scan>
<!-- mvc視圖解析器 -->
<bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name="prefix" value="/"></property>
<property name="suffix" value=".jsp"></property>
</bean>
<!-- mvc基礎(chǔ)配置 -->
<mvc:annotation-driven></mvc:annotation-driven>
<mvc:default-servlet-handler></mvc:default-servlet-handler>
</beans>
日志代碼
handlers = org.apache.juli.FileHandler, java.util.logging.ConsoleHandler
############################################################
# Handler specific properties.
# Describes specific configuration info for Handlers.
############################################################
org.apache.juli.FileHandler.level = FINE
org.apache.juli.FileHandler.directory = ../logs
org.apache.juli.FileHandler.prefix = error-debug.
java.util.logging.ConsoleHandler.level = FINE
java.util.logging.ConsoleHandler.formatter = java.util.logging.SimpleFormatter
創(chuàng)建配置資源和權(quán)限所需要的Bean
package com.stone.shiro.web.factory;
import java.util.LinkedHashMap;
/*
配置資源和權(quán)限需要的bean
*/
public class FilterChainDefinitionMapBuilder
{
public LinkedHashMap<String,Object> buildfilterChainDefinitionMap(){
// 必須為LinkedHashMap
LinkedHashMap<String,Object> map = new LinkedHashMap();
// 假裝查詢數(shù)據(jù)庫,從數(shù)據(jù)庫中添加資源和權(quán)限
map.put("/login.jsp","anon");
map.put("/shiro/login","anon");
map.put("/shiro/logout","logout");
map.put("/user.jsp","authc,roles[user]"); //認(rèn)證并且必須為角色為user
map.put("/admin.jsp","authc,roles[admin]");//認(rèn)證并且必須為角色為user
map.put("/success.jsp","user");//自動登錄一樣可以進(jìn)入
map.put("/**","authc");
return map;
}
}
創(chuàng)建認(rèn)證和授權(quán)的類
package com.stone.shiro.web.realm;
import org.apache.shiro.authc.*;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.crypto.hash.SimpleHash;
import org.apache.shiro.realm.AuthenticatingRealm;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.realm.Realm;
import org.apache.shiro.subject.PrincipalCollection;
import org.apache.shiro.util.ByteSource;
import java.util.HashSet;
import java.util.Set;
// 如果只需要認(rèn)證可以只繼承AuthorizingRealm類
public class ShiroRealm extends AuthorizingRealm
{
// 認(rèn)證方法
@Override
protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token)
throws AuthenticationException {
// 在認(rèn)證時,shiro封裝的UsernamePasswordToken會保存到AuthenticationToken中
// 1.把AuthenticationToken重新轉(zhuǎn)換為UsernamePasswordToken
UsernamePasswordToken uptoken= (UsernamePasswordToken) token;
// 2.從UsernamePasswordToken中獲取username
String username = uptoken.getUsername();
// 3.從數(shù)據(jù)庫中獲取數(shù)據(jù)信息
System.out.println("模擬從數(shù)據(jù)庫中獲取數(shù)據(jù)信息 username " +username+"所對應(yīng)的用戶信息");
// 4.用戶判斷
if("zs".equals(username)){
throw new LockedAccountException("此用戶被鎖定");
}else if("aa".equals(username)){
throw new UnknownAccountException("用戶不存在");
}
// 5.根據(jù)用戶的判斷情況,來構(gòu)建AuthenticationInfo對象并返回 通過情況使用SimpleAuthenticationInfo
/*
SimpleAuthenticationInfo參數(shù):
1.Object principal:認(rèn)證的實(shí)體信息 可以是username
2.Object credentials: 密碼 password
3.ByteSource credentialssalt :鹽值加密最后結(jié)果
4.String realmName:當(dāng)前realm對象的name,調(diào)用父類的方法即可
6.Object hashedCredentials :計(jì)算的鹽值
*/
Object principal = username; // 用戶
// 獲取鹽值加密密碼
Object credentials= null;
if("shij".equals(username)){
credentials = shiroMd5("MD5", "123456", "shij", 2);
}else if("user".equals(username)){
credentials= shiroMd5("MD5","123456","user",2);
}else if("admin".equals(username)){
credentials= shiroMd5("MD5","123456","admin",2);
}
// Object credentials="4280d89a5a03f812751f504cc10ee8a5"; // 加密后密碼
// 當(dāng)前realm對象的name
String realmName=getName();
// 鹽值
ByteSource credentialssalt = ByteSource.Util.bytes(username); // 得到輸入賬號的鹽值
// SimpleAuthenticationInfo saif=new SimpleAuthenticationInfo(principal,credentials,realmName);
SimpleAuthenticationInfo saif=new SimpleAuthenticationInfo(principal,credentials,credentialssalt,realmName);
return saif;
}
public static void main(String [] agrs){
/*
SimpleHash方法查看加密結(jié)果
String algorithmName:加密的方法
Object source:需要加密的內(nèi)容
Object salt:鹽值 ByteSource.Util.bytes 可以獲取鹽值
int hashlterations:加密次數(shù)
*/
String algorithmName = "MD5";//4280d89a5a03f812751f504cc10ee8a5
Object source="123456";
Object salt= ByteSource.Util.bytes("shij");
int hashlterations=2;
Object result=new SimpleHash(algorithmName,source,salt,hashlterations);
System.out.println(algorithmName+"加密方法,加密"+source+"\t"+hashlterations+"次之后的的結(jié)果為:"+result);
}
public static Object shiroMd5(String algorithmName, Object source,Object saltValue, int hashlterations){
Object salt= ByteSource.Util.bytes(saltValue);
Object result=new SimpleHash(algorithmName,source,salt,hashlterations);
return result;
}
public static Object shiroMd5(String algorithmName, Object source, int hashlterations){
Object salt = null;
Object result=new SimpleHash(algorithmName,source,salt,hashlterations);
return result;
}
// 授權(quán)方法
@Override
protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals)
{
// 1.從PrincipalCollection中獲取登時信息
Object primaryPrincipal = principals.getPrimaryPrincipal();
// 2.利用登陸的用戶信息來獲取當(dāng)前登陸用戶的角色
Set<String> roles=new HashSet<>();
if("admin".equals(primaryPrincipal)){
// 添加角色
roles.add("admin");
}
if("user".equals(primaryPrincipal) || "shij".equals(primaryPrincipal)){
// 添加角色
roles.add("user");
}
// 3.創(chuàng)建SimpleAuthorizationInfo,并設(shè)置reles屬性
SimpleAuthorizationInfo sainfo=new SimpleAuthorizationInfo(roles);
// 4.返回SimpleAuthorizationInfo對象
return sainfo;
}
}
創(chuàng)建Service層
package com.stone.shiro.web.service;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authz.annotation.RequiresRoles;
import org.apache.shiro.session.Session;
public class ShiroService
{
/*
@RequiresRoles 必須要有什么角色才能進(jìn)行訪問
*/
@RequiresRoles({"user"})
public void getMethod(){
// 測試shiro session 2. 得到session
Session session = SecurityUtils.getSubject().getSession();
Object key = session.getAttribute("key");
System.out.println("shiro service .... \t session的值 "+key);
}
}
創(chuàng)建控制層
package com.stone.shiro.web.controller;
import com.stone.shiro.web.service.ShiroService;
import com.sun.net.httpserver.HttpsServer;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.authz.annotation.RequiresRoles;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import javax.servlet.http.HttpSession;
@Controller
@RequestMapping("/shiro")
public class LoginController
{
@Autowired
private ShiroService shiroService;
@RequestMapping("/testShiroAnnotation")
public String testShiroAnnotation(HttpSession session){
// 測試shiro session 1. 設(shè)置session
session.setAttribute("key","shiroValue");
shiroService.getMethod();
return "ShiroAnnotation";
}
@RequestMapping("/login")
public String shiroLogin(@RequestParam("username") String username, @RequestParam("password") String password){
// 1.獲取shiro框架對外api Subject
Subject subject = SecurityUtils.getSubject();
// 2.進(jìn)行權(quán)限認(rèn)證
// 2.1isAuthenticated判斷用戶是否已被認(rèn)證,即是否登錄
if(!subject.isAuthenticated()){
// 2.2吧用戶名密碼封裝到UsernamePasswordToken中 shiro框架會吧UsernamePasswordToken封裝的內(nèi)容自動封裝到AuthenticatingRealm類的doGetAuthenticationInfo方法的形參中
UsernamePasswordToken token=new UsernamePasswordToken(username,password);
// setRememberMe容許實(shí)現(xiàn)自動登錄
token.setRememberMe(true);
try
{
// 2.3執(zhí)行登錄
subject.login(token);
return "redirect:/success.jsp";
}catch (Exception e){
System.out.println("登錄失敗 \t" +e.getMessage());
}
}
return "/login";
}
}
創(chuàng)建登錄頁面
<%--
Created by IntelliJ IDEA.
User: Administrator
Date: 2020/3/10
Time: 22:50
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>
<h3> login page /</h3>
<form action="shiro/login" method="post">
用戶 : <input type="text" name="username"/> <br/>
密碼 :<input type="password" name="password"/> <br/>
<input type="submit" name="登錄"/> <br/>
</form>
</body>
</html>
創(chuàng)建登錄成功的頁面
<%--
Created by IntelliJ IDEA.
User: Administrator
Date: 2020/3/11
Time: 15:54
To change this template use File | Settings | File Templates.
--%>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<%@ taglib uri="http://shiro.apache.org/tags" prefix="shiro"%>
<html>
<head>
<title>Title</title>
</head>
<body>
<h3>登錄成功</h3> <br/>
<%--
principal:登陸用戶名
hasRole角色權(quán)限
--%>
歡迎你 :<shiro:principal></shiro:principal> <br/>
<shiro:hasRole name="user">
<a href="user.jsp">user</a> <br/>
</shiro:hasRole>
<shiro:hasRole name="admin">
<a href="admin.jsp">admin</a> <br/>
</shiro:hasRole>
<a href="shiro/testShiroAnnotation">ShiroAnnotation</a><br/>
<a href="shiro/logout">退出登錄</a><br/>
</body>
</html>
完
如果你覺得這篇內(nèi)容對你挺有啟發(fā),我想邀請你幫我三個小忙:
點(diǎn)個【在看】,或者分享轉(zhuǎn)發(fā),讓更多的人也能看到這篇內(nèi)容
關(guān)注公眾號【園碼生活】,不定期分享原創(chuàng)&精品技術(shù)文章。
覺得文章不錯可以分享到朋友圈讓更多的小伙伴看到哦~
評論
圖片
表情
