Springboot中的Shiro基礎(chǔ)入門教程
Shiro簡(jiǎn)介
什么是Shiro
- Apache Shiro 是一個(gè)Java 的安全(權(quán)限)框架。
- Shiro 可以非常容易的開(kāi)發(fā)出足夠好的應(yīng)用,其不僅可以用在JavaSE環(huán)境,也可以用在JavaEE環(huán)境。
- Shiro可以完成,認(rèn)證,授權(quán),加密,會(huì)話管理,Web集成,緩存等。
- 下載地址:https://shiro.apache.org
Shiro有哪些功能

- Authentication:身份認(rèn)證、登錄,驗(yàn)證用戶是不是擁有相應(yīng)的身份;
- Authorization:授權(quán),即權(quán)限驗(yàn)證,驗(yàn)證某個(gè)已認(rèn)證的用戶是否擁有某個(gè)權(quán)限,即判斷用戶能否進(jìn)行什么操作,如:驗(yàn)證某個(gè)用戶是否擁有某個(gè)角色,或者細(xì)粒度的驗(yàn)證某個(gè)用戶對(duì)某個(gè)資源是否具有某個(gè)權(quán)限!
- Session Management:會(huì)話管理,即用戶登錄后就是第一次會(huì)話,在沒(méi)有退出之前,它的所有信息都在會(huì)話中;會(huì)話可以是普通的JavaSE環(huán)境,也可以是Web環(huán)境;
- Cryptography:加密,保護(hù)數(shù)據(jù)的安全性,如密碼加密存儲(chǔ)到數(shù)據(jù)庫(kù)中,而不是明文存儲(chǔ);
- Web Support:Web支持,可以非常容易的集成到Web環(huán)境;
- Caching:緩存,比如用戶登錄后,其用戶信息,擁有的角色、權(quán)限不必每次去查,這樣可以提高效率
- Concurrency:并發(fā),shiro支持多線程應(yīng)用的并發(fā)驗(yàn)證,即,如在一個(gè)線程中開(kāi)啟另一個(gè)線程,能把權(quán)限自動(dòng)的傳播過(guò)去
- Testing:提供測(cè)試支持;
- Run As:允許一個(gè)用戶假裝為另一個(gè)用戶(如果他們?cè)试S)的身份進(jìn)行訪問(wèn);
- Remember Me:記住我,這個(gè)是非常常見(jiàn)的功能,即一次登錄后,下次再來(lái)的話不用登錄了
Shiro架構(gòu)(外部)
從外部來(lái)看Shiro,即從應(yīng)用程序角度來(lái)觀察如何使用Shiro完成工作:

- Subject:應(yīng)用代碼直接交互的對(duì)象是Subject,也就是說(shuō)Shiro的對(duì)外API核心就是Subject,Subject代表了當(dāng)前的用戶,這個(gè)用戶不一定是一個(gè)具體的人,與當(dāng)前應(yīng)用交互的任何東西都是subiect,如網(wǎng)絡(luò)爬蟲(chóng),機(jī)器人等,與Subject的所有交互都會(huì)委托給SecurityManager;Subject其實(shí)是一個(gè)門面,SecurityManageer 才是實(shí)際的執(zhí)行者
- SecurityManager:安全管理器,即所有與安全有關(guān)的操作都會(huì)與SercurityManager交互,并且它管理著所有的Subject,可以看出它是Shiro的核心,它負(fù)責(zé)與Shiro的其他組件進(jìn)行交互,它相當(dāng)于SpringMVC的Dispatcherservlet的角色
- Realm:Shiro從Realm獲取安全數(shù)據(jù)(如用戶,角色,權(quán)限),就是說(shuō)SecurityManager 要驗(yàn)證用戶身份那么它需要從Realm 獲取相應(yīng)的用戶進(jìn)行比較,來(lái)確定用戶的身份是否合法;也需要從Realm得到用戶相應(yīng)的角色、權(quán)限,進(jìn)行驗(yàn)證用戶的操作是否能夠進(jìn)行,可以把Realm看成DataSource;
Shiro架構(gòu)(內(nèi)部)

- Subject:任何可以與應(yīng)用交互的“用戶”;
- Security Manager:相當(dāng)于SpringMVC中的Dispatcherservlet;是Shiro的心臟,所有具體的交互都通過(guò)Security Manager進(jìn)行控制,它管理者所有的Subject,且負(fù)責(zé)進(jìn)行認(rèn)證,授權(quán),會(huì)話,及緩存的管理。
- Authenticator:負(fù)責(zé)subject認(rèn)證,是一個(gè)擴(kuò)展點(diǎn),可以自定義實(shí)現(xiàn);可以使用認(rèn)證策略(AuthenticationStrategy),即什么情況下算用戶認(rèn)證通過(guò)了;
- Authorizer:授權(quán)器,即訪問(wèn)控制器,用來(lái)決定主體是否有權(quán)限進(jìn)行相應(yīng)的操作:即控制著用戶能訪問(wèn)應(yīng)用中的那些功能;
- Realm:可以有一個(gè)或者多個(gè)的realm,可以認(rèn)為是安全實(shí)體數(shù)據(jù)源,即用于獲取安全實(shí)體的,可以用JDBC實(shí)現(xiàn),也可以是內(nèi)存實(shí)現(xiàn)等等,由用戶提供;所以一般在應(yīng)用中都需要實(shí)現(xiàn)自己的realm
- SessionManager:管理Session生命周期的組件,而Shiro并不僅僅可以用在Web環(huán)境,也可以用在普通的JavaSE環(huán)境中
- CacheManager:緩存控制器,來(lái)管理如用戶,角色,權(quán)限等緩存的;因?yàn)檫@些數(shù)據(jù)基本上很少改變,放到緩存中后可以提高訪問(wèn)的性能;
- Cryptography:密碼模塊,Shiro 提高了一些常見(jiàn)的加密組件用于密碼加密,解密等
HelloWorld
快速實(shí)踐
查看官方文檔:https://shiro.apache.org/10-minute-tutorial.html
官方的quickstart:https://github.com/apache/shiro/blob/1.4.x/samples/quickstart
- 創(chuàng)建一個(gè)maven父工程,用于學(xué)習(xí)Shiro,刪掉不必要的東西
- 創(chuàng)建一個(gè)普通的Maven子工程:shiro-01-helloworld
- 根據(jù)官方文檔,我們來(lái)導(dǎo)入Shiro的依賴
<!-- https://mvnrepository.com/artifact/org.apache.shiro/shiro-core -->
<dependency>
<groupId>org.apache.shiro</groupId>
<artifactId>shiro-core</artifactId>
<version>1.4.1</version>
</dependency>
<dependency>
<groupId>org.slf4j</groupId>
<artifactId>jcl-over-slf4j</artifactId>
<version>1.7.21</version>
</dependency>
<dependency>
<groupId>org.slf4j</groupId>
<artifactId>slf4j-log4j12</artifactId>
<version>1.7.21</version>
</dependency>
<dependency>
<groupId>log4j</groupId>
<artifactId>log4j</artifactId>
<version>1.2.17</version>
</dependency>編寫log4j的配置文件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
[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復(fù)制官方Quickstart.java文件
/*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.*;
import org.apache.shiro.config.IniSecurityManagerFactory;
import org.apache.shiro.mgt.SecurityManager;
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;
/**
* Simple Quickstart application showing how to use Shiro's API.
*
* @since 0.9 RC2
*/
public class Quickstart {
private static final transient Logger log = LoggerFactory.getLogger(Quickstart.class);
public static void main(String[] args) {
// The easiest way to create a Shiro SecurityManager with configured
// realms, users, roles and permissions is to use the simple INI config.
// We'll do that by using a factory that can ingest a .ini file and
// return a SecurityManager instance:
// Use the shiro.ini file at the root of the classpath
// (file: and url: prefixes load from files and urls respectively):
Factory<SecurityManager> factory = new IniSecurityManagerFactory("classpath:shiro.ini");
SecurityManager securityManager = factory.getInstance();
// for this simple example quickstart, make the SecurityManager
// accessible as a JVM singleton. Most applications wouldn't do this
// and instead rely on their container configuration or web.xml for
// webapps. That is outside the scope of this simple quickstart, so
// we'll just do the bare minimum so you can continue to get a feel
// for things.
SecurityUtils.setSecurityManager(securityManager);
// Now that a simple Shiro environment is set up, let's see what you can do:
// get the currently executing user:
Subject currentUser = SecurityUtils.getSubject();
// Do some stuff with a Session (no need for a web or EJB container!!!)
Session session = currentUser.getSession();
session.setAttribute("someKey", "aValue");
String value = (String) session.getAttribute("someKey");
if (value.equals("aValue")) {
log.info("Retrieved the correct value! [" + value + "]");
}
// let's login the current user so we can check against roles and permissions:
if (!currentUser.isAuthenticated()) {
UsernamePasswordToken token = new UsernamePasswordToken("lonestarr", "vespa");
token.setRememberMe(true);
try {
currentUser.login(token);
} 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.");
}
// ... catch more exceptions here (maybe custom ones specific to your application?
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);
}
}啟動(dòng)測(cè)試,有日志輸出即可。

帶有中文注釋版本的Quickstart
public class Quickstart {
private static final transient Logger log = LoggerFactory.getLogger(Quickstart.class);
public static void main(String[] args) {
Factory<SecurityManager> factory = new IniSecurityManagerFactory("classpath:shiro.ini");
SecurityManager securityManager = factory.getInstance();
SecurityUtils.setSecurityManager(securityManager);
// 獲取當(dāng)前的用戶對(duì)象:Subject
Subject currentUser = SecurityUtils.getSubject();
// 通過(guò)當(dāng)前用戶拿到Session
Session session = currentUser.getSession();
session.setAttribute("someKey", "aValue");
String value = (String) session.getAttribute("someKey");
if (value.equals("aValue")) {
log.info("Subject=>session [" + value + "]");
}
// 判斷當(dāng)前用戶是否被認(rèn)證
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.");
}
// ... catch more exceptions here (maybe custom ones specific to your application?
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.");
}
//細(xì)粒度
//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();
//結(jié)束
System.exit(0);
}
}Springboot整合Shiro
項(xiàng)目搭建
導(dǎo)入正確的Maven依賴:
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-thymeleaf</artifactId>
</dependency>
<!--Shiro整合Spring的包-->
<dependency>
<groupId>org.apache.shiro</groupId>
<artifactId>shiro-spring</artifactId>
<version>1.4.1</version>
</dependency>編寫前端頁(yè)面:
/user/update.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
<h1>update</h1>
</body>
</html>/user/add.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
<h1>add</h1>
</body>
</html>index.html
<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
<h1>首頁(yè)</h1>
<p th:text="${msg}"></p>
<hr>
<a th:href="@{/user/add}">add</a> | <a th:href="@{/user/update}">update</a>
</body>
</html>編寫MyController.java
@Controller
public class MyController {
@RequestMapping({"/","/index"})
public String toIndex(Model model){
model.addAttribute("msg","Hello World");
return "index";
}
@RequestMapping("/user/add")
public String add(){
return "user/add";
}
@RequestMapping("/user/update")
public String update(){
return "user/update";
}
}配置Shiro
自定義Realm
package com.lingbo.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;
//自定義的 realm
public class UserRealm extends AuthorizingRealm {
//授權(quán)
@Override
protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {
System.out.println("執(zhí)行了=>授權(quán)doGetAuthorizationInfo");
return null;
}
//認(rèn)證
@Override
protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authenticationToken) throws AuthenticationException {
System.out.println("執(zhí)行了=>認(rèn)證doGetAuthenticationInfo");
return null;
}
}Realm 是 Shiro 的“安全數(shù)據(jù)源”——“誰(shuí)可以登錄、登錄后能干啥”這兩件事,Shiro 自己不保存,全權(quán)委托給 Realm 去查。
主要工作為:
- 認(rèn)證(doGetAuthenticationInfo)→ 把用戶傳來(lái)的賬號(hào)/密碼和數(shù)據(jù)庫(kù)(或任何數(shù)據(jù)源)比對(duì),比對(duì)成功就返回一個(gè)
AuthenticationInfo,Shiro 自動(dòng)做密碼校驗(yàn)。 - 授權(quán)(doGetAuthorizationInfo)→ 登錄成功后,Shiro 把用戶身份再傳給你,讓你把該用戶的角色、權(quán)限字符串查出來(lái)并包成
AuthorizationInfo,后面@RequiresRoles、@RequiresPermissions都靠這里返回的數(shù)據(jù)。
配置ShiroConfig
package com.lingbo.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;
@Configuration
public class ShiroConfig {
//ShiroFilterFactoryBean
@Bean
public ShiroFilterFactoryBean getShiroFilterFactoryBean(@Qualifier("securityManager") DefaultWebSecurityManager defaultWebSecurityManager) {
ShiroFilterFactoryBean bean = new ShiroFilterFactoryBean();
//設(shè)置安全管理器
bean.setSecurityManager(defaultWebSecurityManager);
return bean;
}
//DefaultWebSecurityManager
@Bean(name = "securityManager")
public DefaultWebSecurityManager getDefaultWebSecurityManager(@Qualifier("userRealm") UserRealm userRealm) {
DefaultWebSecurityManager securityManager = new DefaultWebSecurityManager();
// 關(guān)聯(lián)UserRealm
securityManager.setRealm(userRealm);
return securityManager;
}
//創(chuàng)建 realm 對(duì)象,需要自定義類:1
@Bean
public UserRealm userRealm() {
return new UserRealm();
}
}ShiroConfig 就是 “告訴 Spring 如何把 Shiro 的各個(gè)核心組件裝配起來(lái)” 的一個(gè)普通 Java 配置類。
它只做 3 件事,卻缺一不可:
- 把 自定義 Realm(你的
UserRealm)注冊(cè)成 Spring Bean → 讓 Spring 能注入給 SecurityManager。 - 把 SecurityManager(
DefaultWebSecurityManager)注冊(cè)成 Spring Bean,并把自己剛創(chuàng)建的 Realm 設(shè)進(jìn)去 → 這是 Shiro 的總閘門。 - 把 ShiroFilterFactoryBean 注冊(cè)成 Spring Bean,并指向上面的 SecurityManager → 這樣 Spring Boot 啟動(dòng)時(shí)會(huì)自動(dòng)把它包裝成
Filter并注冊(cè)到 Servlet 容器,所有請(qǐng)求都會(huì)被 Shiro 攔截。
Shiro實(shí)現(xiàn)登錄攔截
//ShiroFilterFactoryBean
@Bean
public ShiroFilterFactoryBean getShiroFilterFactoryBean(@Qualifier("securityManager") DefaultWebSecurityManager defaultWebSecurityManager) {
ShiroFilterFactoryBean bean = new ShiroFilterFactoryBean();
//設(shè)置安全管理器
bean.setSecurityManager(defaultWebSecurityManager);
//添加Shiro的內(nèi)置過(guò)濾器
/*
anon: 無(wú)需認(rèn)證即可訪問(wèn)
authc: 必須認(rèn)證了才能訪問(wèn)
user: 必須擁有 記住我 功能才能用
perms: 擁有對(duì)某個(gè)資源的權(quán)限才能訪問(wèn)
role: 擁有某個(gè)角色權(quán)限才能訪問(wèn)
*/
//攔截
Map<String, String> filterMap = new LinkedHashMap<>();
//filterMap.put("/user/add", "authc");
//filterMap.put("/user/update", "anon");
filterMap.put("/user/*", "authc");
bean.setFilterChainDefinitionMap(filterMap);
bean.setLoginUrl("/toLogin");
return bean;
}其中的LinkedHashMap 按插入順序匹配,先放寬松規(guī)則,再放嚴(yán)格規(guī)則。
典型錯(cuò)誤示范:
filterMap.put("/**", "authc"); // 1. 所有請(qǐng)求都要登錄
filterMap.put("/login", "anon"); // 2. 登錄頁(yè)放行 —— 永遠(yuǎn)不會(huì)執(zhí)行到!
正確寫法:
filterMap.put("/login", "anon"); //登錄頁(yè)放行
filterMap.put("/static/**", "anon");//靜態(tài)資源放行
filterMap.put("/**", "authc");//其他頁(yè)面都要求登錄
Shiro實(shí)現(xiàn)用戶認(rèn)證
在MyController中封裝前端傳來(lái)的用戶名和密碼為userToken
@RequestMapping("/login")
public String login(String username, String password,Model model){
//獲取當(dāng)前用戶
Subject subject = SecurityUtils.getSubject();
//封裝用戶的登錄數(shù)據(jù)
UsernamePasswordToken token = new UsernamePasswordToken(username, password);
try {
subject.login(token);//執(zhí)行登錄方法,如果沒(méi)有異常,就說(shuō)明OK了
return "index";
} catch (UnknownAccountException uae) {//用戶名不存在
model.addAttribute("msg","用戶名錯(cuò)誤");
return "login";
} catch (IncorrectCredentialsException ice) {//密碼錯(cuò)誤
model.addAttribute("msg","密碼錯(cuò)誤");
return "login";
}
}subject.login(token) 的整個(gè)實(shí)現(xiàn)路線就是:
subject.login(token)
→ SecurityManager.login(this, token)
→ Authenticator.authenticate(token)
→ 遍歷所有 Realm,調(diào)用 realm.getAuthenticationInfo(token)
→ 最終進(jìn)到自己寫的 UserRealm.doGetAuthenticationInfo(...)
在UserRealm中編寫認(rèn)證代碼
//認(rèn)證
@Override
protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authenticationToken) throws AuthenticationException {
System.out.println("執(zhí)行了=>認(rèn)證doGetAuthenticationInfo");
//用戶名,密碼 數(shù)據(jù)中取
String name = "root";
String password = "123456";
UsernamePasswordToken userToken = (UsernamePasswordToken) authenticationToken;
if (!name.equals(userToken.getUsername())) {
return null; //拋出UnknownAccountException異常
}
//密碼認(rèn)證,Shiro做
return new SimpleAuthenticationInfo("", password, "");
}前端login.html
<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
<h1>登錄</h1>
<hr>
<p th:text="${msg}" style="color: red;"></p>
<form th:action="@{/login}" method="post">
<p>用戶名:<input type="text" name="username"></p>
<p>密碼:<input type="text" name="password"></p>
<p><input type="submit"></p>
</form>
</body>
</html>Shiro整合Mybatis
導(dǎo)入數(shù)據(jù)庫(kù)需要的相關(guān)依賴:
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<version>1.18.36</version>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
</dependency>
<dependency>
<groupId>log4j</groupId>
<artifactId>log4j</artifactId>
<version>1.2.17</version>
</dependency>
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>druid</artifactId>
<version>1.1.24</version>
</dependency>
<dependency>
<groupId>org.mybatis.spring.boot</groupId>
<artifactId>mybatis-spring-boot-starter</artifactId>
<version>2.1.3</version>
</dependency>配置數(shù)據(jù)源文件:
spring:
datasource:
driver-class-name: com.mysql.cj.jdbc.Driver
username: root
password: 123456
# 假如時(shí)區(qū)報(bào)錯(cuò),就增加一個(gè)時(shí)區(qū)的配置
url: jdbc:mysql://localhost:3306/mybatis?serverTimezone=UTC&useUnicode=true&characterEncoding=utf-8
# 自定義數(shù)據(jù)源
type: com.alibaba.druid.pool.DruidDataSource
#Spring Boot 默認(rèn)是不注入這些屬性值的,需要自己綁定
#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)計(jì)攔截的filters,stat:監(jiān)控統(tǒng)計(jì)、log4j:日志記錄、wall:防御sql注入
#如果允許時(shí)報(bào)錯(cuò) 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.lingbo.pojo mybatis.mapper-locations=classpath:mapper/*.xml
編寫User實(shí)體類:
@Data
@AllArgsConstructor
@NoArgsConstructor
public class User {
private Integer id;
private String name;
private String pwd;
}編寫Dao層Mapper接口和xml文件:
@Repository
@Mapper
public interface UserMapper {
public User queryUserByName(String name);
}<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE mapper
PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
"http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="com.lingbo.mapper.UserMapper">
<select id="queryUserByName" resultType="User" parameterType="String">
select *
from mybatis.user
where name = #{name};
</select>
</mapper>編寫Service接口和實(shí)現(xiàn)類
public interface UserService {
public User queryUserByName(String name);
}
@Service
public class UserServiceImpl implements UserService {
@Autowired
UserMapper userMapper;
@Override
public User queryUserByName(String name) {
User user = userMapper.queryUserByName(name);
return user;
}
}在UserRealm中連接數(shù)據(jù)庫(kù)
//自定義的 realm
public class UserRealm extends AuthorizingRealm {
@Autowired
UserService userService;
//授權(quán)
@Override
protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {
System.out.println("執(zhí)行了=>授權(quán)doGetAuthorizationInfo");
return null;
}
//認(rèn)證
@Override
protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authenticationToken) throws AuthenticationException {
System.out.println("執(zhí)行了=>認(rèn)證doGetAuthenticationInfo");
//用戶名,密碼 數(shù)據(jù)中取
//String name = "root";
//String password = "123456";
UsernamePasswordToken userToken = (UsernamePasswordToken) authenticationToken;
//連接真實(shí)數(shù)據(jù)庫(kù)
User user = userService.queryUserByName(userToken.getUsername());
if (user==null) {//沒(méi)有這個(gè)人
return null;
}
//密碼認(rèn)證,Shiro做
return new SimpleAuthenticationInfo("", user.getPwd(), "");
}
}Shiro實(shí)現(xiàn)請(qǐng)求授權(quán)
為數(shù)據(jù)庫(kù)中的user表和User實(shí)體類新增字段:perm
//ShiroFilterFactoryBean
@Bean
public ShiroFilterFactoryBean getShiroFilterFactoryBean(@Qualifier("securityManager") DefaultWebSecurityManager defaultWebSecurityManager) {
ShiroFilterFactoryBean bean = new ShiroFilterFactoryBean();
//設(shè)置安全管理器
bean.setSecurityManager(defaultWebSecurityManager);
//添加Shiro的內(nèi)置過(guò)濾器
/*
anon: 無(wú)需認(rèn)證即可訪問(wèn)
authc: 必須認(rèn)證了才能訪問(wèn)
user: 必須擁有 記住我 功能才能用
perms: 擁有對(duì)某個(gè)資源的權(quán)限才能訪問(wèn)
role: 擁有某個(gè)角色權(quán)限才能訪問(wèn)
*/
//攔截
Map<String, String> filterMap = new LinkedHashMap<>();
//正常情況下,未授權(quán)會(huì)跳轉(zhuǎn)到未授權(quán)頁(yè)面
filterMap.put("/user/add","perms[user:add]");
filterMap.put("/user/update","perms[user:update]");
filterMap.put("/user/*", "authc");
bean.setFilterChainDefinitionMap(filterMap);
bean.setUnauthorizedUrl("/noauth");
bean.setLoginUrl("/toLogin");
return bean;
}過(guò)濾器中增加對(duì)add和update權(quán)限的控制。
//授權(quán)
@Override
protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {
System.out.println("執(zhí)行了=>授權(quán)doGetAuthorizationInfo");
SimpleAuthorizationInfo authorizationInfo = new SimpleAuthorizationInfo();
//拿到當(dāng)前登錄的對(duì)象
Subject subject = SecurityUtils.getSubject();
User currentUser = (User) subject.getPrincipal();
//設(shè)置當(dāng)前用戶的權(quán)限
//若user在數(shù)據(jù)庫(kù)中字段perm的值為user:add則增加訪問(wèn)add頁(yè)面權(quán)限
//authorizationInfo.addStringPermission("user:add");
authorizationInfo.addStringPermission(currentUser.getPerm());
return authorizationInfo;
}
//認(rèn)證
@Override
protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authenticationToken) throws AuthenticationException {
System.out.println("執(zhí)行了=>認(rèn)證doGetAuthenticationInfo");
UsernamePasswordToken userToken = (UsernamePasswordToken) authenticationToken;
//連接真實(shí)數(shù)據(jù)庫(kù)
User user = userService.queryUserByName(userToken.getUsername());
if (user==null) {//沒(méi)有這個(gè)人
return null;
}
//密碼認(rèn)證,Shiro做
//將當(dāng)前用戶信息存入Subject對(duì)象中
return new SimpleAuthenticationInfo(user, user.getPwd(), "");
}到此這篇關(guān)于Springboot中的Shiro基礎(chǔ)入門教程的文章就介紹到這了,更多相關(guān)Springboot Shiro教程內(nèi)容請(qǐng)搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
關(guān)于Java鎖性能提高(鎖升級(jí))機(jī)制的總結(jié)
這篇文章主要介紹了關(guān)于Java鎖性能提高(鎖升級(jí))機(jī)制的總結(jié),具有很好的參考價(jià)值,希望對(duì)大家有所幫助。如有錯(cuò)誤或未考慮完全的地方,望不吝賜教2022-05-05
SpringBoot Nacos實(shí)現(xiàn)自動(dòng)刷新
這篇文章主要介紹了SpringBoot Nacos實(shí)現(xiàn)自動(dòng)刷新,Nacos(Dynamic Naming and Configuration Service)是阿里巴巴開(kāi)源的一個(gè)動(dòng)態(tài)服務(wù)發(fā)現(xiàn)、配置管理和服務(wù)管理平臺(tái)2023-01-01
Java設(shè)計(jì)模式之命令模式CommandPattern詳解
這篇文章主要介紹了Java設(shè)計(jì)模式之命令模式CommandPattern詳解,命令模式是把一個(gè)請(qǐng)求封裝為一個(gè)對(duì)象,從而使你可用不同的請(qǐng)求對(duì)客戶進(jìn)行參數(shù)化;對(duì)請(qǐng)求排隊(duì)或記錄請(qǐng)求日志,以及支持可撤銷的操作,需要的朋友可以參考下2023-10-10
解決MyBatis中為類配置別名,列名與屬性名不對(duì)應(yīng)的問(wèn)題
這篇文章主要介紹了解決MyBatis中為類配置別名,列名與屬性名不對(duì)應(yīng)的問(wèn)題,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。一起跟隨小編過(guò)來(lái)看看吧2020-11-11
詳解Java的Hibernate框架中的搜索工具的運(yùn)用
這篇文章主要介紹了詳解Java的Hibernate框架中的搜索工具的運(yùn)用,Hibernate是Java的SSH三大web開(kāi)發(fā)框架之一,需要的朋友可以參考下2015-11-11
基于Mybatis Plus實(shí)現(xiàn)多表分頁(yè)查詢的示例代碼
這篇文章主要介紹了基于Mybatis Plus實(shí)現(xiàn)多表分頁(yè)查詢的示例代碼,文中通過(guò)示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來(lái)一起學(xué)習(xí)學(xué)習(xí)吧2020-12-12

