Shiro簡介
- Apache Shiro是一個強大且易用的Java安全框架,執(zhí)行身份驗證、授權(quán)、密碼和會話管理
- 三個核心組件:Subject, SecurityManager 和 Realms
- Subject代表了當前用戶的安全操作
- SecurityManager管理所有用戶的安全操作,是Shiro框架的核心,Shiro通過SecurityManager來管理內(nèi)部組件實例,并通過它來提供安全管理的各種服務(wù)。
- Realm充當了Shiro與應(yīng)用安全數(shù)據(jù)間的“橋梁”或者“連接器”。也就是說,當對用戶執(zhí)行認證(登錄)和授權(quán)(訪問控制)驗證時,Shiro會從應(yīng)用配置的Realm中查找用戶及其權(quán)限信息。
- Realm實質(zhì)上是一個安全相關(guān)的DAO:它封裝了數(shù)據(jù)源的連接細節(jié),并在需要時將相關(guān)數(shù)據(jù)提供給Shiro。當配置Shiro時,你必須至少指定一個Realm,用于認證和(或)授權(quán)。配置多個Realm是可以的,但是至少需要一個。
Shiro快速入門
導(dǎo)入依賴
<dependency>
<groupId>org.apache.shiro</groupId>
<artifactId>shiro-core</artifactId>
<version>1.7.1</version>
</dependency>
<!-- configure logging -->
<!-- https://mvnrepository.com/artifact/org.slf4j/jcl-over-slf4j -->
<dependency>
<groupId>org.slf4j</groupId>
<artifactId>jcl-over-slf4j</artifactId>
<version>2.0.0-alpha1</version>
</dependency>
<dependency>
<groupId>org.slf4j</groupId>
<artifactId>slf4j-log4j12</artifactId>
<version>2.0.0-alpha1</version>
</dependency>
<dependency>
<groupId>log4j</groupId>
<artifactId>log4j</artifactId>
<version>1.2.17</version>
</dependency>
配置log4j.properties
log4j.rootLogger=INFO, stdout
log4j.appender.stdout=org.apache.log4j.ConsoleAppender
log4j.appender.stdout.layout=org.apache.log4j.PatternLayout
log4j.appender.stdout.layout.ConversionPattern=%d %p [%c] - %m %n
# General Apache libraries
log4j.logger.org.apache=WARN
# Spring
log4j.logger.org.springframework=WARN
# Default Shiro logging
log4j.logger.org.apache.shiro=INFO
# Disable verbose logging
log4j.logger.org.apache.shiro.util.ThreadContext=WARN
log4j.logger.org.apache.shiro.cache.ehcache.EhCache=WARN
配置Shiro.ini(在IDEA中需要導(dǎo)入ini插件)
[users]
# user 'root' with password 'secret' and the 'admin' role
root = secret, admin
# user 'guest' with the password 'guest' and the 'guest' role
guest = guest, guest
# user 'presidentskroob' with password '12345' ("That's the same combination on
# my luggage!!!" ;)), and role 'president'
presidentskroob = 12345, president
# user 'darkhelmet' with password 'ludicrousspeed' and roles 'darklord' and 'schwartz'
darkhelmet = ludicrousspeed, darklord, schwartz
# user 'lonestarr' with password 'vespa' and roles 'goodguy' and 'schwartz'
lonestarr = vespa, goodguy, schwartz
# -----------------------------------------------------------------------------
# Roles with assigned permissions
#
# Each line conforms to the format defined in the
# org.apache.shiro.realm.text.TextConfigurationRealm#setRoleDefinitions JavaDoc
# -----------------------------------------------------------------------------
[roles]
# 'admin' role has all permissions, indicated by the wildcard '*'
admin = *
# The 'schwartz' role can do anything (*) with any lightsaber:
schwartz = lightsaber:*
# The 'goodguy' role is allowed to 'drive' (action) the winnebago (type) with
# license plate 'eagle5' (instance specific id)
goodguy = winnebago:drive:eagle5
快速入門實現(xiàn)類 quickStart.java
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.*;
import org.apache.shiro.config.IniSecurityManagerFactory;
import org.apache.shiro.mgt.DefaultSecurityManager;
import org.apache.shiro.realm.text.IniRealm;
import org.apache.shiro.session.Session;
import org.apache.shiro.subject.Subject;
import org.apache.shiro.util.Factory;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
public class quickStart {
private static final transient Logger log = LoggerFactory.getLogger(quickStart.class);
/*
Shiro三大對象:
Subject: 用戶
SecurityManager:管理所有用戶
Realm: 連接數(shù)據(jù)
*/
public static void main(String[] args) {
// 創(chuàng)建帶有配置的Shiro SecurityManager的最簡單方法
// realms, users, roles and permissions 是使用簡單的INI配置。
// 我們將使用可以提取.ini文件的工廠來完成此操作,
// 返回一個SecurityManager實例:
// 在類路徑的根目錄下使用shiro.ini文件
// (file:和url:前綴分別從文件和url加載):
//Factory<SecurityManager> factory = new IniSecurityManagerFactory("classpath:shiro.ini");
//SecurityManager securityManager = factory.getInstance();
DefaultSecurityManager securityManager = new DefaultSecurityManager();
IniRealm iniRealm = new IniRealm("classpath:shiro.ini");
securityManager.setRealm(iniRealm);
// 對于這個簡單的示例快速入門,請使SecurityManager
// 可作為JVM單例訪問。大多數(shù)應(yīng)用程序都不會這樣做
// 而是依靠其容器配置或web.xml進行
// webapps。這超出了此簡單快速入門的范圍,因此
// 我們只做最低限度的工作,這樣您就可以繼續(xù)感受事物.
SecurityUtils.setSecurityManager(securityManager);
// 現(xiàn)在已經(jīng)建立了一個簡單的Shiro環(huán)境,讓我們看看您可以做什么:
// 獲取當前用戶對象 Subject
Subject currentUser = SecurityUtils.getSubject();
// 使用Session做一些事情(不需要Web或EJB容器?。。? Session session = currentUser.getSession();//通過當前用戶拿到Session
session.setAttribute("someKey", "aValue");
String value = (String) session.getAttribute("someKey");
if (value.equals("aValue")) {
log.info("Retrieved the correct value! [" + value + "]");
}
// 判斷當前用戶是否被認證
if (!currentUser.isAuthenticated()) {
//token : 令牌,沒有獲取,隨機
UsernamePasswordToken token = new UsernamePasswordToken("lonestarr", "vespa");
token.setRememberMe(true); // 設(shè)置記住我
try {
currentUser.login(token);//執(zhí)行登陸操作
} catch (UnknownAccountException uae) {//打印出 用戶名
log.info("There is no user with username of " + token.getPrincipal());
} catch (IncorrectCredentialsException ice) {//打印出 密碼
log.info("Password for account " + token.getPrincipal() + " was incorrect!");
} catch (LockedAccountException lae) {
log.info("The account for username " + token.getPrincipal() + " is locked. " +
"Please contact your administrator to unlock it.");
}
// ... 在此處捕獲更多異常(也許是針對您的應(yīng)用程序的自定義異常?
catch (AuthenticationException ae) {
//unexpected condition? error?
}
}
//say who they are:
//print their identifying principal (in this case, a username):
log.info("User [" + currentUser.getPrincipal() + "] logged in successfully.");
//test a role:
if (currentUser.hasRole("schwartz")) {
log.info("May the Schwartz be with you!");
} else {
log.info("Hello, mere mortal.");
}
//test a typed permission (not instance-level)
if (currentUser.isPermitted("lightsaber:wield")) {
log.info("You may use a lightsaber ring. Use it wisely.");
} else {
log.info("Sorry, lightsaber rings are for schwartz masters only.");
}
//a (very powerful) Instance Level permission:
if (currentUser.isPermitted("winnebago:drive:eagle5")) {
log.info("You are permitted to 'drive' the winnebago with license plate (id) 'eagle5'. " +
"Here are the keys - have fun!");
} else {
log.info("Sorry, you aren't allowed to drive the 'eagle5' winnebago!");
}
//all done - log out!
currentUser.logout();//注銷
System.exit(0);//退出
}
}
啟動測試
SpringBoot-Shiro整合(最后會附上完整代碼)
前期工作
導(dǎo)入shiro-spring整合包依賴
<!-- shiro-spring整合包 -->
<dependency>
<groupId>org.apache.shiro</groupId>
<artifactId>shiro-spring</artifactId>
<version>1.7.1</version>
</dependency>
跳轉(zhuǎn)的頁面
index.html
<html lang="en" xmlns:th="http://www.w3.org/1999/xhtml">
<head>
<meta charset="UTF-8">
<title>首頁</title>
</head>
<body>
<h1>首頁</h1>
<p th:text="${msg}"></p>
<a th:href="@{/user/add}" rel="external nofollow" rel="external nofollow" rel="external nofollow" >add</a>| <a th:href="@{/user/update}" rel="external nofollow" rel="external nofollow" rel="external nofollow" >update</a>
</body>
</html>
add.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>add</title>
</head>
<body>
<p>add</p>
</body>
</html>
update.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>update</title>
</head>
<body>
<p>update</p>
</body>
</html>
編寫shiro的配置類ShiroConfig.java
package com.example.config;
import org.apache.shiro.spring.web.ShiroFilterFactoryBean;
import org.apache.shiro.web.mgt.DefaultWebSecurityManager;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import java.util.LinkedHashMap;
import java.util.Map;
@Configuration
public class ShiroConfig {
//3. ShiroFilterFactoryBean
@Bean
public ShiroFilterFactoryBean getshiroFilterFactoryBean(@Qualifier("SecurityManager") DefaultWebSecurityManager defaultWebSecurityManager){
ShiroFilterFactoryBean factoryBean = new ShiroFilterFactoryBean();
//設(shè)置安全管理器
factoryBean.setSecurityManager(defaultWebSecurityManager);
return factoryBean;
}
//2.創(chuàng)建DefaultWebSecurityManager
@Bean(name = "SecurityManager")
public DefaultWebSecurityManager getDefaultWebSecurityManager(@Qualifier("userRealm") UserRealm userRealm){
DefaultWebSecurityManager SecurityManager=new DefaultWebSecurityManager();
//3.關(guān)聯(lián)Realm
SecurityManager.setRealm(userRealm);
return SecurityManager;
}
//1.創(chuàng)建Realm對象
@Bean(name = "userRealm")
public UserRealm userRealm(){
return new UserRealm();
}
}
編寫UserRealm.java
package com.example.config;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.AuthenticationInfo;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
public class UserRealm extends AuthorizingRealm {
@Override
protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {
System.out.println("授權(quán)");
return null;
}
@Override
protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authenticationToken) throws AuthenticationException {
System.out.println("認證");
return null;
}
}
編寫controller測試環(huán)境是否搭建好
package com.example.controller;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
@Controller
public class MyController {
@RequestMapping({"/","/index"})
public String index(Model model){
model.addAttribute("msg","hello,shiro");
return "index";
}
@RequestMapping("/user/add")
public String add(){
return "user/add";
}
@RequestMapping("/user/update")
public String update(){
return "user/update";
}
}
實現(xiàn)登錄攔截
在ShiroConfig.java文件中添加攔截
Map<String,String> filterMap = new LinkedHashMap<>();
//對/user/*下的文件只有擁有authc權(quán)限的才能訪問
filterMap.put("/user/*","authc");
//將Map存放到ShiroFilterFactoryBean中
factoryBean.setFilterChainDefinitionMap(filterMap);
這樣,代碼跑起來,你點擊add或者update就會出現(xiàn)404錯誤,這時候,我們再繼續(xù)添加,讓它跳轉(zhuǎn)到我們自定義的登錄頁
添加登錄攔截到登錄頁
//需進行權(quán)限認證時跳轉(zhuǎn)到toLogin
factoryBean.setLoginUrl("/toLogin");
//權(quán)限認證失敗時跳轉(zhuǎn)到unauthorized
factoryBean.setUnauthorizedUrl("/unauthorized");
login.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>登錄</title>
</head>
<body>
<form action="">
用戶名:<input type="text" name="username"><br>
密碼:<input type="text" name="password"><br>
<input type="submit">
</form>
</body>
</html>
視圖跳轉(zhuǎn)添加一個login頁面跳轉(zhuǎn)
@RequestMapping("/toLogin")
public String login(){
return "login";
}
上面,我們已經(jīng)成功攔截了,現(xiàn)在我們來實現(xiàn)用戶認證
首先,我們需要一個登錄頁面
login.html
<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.w3.org/1999/xhtml">
<head>
<meta charset="UTF-8">
<title>登錄</title>
</head>
<body>
<p th:text="${msg}" style="color: red"></p>
<form th:action="@{/login}">
用戶名:<input type="text" name="username"><br>
密碼:<input type="text" name="password"><br>
<input type="submit">
</form>
</body>
</html>
其次,去controller編寫跳轉(zhuǎn)到登錄頁面
@RequestMapping("/login")
public String login(String username,String password,Model model){
//獲得當前的用戶
Subject subject = SecurityUtils.getSubject();
//封裝用戶數(shù)據(jù)
UsernamePasswordToken taken = new UsernamePasswordToken(username,password);
try{//執(zhí)行登陸操作,沒有發(fā)生異常就說明登陸成功
subject.login(taken);
return "index";
}catch (UnknownAccountException e){
model.addAttribute("msg","用戶名錯誤");
return "login";
}catch (IncorrectCredentialsException e){
model.addAttribute("msg","密碼錯誤");
return "login";
}
}
最后去UserRealm.java配置認證
//認證
@Override
protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authenticationToken) throws AuthenticationException {
System.out.println("認證");
String name = "root";
String password = "123456";
UsernamePasswordToken userToken = (UsernamePasswordToken) authenticationToken;
if (!userToken.getUsername().equals(name)){
return null;//拋出異常 用戶名錯誤那個異常
}
//密碼認證,shiro自己做
return new SimpleAuthenticationInfo("",password,"");
}
運行測試,成功?。?!
附上最后的完整代碼
pom.xml引入的依賴
pom.xml
<?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 https://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.4.4</version>
<relativePath/> <!-- lookup parent from repository -->
</parent>
<groupId>com.example</groupId>
<artifactId>springboot-08-shiro</artifactId>
<version>0.0.1-SNAPSHOT</version>
<name>springboot-08-shiro</name>
<description>Demo project for Spring Boot</description>
<properties>
<java.version>1.8</java.version>
</properties>
<dependencies>
<!-- shiro-spring整合包 -->
<dependency>
<groupId>org.apache.shiro</groupId>
<artifactId>shiro-spring</artifactId>
<version>1.7.1</version>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-thymeleaf</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
</plugins>
</build>
</project>
靜態(tài)資源
index.html
<html lang="en" xmlns:th="http://www.w3.org/1999/xhtml">
<head>
<meta charset="UTF-8">
<title>首頁</title>
</head>
<body>
<h1>首頁</h1>
<p th:text="${msg}"></p>
<a th:href="@{/user/add}" rel="external nofollow" rel="external nofollow" rel="external nofollow" >add</a>| <a th:href="@{/user/update}" rel="external nofollow" rel="external nofollow" rel="external nofollow" >update</a>
</body>
</html>
login.html
<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.w3.org/1999/xhtml">
<head>
<meta charset="UTF-8">
<title>登錄</title>
</head>
<body>
<p th:text="${msg}" style="color: red"></p>
<form th:action="@{/login}">
用戶名:<input type="text" name="username"><br>
密碼:<input type="text" name="password"><br>
<input type="submit">
</form>
</body>
</html>
add.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>add</title>
</head>
<body>
<p>add</p>
</body>
</html>
update.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>update</title>
</head>
<body>
<p>update</p>
</body>
</html>
controller層
MyController.java
package com.example.controller;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.IncorrectCredentialsException;
import org.apache.shiro.authc.UnknownAccountException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.subject.Subject;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
@Controller
public class MyController {
@RequestMapping({"/","/index"})
public String index(Model model){
model.addAttribute("msg","hello,shiro");
return "index";
}
@RequestMapping("/user/add")
public String add(){
return "user/add";
}
@RequestMapping("/user/update")
public String update(){
return "user/update";
}
@RequestMapping("/toLogin")
public String toLogin(){
return "login";
}
@RequestMapping("/login")
public String login(String username,String password,Model model){
//獲得當前的用戶
Subject subject = SecurityUtils.getSubject();
//封裝用戶數(shù)據(jù)
UsernamePasswordToken taken = new UsernamePasswordToken(username,password);
try{//執(zhí)行登陸操作,沒有發(fā)生異常就說明登陸成功
subject.login(taken);
return "index";
}catch (UnknownAccountException e){
model.addAttribute("msg","用戶名錯誤");
return "login";
}catch (IncorrectCredentialsException e){
model.addAttribute("msg","密碼錯誤");
return "login";
}
}
}
config文件
ShiroConfig.java
package com.example.config;
import org.apache.shiro.spring.web.ShiroFilterFactoryBean;
import org.apache.shiro.web.mgt.DefaultWebSecurityManager;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import java.util.LinkedHashMap;
import java.util.Map;
@Configuration
public class ShiroConfig {
//4. ShiroFilterFactoryBean
@Bean
public ShiroFilterFactoryBean getshiroFilterFactoryBean(@Qualifier("SecurityManager") DefaultWebSecurityManager defaultWebSecurityManager){
ShiroFilterFactoryBean factoryBean = new ShiroFilterFactoryBean();
//5. 設(shè)置安全管理器
factoryBean.setSecurityManager(defaultWebSecurityManager);
/* shiro內(nèi)置過濾器
anon 無需授權(quán)、登錄就可以訪問,所有人可訪。
authc 需要登錄授權(quán)才能訪問。
authcBasic Basic HTTP身份驗證攔截器
logout 退出攔截器。退出成功后,會 redirect到設(shè)置的/URI
noSessionCreation 不創(chuàng)建會話連接器
perms 授權(quán)攔截器,擁有對某個資源的權(quán)限才可訪問
port 端口攔截器
rest rest風(fēng)格攔截器
roles 角色攔截器,擁有某個角色的權(quán)限才可訪問
ssl ssl攔截器。通過https協(xié)議才能通過
user 用戶攔截器,需要有remember me功能方可使用
*/
Map<String,String> filterMap = new LinkedHashMap<>();
//對/user/*下的文件只有擁有authc權(quán)限的才能訪問
filterMap.put("/user/*","authc");
//將Map存放到ShiroFilterFactoryBean中
factoryBean.setFilterChainDefinitionMap(filterMap);
//需進行權(quán)限認證時跳轉(zhuǎn)到toLogin
factoryBean.setLoginUrl("/toLogin");
//權(quán)限認證失敗時跳轉(zhuǎn)到unauthorized
factoryBean.setUnauthorizedUrl("/unauthorized");
return factoryBean;
}
//2.創(chuàng)建DefaultWebSecurityManager
@Bean(name = "SecurityManager")
public DefaultWebSecurityManager getDefaultWebSecurityManager(@Qualifier("userRealm") UserRealm userRealm){
DefaultWebSecurityManager SecurityManager=new DefaultWebSecurityManager();
//3.關(guān)聯(lián)Realm
SecurityManager.setRealm(userRealm);
return SecurityManager;
}
//1.創(chuàng)建Realm對象
@Bean(name = "userRealm")
public UserRealm userRealm(){
return new UserRealm();
}
}
UserRealm.java
package com.example.config;
import org.apache.shiro.authc.*;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
public class UserRealm extends AuthorizingRealm {
//授權(quán)
@Override
protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {
System.out.println("授權(quán)");
return null;
}
//認證
@Override
protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authenticationToken) throws AuthenticationException {
System.out.println("認證");
String name = "root";
String password = "123456";
UsernamePasswordToken userToken = (UsernamePasswordToken) authenticationToken;
if (!userToken.getUsername().equals(name)){
return null;//拋出異常 用戶名錯誤那個異常
}
//密碼認證,shiro自己做
return new SimpleAuthenticationInfo("",password,"");
}
}
但是,我們在用戶認證這里,真實情況是從數(shù)據(jù)庫中取的,所以,我們接下來去實現(xiàn)一下從數(shù)據(jù)庫中取出數(shù)據(jù)來實現(xiàn)用戶認證
Shiro整合mybatis
前期工作
在前面導(dǎo)入的依賴中,繼續(xù)添加以下依賴
<!-- mysql -->
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
</dependency>
<!-- log4j -->
<dependency>
<groupId>log4j</groupId>
<artifactId>log4j</artifactId>
<version>1.2.17</version>
</dependency>
<!-- 數(shù)據(jù)源Druid -->
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>druid</artifactId>
<version>1.2.5</version>
</dependency>
<!-- 引入mybatis -->
<dependency>
<groupId>org.mybatis.spring.boot</groupId>
<artifactId>mybatis-spring-boot-starter</artifactId>
<version>2.1.4</version>
</dependency>
<!-- lombok -->
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
</dependency>
導(dǎo)入了mybatis和Druid,就去application.properties配置一下和Druid
Druid
spring:
datasource:
username: root
password: 123456
url: jdbc:mysql://localhost:3306/mybatis?serverTimezone=UTC&useUnicode=true&characterEncoding=utf-8
driver-class-name: com.mysql.cj.jdbc.Driver
type: com.alibaba.druid.pool.DruidDataSource # 自定義數(shù)據(jù)源
#Spring Boot 默認是不注入這些屬性值的,需要自己綁定
#druid 數(shù)據(jù)源專有配置
initialSize: 5
minIdle: 5
maxActive: 20
maxWait: 60000
timeBetweenEvictionRunsMillis: 60000
minEvictableIdleTimeMillis: 300000
validationQuery: SELECT 1 FROM DUAL
testWhileIdle: true
testOnBorrow: false
testOnReturn: false
poolPreparedStatements: true
#配置監(jiān)控統(tǒng)計攔截的filters,stat:監(jiān)控統(tǒng)計、log4j:日志記錄、wall:防御sql注入
#如果允許時報錯 java.lang.ClassNotFoundException: org.apache.log4j.Priority
#則導(dǎo)入 log4j 依賴即可,Maven 地址:https://mvnrepository.com/artifact/log4j/log4j
filters: stat,wall,log4j
maxPoolPreparedStatementPerConnectionSize: 20
useGlobalDataSourceStat: true
connectionProperties: druid.stat.mergeSql=true;druid.stat.slowSqlMillis=500
mybatis
mybatis: type-aliases-package: com.example.pojo mapper-locations: classpath:mapper/*.xml
連接數(shù)據(jù)庫
編寫實體類
package com.example.pojo;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
@Data
@AllArgsConstructor
@NoArgsConstructor
public class User {
private Integer id;
private String name;
private String pwd;
}
編寫mapper
package com.example.mapper;
import com.example.pojo.User;
import org.apache.ibatis.annotations.Mapper;
import org.springframework.stereotype.Repository;
@Repository
@Mapper
public interface UserMapper {
public User getUserByName(String name);
}
編寫mapper.xml
<?xml version="1.0" encoding="UTF8" ?>
<!DOCTYPE mapper
PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
"http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="com.example.mapper.UserMapper">
<select id="getUserByName" parameterType="String" resultType="User">
select * from mybatis.user where name=#{name}
</select>
</mapper>
編寫service
package com.example.service;
import com.example.pojo.User;
public interface UserService {
public User getUserByName(String name);
}
package com.example.service;
import com.example.mapper.UserMapper;
import com.example.pojo.User;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
@Service
public class UserServiceImpl implements UserService{
@Autowired
UserMapper userMapper;
@Override
public User getUserByName(String name) {
return userMapper.getUserByName(name);
}
}
使用數(shù)據(jù)庫中的數(shù)據(jù)
修改UserRealm.java即可
package com.example.config;
import com.example.pojo.User;
import com.example.service.UserService;
import org.apache.shiro.authc.*;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.springframework.beans.factory.annotation.Autowired;
public class UserRealm extends AuthorizingRealm {
@Autowired
UserService userService;
//授權(quán)
@Override
protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {
System.out.println("授權(quán)");
return null;
}
//認證
@Override
protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authenticationToken) throws AuthenticationException {
System.out.println("認證");
UsernamePasswordToken userToken = (UsernamePasswordToken) authenticationToken;
//連接真實的數(shù)據(jù)庫
User user = userService.getUserByName(userToken.getUsername());
if (user==null){
return null;//拋出異常 用戶名錯誤那個異常
}
//密碼認證,shiro自己做
return new SimpleAuthenticationInfo("",user.getPwd(),"");
}
}
認證搞完了,我們再來看看授權(quán)
在ShiroConfig.java文件加入授權(quán),加入這行代碼: filterMap.put("/user/add","perms[user:add]");//只有擁有user:add權(quán)限的人才能訪問add,注意授權(quán)的位置在認證前面,不然授權(quán)會認證不了;
運行測試:add頁面無法訪問
授權(quán)同理:filterMap.put("/user/update","perms[user:update]");//只有擁有user:update權(quán)限的人才能訪問update
自定義一個未授權(quán)跳轉(zhuǎn)頁面
在ShiroConfig.java文件設(shè)置未授權(quán)時跳轉(zhuǎn)到unauthorized頁面,加入這行代碼:
factoryBean.setUnauthorizedUrl("/unauthorized"); 2. 去Mycontroller寫跳轉(zhuǎn)未授權(quán)頁面
@RequestMapping("/unauthorized")
@ResponseBody//懶得寫界面,返回一個字符串
public String unauthorized(){
return "沒有授權(quán),無法訪問";
}
運行效果:
從數(shù)據(jù)庫中接受用戶的權(quán)限,進行判斷
在數(shù)據(jù)庫中添加一個屬性perms,相應(yīng)的實體類也要修改
修改UserRealm.java
package com.example.config;
import com.example.pojo.User;
import com.example.service.UserService;
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.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;
public class UserRealm extends AuthorizingRealm {
@Autowired
UserService userService;
//授權(quán)
@Override
protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {
System.out.println("授權(quán)");
SimpleAuthorizationInfo info = new SimpleAuthorizationInfo();
//沒有使用數(shù)據(jù)庫,直接自己設(shè)置的用戶權(quán)限,給每個人都設(shè)置了,現(xiàn)實中要從數(shù)據(jù)庫中取
//info.addStringPermission("user:add");
//從數(shù)據(jù)庫中得到權(quán)限信息
//獲得當前登錄的對象
Subject subject = SecurityUtils.getSubject();
//拿到User對象,通過getPrincipal()獲得
User currentUser = (User) subject.getPrincipal();
//設(shè)置當前用戶的權(quán)限
info.addStringPermission(currentUser.getPerms());
return info;
}
//認證
@Override
protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authenticationToken) throws AuthenticationException {
System.out.println("認證");
UsernamePasswordToken userToken = (UsernamePasswordToken) authenticationToken;
//連接真實的數(shù)據(jù)庫
User user = userService.getUserByName(userToken.getUsername());
if (user==null){
return null;//拋出異常 用戶名錯誤那個異常
}
//密碼認證,shiro自己做
return new SimpleAuthenticationInfo(user,user.getPwd(),"");
}
}
有了授權(quán)后,就又出現(xiàn)了一個問題,我們是不是要讓用戶沒有權(quán)限的東西,就看不見呢?這時候,就出現(xiàn)了Shiro-thymeleaf整合
Shiro-thymeleaf整合
導(dǎo)入整合的依賴
<!-- https://mvnrepository.com/artifact/com.github.theborakompanioni/thymeleaf-extras-shiro -->
<dependency>
<groupId>com.github.theborakompanioni</groupId>
<artifactId>thymeleaf-extras-shiro</artifactId>
<version>2.0.0</version>
</dependency>
在ShiroConfig整合ShiroDialect
//整合ShiroDialect: 用來整合 shiro thymeleaf
@Bean
public ShiroDialect getShiroDialect(){
return new ShiroDialect();
}
修改index頁面
<html lang="en" xmlns:th="http://www.thymeleaf.org"
xmlns:shiro="http://www.thymeleaf.org/thymeleaf-extras-shiro">
<!-- 三個命名空間
xmlns:th="http://www.thymeleaf.org"
xmlns:sec="http://www.thymeleaf.org/extras/spring-security"
xmlns:shiro="http://www.thymeleaf.org/thymeleaf-extras-shiro"
-->
<head>
<meta charset="UTF-8">
<title>首頁</title>
</head>
<body>
<h1>首頁</h1>
<p th:text="${msg}"></p>
<!--判斷是否有用戶登錄,如果有就不顯示登錄按鈕-->
<div th:if="${session.loginUser==null}">
<a th:href="@{/toLogin}" rel="external nofollow" >登錄</a>
</div>
<div shiro:hasPermission="user:add">
<a th:href="@{/user/add}" rel="external nofollow" rel="external nofollow" rel="external nofollow" >add</a>
</div>
<div shiro:hasPermission="user:update">
<a th:href="@{/user/update}" rel="external nofollow" rel="external nofollow" rel="external nofollow" >update</a>
</div>
</body>
</html>
判斷是否有用戶登錄
//這個是整合shiro和thymeleaf用到的,讓登錄按鈕消失的判斷
Subject subject = SecurityUtils.getSubject();
Session session = subject.getSession();
session.setAttribute("loginUser", user);
測試
以上就是關(guān)于Java安全框架Shiro以及SpringBoot項目中整合Shiro框架的詳細內(nèi)容,想要了解更多關(guān)于Java安全框架Shiro的資料,請關(guān)注W3Cschool其它相關(guān)文章!也希望大家能夠多多支持我們!