您好,登录后才能下订单哦!
在现代Web应用开发中,安全性是一个不可忽视的重要方面。无论是用户认证、授权、会话管理还是密码加密,都需要开发者投入大量的精力去设计和实现。为了简化这些安全相关的开发工作,Apache Shiro应运而生。Shiro是一个强大且易用的Java安全框架,提供了全面的安全解决方案。
Spring Boot作为现代Java应用开发的利器,以其简洁的配置和快速的开发能力,深受开发者喜爱。将Shiro与Spring Boot结合使用,可以极大地提高开发效率,同时保证应用的安全性。
本文将详细介绍如何使用Spring Boot快速整合Shiro安全框架,涵盖从项目创建到配置、从用户认证到授权、从数据库整合到缓存使用等多个方面。通过本文的学习,您将能够轻松地在Spring Boot项目中集成Shiro,构建安全可靠的Web应用。
Apache Shiro是一个强大且易用的Java安全框架,提供了认证、授权、加密和会话管理等功能。Shiro的设计目标是简化应用安全性的实现,使开发者能够专注于业务逻辑,而不必过多关注安全细节。
Spring Boot是Spring框架的一个子项目,旨在简化Spring应用的初始搭建和开发过程。Spring Boot通过自动配置和约定优于配置的原则,极大地减少了开发者的配置工作,使得开发者能够快速构建和部署Spring应用。
在开始整合Shiro和Spring Boot之前,我们需要准备好开发环境。以下是所需的环境和工具:
确保您的系统上已经安装了JDK,并且配置了环境变量。可以通过以下命令检查JDK版本:
java -version
Maven是Java项目的构建工具,用于管理项目依赖和构建过程。可以通过以下命令检查Maven版本:
mvn -v
如果未安装Maven,可以从Maven官网下载并安装。
推荐使用IntelliJ IDEA或Eclipse作为开发工具。IntelliJ IDEA提供了强大的Spring Boot支持,可以极大地提高开发效率。
在准备好开发环境后,我们可以开始创建一个Spring Boot项目。Spring Boot提供了多种创建项目的方式,包括使用Spring Initializr、Maven或Gradle等。本文将使用Spring Initializr创建项目。
导入项目后,您将看到以下项目结构:
src
├── main
│ ├── java
│ │ └── com
│ │ └── example
│ │ └── demo
│ │ ├── DemoApplication.java
│ │ └── controller
│ │ └── HomeController.java
│ └── resources
│ ├── application.properties
│ ├── static
│ └── templates
└── test
└── java
└── com
└── example
└── demo
└── DemoApplicationTests.java
在IDE中运行DemoApplication.java
,启动Spring Boot应用。访问http://localhost:8080
,您将看到默认的欢迎页面。
在创建好Spring Boot项目后,我们需要引入Shiro的依赖。Shiro提供了多个模块,可以根据需求选择引入。本文将引入shiro-spring
和shiro-web
模块。
在pom.xml
中添加以下依赖:
<dependencies>
<!-- Spring Boot Starter Web -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<!-- Spring Boot Starter Thymeleaf -->
<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.7.1</version>
</dependency>
<!-- Shiro Web -->
<dependency>
<groupId>org.apache.shiro</groupId>
<artifactId>shiro-web</artifactId>
<version>1.7.1</version>
</dependency>
<!-- Spring Boot Starter Security -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-security</artifactId>
</dependency>
</dependencies>
在添加依赖后,使用Maven更新项目,确保依赖正确下载和配置。
mvn clean install
在引入Shiro依赖后,我们需要配置Shiro,使其与Spring Boot应用集成。Shiro的配置主要包括SecurityManager
、Realm
、Filter
等。
在src/main/java/com/example/demo/config
目录下创建ShiroConfig.java
文件,内容如下:
package com.example.demo.config;
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;
import java.util.LinkedHashMap;
import java.util.Map;
@Configuration
public class ShiroConfig {
@Bean
public ShiroFilterFactoryBean shiroFilterFactoryBean(DefaultWebSecurityManager securityManager) {
ShiroFilterFactoryBean shiroFilterFactoryBean = new ShiroFilterFactoryBean();
shiroFilterFactoryBean.setSecurityManager(securityManager);
// 配置拦截器链
Map<String, String> filterChainDefinitionMap = new LinkedHashMap<>();
filterChainDefinitionMap.put("/static/**", "anon");
filterChainDefinitionMap.put("/login", "anon");
filterChainDefinitionMap.put("/**", "authc");
shiroFilterFactoryBean.setFilterChainDefinitionMap(filterChainDefinitionMap);
shiroFilterFactoryBean.setLoginUrl("/login");
shiroFilterFactoryBean.setSuccessUrl("/home");
shiroFilterFactoryBean.setUnauthorizedUrl("/403");
return shiroFilterFactoryBean;
}
@Bean
public DefaultWebSecurityManager securityManager(MyRealm myRealm) {
DefaultWebSecurityManager securityManager = new DefaultWebSecurityManager();
securityManager.setRealm(myRealm);
return securityManager;
}
@Bean
public MyRealm myRealm() {
return new MyRealm();
}
}
在src/main/java/com/example/demo/realm
目录下创建MyRealm.java
文件,内容如下:
package com.example.demo.realm;
import org.apache.shiro.authc.*;
import org.apache.shiro.realm.AuthenticatingRealm;
public class MyRealm extends AuthenticatingRealm {
@Override
protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {
String username = (String) token.getPrincipal();
String password = new String((char[]) token.getCredentials());
// 模拟从数据库获取用户信息
if (!"admin".equals(username)) {
throw new UnknownAccountException("用户不存在");
}
if (!"123456".equals(password)) {
throw new IncorrectCredentialsException("密码错误");
}
return new SimpleAuthenticationInfo(username, password, getName());
}
}
在配置好Shiro后,我们可以实现用户认证功能。用户认证是指验证用户的身份,确保用户是合法的。
在src/main/resources/templates
目录下创建login.html
文件,内容如下:
<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">
<head>
<meta charset="UTF-8">
<title>Login</title>
</head>
<body>
<h1>Login</h1>
<form th:action="@{/login}" method="post">
<div>
<label for="username">Username:</label>
<input type="text" id="username" name="username" required>
</div>
<div>
<label for="password">Password:</label>
<input type="password" id="password" name="password" required>
</div>
<div>
<button type="submit">Login</button>
</div>
</form>
</body>
</html>
在src/main/java/com/example/demo/controller
目录下创建LoginController.java
文件,内容如下:
package com.example.demo.controller;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
@Controller
public class LoginController {
@GetMapping("/login")
public String login() {
return "login";
}
}
启动Spring Boot应用,访问http://localhost:8080/login
,输入用户名admin
和密码123456
,点击登录按钮。如果认证成功,将跳转到/home
页面。
用户授权是指控制用户对资源的访问权限。Shiro提供了丰富的授权功能,可以根据角色或权限控制用户访问。
在MyRealm.java
中添加以下代码,模拟用户角色和权限:
@Override
protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals) {
SimpleAuthorizationInfo authorizationInfo = new SimpleAuthorizationInfo();
String username = (String) principals.getPrimaryPrincipal();
// 模拟从数据库获取用户角色和权限
if ("admin".equals(username)) {
authorizationInfo.addRole("admin");
authorizationInfo.addStringPermission("user:view");
authorizationInfo.addStringPermission("user:edit");
} else if ("user".equals(username)) {
authorizationInfo.addRole("user");
authorizationInfo.addStringPermission("user:view");
}
return authorizationInfo;
}
在ShiroConfig.java
中配置授权拦截器:
filterChainDefinitionMap.put("/user/view", "perms[user:view]");
filterChainDefinitionMap.put("/user/edit", "perms[user:edit]");
在src/main/java/com/example/demo/controller
目录下创建UserController.java
文件,内容如下:
package com.example.demo.controller;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
@Controller
public class UserController {
@GetMapping("/user/view")
@RequiresPermissions("user:view")
public String viewUser() {
return "user/view";
}
@GetMapping("/user/edit")
@RequiresPermissions("user:edit")
public String editUser() {
return "user/edit";
}
}
在src/main/resources/templates/user
目录下创建view.html
和edit.html
文件,内容如下:
view.html:
<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">
<head>
<meta charset="UTF-8">
<title>View User</title>
</head>
<body>
<h1>View User</h1>
<p>This is the user view page.</p>
</body>
</html>
edit.html:
<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">
<head>
<meta charset="UTF-8">
<title>Edit User</title>
</head>
<body>
<h1>Edit User</h1>
<p>This is the user edit page.</p>
</body>
</html>
启动Spring Boot应用,访问http://localhost:8080/user/view
和http://localhost:8080/user/edit
,验证用户授权功能。只有具有相应权限的用户才能访问这些页面。
在实际应用中,用户信息和权限信息通常存储在数据库中。Shiro可以与数据库集成,实现动态的用户认证和授权。
在pom.xml
中添加以下依赖:
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-jpa</artifactId>
</dependency>
<dependency>
<groupId>com.h2database</groupId>
<artifactId>h2</artifactId>
<scope>runtime</scope>
</dependency>
在application.properties
中添加以下配置:
spring.datasource.url=jdbc:h2:mem:testdb
spring.datasource.driverClassName=org.h2.Driver
spring.datasource.username=sa
spring.datasource.password=password
spring.jpa.database-platform=org.hibernate.dialect.H2Dialect
spring.h2.console.enabled=true
在src/main/java/com/example/demo/entity
目录下创建User.java
文件,内容如下:
package com.example.demo.entity;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
@Entity
public class User {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
private String username;
private String password;
private String role;
// Getters and Setters
}
在src/main/java/com/example/demo/repository
目录下创建UserRepository.java
文件,内容如下:
package com.example.demo.repository;
import com.example.demo.entity.User;
import org.springframework.data.jpa.repository.JpaRepository;
public interface UserRepository extends JpaRepository<User, Long> {
User findByUsername(String username);
}
在MyRealm.java
中修改doGetAuthenticationInfo
和doGetAuthorizationInfo
方法,使用数据库中的用户信息进行认证和授权:
”`java @Autowired private UserRepository userRepository;
@Override protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException { String username = (String) token.getPrincipal();
免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。