更新時(shí)間:2021-09-30 10:17:20 來(lái)源:動(dòng)力節(jié)點(diǎn) 瀏覽1152次
項(xiàng)目結(jié)構(gòu)截圖:
項(xiàng)目在結(jié)構(gòu)上沒(méi)有任何特殊之處,基本就是SpringMVC的傳統(tǒng)結(jié)構(gòu)重點(diǎn)需要關(guān)注的是3個(gè)Entity類(lèi)、2個(gè)Controller類(lèi)和1個(gè)Config類(lèi)。
首先,提供pom的完整文檔結(jié)構(gòu):
<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>com.learnhow.springboot</groupId>
<artifactId>web</artifactId>
<version>0.0.1-SNAPSHOT</version>
<packaging>jar</packaging>
<name>web</name>
<url>http://maven.apache.org</url>
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.0.4.RELEASE</version>
<relativePath /> <!-- lookup parent from repository -->
</parent>
<properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<java.version>1.8</java.version>
</properties>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-jpa</artifactId>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
</dependency>
<dependency>
<groupId>org.apache.shiro</groupId>
<artifactId>shiro-spring</artifactId>
<version>1.4.0</version>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-devtools</artifactId>
<optional>true</optional>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
<configuration>
<fork>true</fork>
</configuration>
</plugin>
</plugins>
</build>
</project>
其次,創(chuàng)建數(shù)據(jù)庫(kù)和表結(jié)構(gòu)。由于我們采用jpa作為數(shù)據(jù)庫(kù)持久層框架,因此我們將建表的任務(wù)交給框架自動(dòng)完成,我們只需要在entity中寫(xiě)清楚對(duì)應(yīng)關(guān)系即可。
CREATE DATABASE enceladus; // enceladus是數(shù)據(jù)庫(kù)的名稱
application.yml
server:
port: 8088
spring:
application:
name: shiro
datasource:
url: jdbc:mysql://192.168.31.37:3306/enceladus
username: root
password: 12345678
driver-class-name: com.mysql.jdbc.Driver
jpa:
database: mysql
showSql: true
hibernate:
ddlAuto: update
properties:
hibernate:
dialect: org.hibernate.dialect.MySQL5Dialect
format_sql: true
最基礎(chǔ)的Shiro配置至少需要三張主表分別代表用戶(user)、角色(role)、權(quán)限(permission),用戶和角色,角色與權(quán)限之間都是ManyToMany的對(duì)應(yīng)關(guān)系,不熟悉實(shí)體對(duì)應(yīng)關(guān)系的小伙伴可以先去熟悉一下Hibernate。
User.java
import java.io.Serializable;
import java.util.List;
import javax.persistence.Entity;
import javax.persistence.FetchType;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import javax.persistence.JoinColumn;
import javax.persistence.JoinTable;
import javax.persistence.ManyToMany;
import javax.persistence.Table;
@Entity
@Table(name = "user_t")
public class User implements Serializable {
private static final long serialVersionUID = -3320971805590503443L;
@Id
@GeneratedValue
private long id;
private String username;
private String password;
private String salt;
@ManyToMany(fetch = FetchType.EAGER)
@JoinTable(name = "user_role_t", joinColumns = { @JoinColumn(name = "uid") }, inverseJoinColumns = {
@JoinColumn(name = "rid") })
private List<SysRole> roles;
public long getId() {
return id;
}
public void setId(long id) {
this.id = id;
}
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
public String getSalt() {
return salt;
}
public void setSalt(String salt) {
this.salt = salt;
}
public List<SysRole> getRoles() {
return roles;
}
public void setRoles(List<SysRole> roles) {
this.roles = roles;
}
public String getCredentialsSalt() {
return username + salt + salt;
}
@Override
public String toString() {
return "User [id=" + id + ", username=" + username + "]";
}
}
user
SysRole.java
import java.io.Serializable;
import java.util.List;
import javax.persistence.Entity;
import javax.persistence.FetchType;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import javax.persistence.JoinColumn;
import javax.persistence.JoinTable;
import javax.persistence.ManyToMany;
import javax.persistence.Table;
@Entity
@Table(name = "role_t")
public class SysRole implements Serializable {
private static final long serialVersionUID = -8687790154329829056L;
@Id
@GeneratedValue
private Integer id;
private String role;
@ManyToMany(fetch = FetchType.EAGER)
@JoinTable(name = "role_permission_t", joinColumns = { @JoinColumn(name = "rid") }, inverseJoinColumns = {
@JoinColumn(name = "pid") })
private List<SysPermission> permissions;
@ManyToMany
@JoinTable(name = "user_role_t", joinColumns = { @JoinColumn(name = "rid") }, inverseJoinColumns = {
@JoinColumn(name = "uid") })
private List<User> users;
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getRole() {
return role;
}
public void setRole(String role) {
this.role = role;
}
public List<SysPermission> getPermissions() {
return permissions;
}
public void setPermissions(List<SysPermission> permissions) {
this.permissions = permissions;
}
public List<User> getUsers() {
return users;
}
public void setUsers(List<User> users) {
this.users = users;
}
}
role
SysPermission.java
import java.io.Serializable;
import java.util.List;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import javax.persistence.JoinColumn;
import javax.persistence.JoinTable;
import javax.persistence.ManyToMany;
import javax.persistence.Table;
@Entity
@Table(name = "permission_t")
public class SysPermission implements Serializable {
private static final long serialVersionUID = 353629772108330570L;
@Id
@GeneratedValue
private Integer id;
private String name;
@ManyToMany
@JoinTable(name = "role_permission_t", joinColumns = { @JoinColumn(name = "pid") }, inverseJoinColumns = {
@JoinColumn(name = "rid") })
private List<SysRole> roles;
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public List<SysRole> getRoles() {
return roles;
}
public void setRoles(List<SysRole> roles) {
this.roles = roles;
}
}
perm
在注明對(duì)應(yīng)關(guān)系以后,jpa會(huì)幫助我們創(chuàng)建3張實(shí)體表和2張中間表:
最后我們還需要初始化一些基礎(chǔ)數(shù)據(jù):
INSERT INTO `permission_t` VALUES (1, 'Retrieve');
INSERT INTO `permission_t` VALUES (2, 'Create');
INSERT INTO `permission_t` VALUES (3, 'Update');
INSERT INTO `permission_t` VALUES (4, 'Delete');
INSERT INTO `role_t` VALUES (1, 'guest');
INSERT INTO `role_t` VALUES (2, 'user');
INSERT INTO `role_t` VALUES (3, 'admin');
INSERT INTO `role_permission_t` VALUES (1, 1);
INSERT INTO `role_permission_t` VALUES (1, 2);
INSERT INTO `role_permission_t` VALUES (2, 2);
INSERT INTO `role_permission_t` VALUES (3, 2);
INSERT INTO `role_permission_t` VALUES (1, 3);
INSERT INTO `role_permission_t` VALUES (2, 3);
INSERT INTO `role_permission_t` VALUES (3, 3);
INSERT INTO `role_permission_t` VALUES (4, 3);
至此,前期的準(zhǔn)備工作已經(jīng)完成。下面為了讓Shiro能夠在項(xiàng)目中生效我們需要通過(guò)代碼的方式提供配置信息。Shiro的安全管理提供了兩個(gè)層面的控制:(1)用戶認(rèn)證:需要用戶通過(guò)登陸證明你是你自己。(2)權(quán)限控制:在證明了你是你自己的基礎(chǔ)上系統(tǒng)為當(dāng)前用戶賦予權(quán)限。后者我們已經(jīng)在數(shù)據(jù)庫(kù)中完成了大部分配置。
用戶認(rèn)證的常規(guī)手段就是登陸認(rèn)證,在目前的情況下我們認(rèn)為只有用戶自己知道登陸密碼。不過(guò)Shiro為我們做的更多,它還提供了一套能夠很方便我們使用的密碼散列算法。因?yàn)槠胀ǖ纳⒘屑记煽梢院苋菀椎耐ㄟ^(guò)暴力手段破解,我們可以在散列的過(guò)程中加入一定的算法復(fù)雜度(增加散列次數(shù)與Salt)從而解決這樣的問(wèn)題。
import org.apache.shiro.crypto.RandomNumberGenerator;
import org.apache.shiro.crypto.SecureRandomNumberGenerator;
import org.apache.shiro.crypto.hash.SimpleHash;
import org.apache.shiro.util.ByteSource;
import com.learnhow.springboot.web.entity.User;
public class PasswordHelper {
private RandomNumberGenerator randomNumberGenerator = new SecureRandomNumberGenerator();
public static final String ALGORITHM_NAME = "md5"; // 基礎(chǔ)散列算法
public static final int HASH_ITERATIONS = 2; // 自定義散列次數(shù)
public void encryptPassword(User user) {
// 隨機(jī)字符串作為salt因子,實(shí)際參與運(yùn)算的salt我們還引入其它干擾因子
user.setSalt(randomNumberGenerator.nextBytes().toHex());
String newPassword = new SimpleHash(ALGORITHM_NAME, user.getPassword(),
ByteSource.Util.bytes(user.getCredentialsSalt()), HASH_ITERATIONS).toHex();
user.setPassword(newPassword);
}
}
這個(gè)類(lèi)幫助我們解決用戶注冊(cè)的密碼散列問(wèn)題,當(dāng)然我們還需要使用同樣的算法來(lái)保證在登陸的時(shí)候密碼能夠被散列成相同的字符串。如果兩次散列的結(jié)果不同系統(tǒng)就無(wú)法完成密碼比對(duì),因此在計(jì)算散列因子的時(shí)候我們不能引入變量,例如我們可以將username作為salt因子加入散列算法,但是不能選擇password或datetime,具體原因各位請(qǐng)手動(dòng)測(cè)試。
另外為了幫助Shiro能夠正確為當(dāng)前登陸用戶做認(rèn)證和賦權(quán),我們需要實(shí)現(xiàn)自定義的Realm。具體來(lái)說(shuō)就是實(shí)現(xiàn)doGetAuthenticationInfo和doGetAuthorizationInfo,這兩個(gè)方法前者負(fù)責(zé)登陸認(rèn)證后者負(fù)責(zé)提供一個(gè)權(quán)限信息。
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.AuthenticationInfo;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.SimpleAuthenticationInfo;
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.util.ByteSource;
import org.springframework.beans.factory.annotation.Autowired;
import com.learnhow.springboot.web.entity.SysPermission;
import com.learnhow.springboot.web.entity.SysRole;
import com.learnhow.springboot.web.entity.User;
import com.learnhow.springboot.web.service.UserService;
public class EnceladusShiroRealm extends AuthorizingRealm {
@Autowired
private UserService userService;
@Override
protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals) {
SimpleAuthorizationInfo authorizationInfo = new SimpleAuthorizationInfo();
String username = (String) principals.getPrimaryPrincipal();
User user = userService.findUserByName(username);
for (SysRole role : user.getRoles()) {
authorizationInfo.addRole(role.getRole());
for (SysPermission permission : role.getPermissions()) {
authorizationInfo.addStringPermission(permission.getName());
}
}
return authorizationInfo;
}
@Override
protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {
String username = (String) token.getPrincipal();
User user = userService.findUserByName(username);
if (user == null) {
return null;
}
SimpleAuthenticationInfo authenticationInfo = new SimpleAuthenticationInfo(user.getUsername(), user.getPassword(),
ByteSource.Util.bytes(user.getCredentialsSalt()), getName());
return authenticationInfo;
}
}
還記得前面我們說(shuō)過(guò),認(rèn)證的時(shí)候我們需要提供相同的散列算法嗎?可是在上面的代碼里,我們并未提供。那么Shiro是怎么做的呢?AuthorizingRealm是一個(gè)抽象類(lèi),我們會(huì)在另外的配置文件里向它提供基礎(chǔ)算法與散列次數(shù)這兩個(gè)變量。
import java.util.HashMap;
import java.util.Map;
import org.apache.shiro.authc.credential.HashedCredentialsMatcher;
import org.apache.shiro.mgt.SecurityManager;
import org.apache.shiro.spring.web.ShiroFilterFactoryBean;
import org.apache.shiro.web.mgt.DefaultWebSecurityManager;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
@Configuration
public class ShiroConfig {
@Bean
public ShiroFilterFactoryBean shirFilter(SecurityManager securityManager) {
ShiroFilterFactoryBean shiroFilterFactoryBean = new ShiroFilterFactoryBean();
shiroFilterFactoryBean.setSecurityManager(securityManager);
Map<String, String> filterChainDefinitionMap = new HashMap<String, String>();
shiroFilterFactoryBean.setLoginUrl("/login");
shiroFilterFactoryBean.setUnauthorizedUrl("/unauthc");
shiroFilterFactoryBean.setSuccessUrl("/home/index");
filterChainDefinitionMap.put("/*", "anon");
filterChainDefinitionMap.put("/authc/index", "authc");
filterChainDefinitionMap.put("/authc/admin", "roles[admin]");
filterChainDefinitionMap.put("/authc/renewable", "perms[Create,Update]");
filterChainDefinitionMap.put("/authc/removable", "perms[Delete]");
shiroFilterFactoryBean.setFilterChainDefinitionMap(filterChainDefinitionMap);
return shiroFilterFactoryBean;
}
@Bean
public HashedCredentialsMatcher hashedCredentialsMatcher() {
HashedCredentialsMatcher hashedCredentialsMatcher = new HashedCredentialsMatcher();
hashedCredentialsMatcher.setHashAlgorithmName(PasswordHelper.ALGORITHM_NAME); // 散列算法
hashedCredentialsMatcher.setHashIterations(PasswordHelper.HASH_ITERATIONS); // 散列次數(shù)
return hashedCredentialsMatcher;
}
@Bean
public EnceladusShiroRealm shiroRealm() {
EnceladusShiroRealm shiroRealm = new EnceladusShiroRealm();
shiroRealm.setCredentialsMatcher(hashedCredentialsMatcher()); // 原來(lái)在這里
return shiroRealm;
}
@Bean
public SecurityManager securityManager() {
DefaultWebSecurityManager securityManager = new DefaultWebSecurityManager();
securityManager.setRealm(shiroRealm());
return securityManager;
}
@Bean
public PasswordHelper passwordHelper() {
return new PasswordHelper();
}
}
接下來(lái),我們將目光集中到上文的shirFilter方法中。Shiro通過(guò)一系列filter來(lái)控制訪問(wèn)權(quán)限,并在它的內(nèi)部為我們預(yù)先定義了多個(gè)過(guò)濾器,我們可以直接通過(guò)字符串配置這些過(guò)濾器。
常用的過(guò)濾器如下:
authc:所有已登陸用戶可訪問(wèn)
roles:有指定角色的用戶可訪問(wèn),通過(guò)[ ]指定具體角色,這里的角色名稱與數(shù)據(jù)庫(kù)中配置一致
perms:有指定權(quán)限的用戶可訪問(wèn),通過(guò)[ ]指定具體權(quán)限,這里的權(quán)限名稱與數(shù)據(jù)庫(kù)中配置一致
anon:所有用戶可訪問(wèn),通常作為指定頁(yè)面的靜態(tài)資源時(shí)使用
為了測(cè)試方便我們不引入頁(yè)面配置直接通過(guò)rest方式訪問(wèn)
不受權(quán)限控制訪問(wèn)的地址
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.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import com.learnhow.springboot.web.PasswordHelper;
import com.learnhow.springboot.web.entity.User;
import com.learnhow.springboot.web.service.UserService;
@RestController
@RequestMapping
public class HomeController {
@Autowired
private UserService userService;
@Autowired
private PasswordHelper passwordHelper;
@GetMapping("login")
public Object login() {
return "Here is Login page";
}
@GetMapping("unauthc")
public Object unauthc() {
return "Here is Unauthc page";
}
@GetMapping("doLogin")
public Object doLogin(@RequestParam String username, @RequestParam String password) {
UsernamePasswordToken token = new UsernamePasswordToken(username, password);
Subject subject = SecurityUtils.getSubject();
try {
subject.login(token);
} catch (IncorrectCredentialsException ice) {
return "password error!";
} catch (UnknownAccountException uae) {
return "username error!";
}
User user = userService.findUserByName(username);
subject.getSession().setAttribute("user", user);
return "SUCCESS";
}
@GetMapping("register")
public Object register(@RequestParam String username, @RequestParam String password) {
User user = new User();
user.setUsername(username);
user.setPassword(password);
passwordHelper.encryptPassword(user);
userService.saveUser(user);
return "SUCCESS";
}
}
需要指定權(quán)限可以訪問(wèn)的地址
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.subject.Subject;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import com.learnhow.springboot.web.entity.User;
@RestController
@RequestMapping("authc")
public class AuthcController {
@GetMapping("index")
public Object index() {
Subject subject = SecurityUtils.getSubject();
User user = (User) subject.getSession().getAttribute("user");
return user.toString();
}
@GetMapping("admin")
public Object admin() {
return "Welcome Admin";
}
// delete
@GetMapping("removable")
public Object removable() {
return "removable";
}
// insert & update
@GetMapping("renewable")
public Object renewable() {
return "renewable";
}
}
以上就是“SpringBoot整合Shiro”的介紹,大家如果感興趣,可以關(guān)注一下動(dòng)力節(jié)點(diǎn)的SpringBoot教程,里面有更多知識(shí)可以免費(fèi)在線學(xué)習(xí),相信對(duì)大家的學(xué)習(xí)會(huì)有所幫助。
相關(guān)閱讀
0基礎(chǔ) 0學(xué)費(fèi) 15天面授
有基礎(chǔ) 直達(dá)就業(yè)
業(yè)余時(shí)間 高薪轉(zhuǎn)行
工作1~3年,加薪神器
工作3~5年,晉升架構(gòu)
提交申請(qǐng)后,顧問(wèn)老師會(huì)電話與您溝通安排學(xué)習(xí)