Springboot集成SpringSecurity实现权限管理
Spring Boot 集成 Spring Security 是一种常见的方法来实现基于角色的权限管理。下面是一个简单的示例代码,包括必要的注释,帮助你理解如何实现这一功能。
在Spring Boot项目中集成Spring Security以实现权限管理是一个常见的需求。Spring Security是一个功能强大且高度可定制的身份验证和访问控制框架。以下是一个基本的步骤指南,帮助你在Spring Boot项目中集成Spring Security并实现权限管理。
1. 添加依赖
首先,在你的 pom.xml
文件中添加 Spring Security 相关的依赖:
<dependencies>
<!-- Spring Boot Starter Web -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<!-- Spring Boot Starter Security -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-security</artifactId>
</dependency>
<!-- Spring Boot Starter Thymeleaf (可选,如果你使用 Thymeleaf 作为模板引擎) -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-thymeleaf</artifactId>
</dependency>
</dependencies>
2. 配置 Spring Security安全设置
创建一个配置类来配置 Spring Security。
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.provisioning.InMemoryUserDetailsManager;
@Configuration
@EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter {
@Override
protected void configure(HttpSecurity http) throws Exception {
http
.authorizeRequests()
.antMatchers("/admin/**").hasRole("ADMIN") // 访问 /admin/** 需要ADMIN角色
.antMatchers("/user/**").hasRole("USER") // 访问 /user/** 需要USER角色
.antMatchers("/", "/home").permitAll() // 访问根路径和 /home 路径不需要认证
.anyRequest().authenticated() // 其他请求需要认证
.and()
.formLogin()
.loginPage("/login") // 自定义登录页面
.permitAll()
.and()
.logout()
.permitAll();
}
// 使用内存中的用户存储进行简单配置(实际应用中应从数据库加载用户)
@Override
protected void configure(AuthenticationManagerBuilder auth) throws Exception {
auth.inMemoryAuthentication()
.withUser(User.withDefaultPasswordEncoder()
.username("admin")
.password("admin")
.roles("ADMIN"))
.and()
.withUser(User.withDefaultPasswordEncoder()
.username("user")
.password("user")
.roles("USER"));
}
// 自定义 UserDetailsService(这里使用内存中的用户管理作为示例)
@Bean
@Override
public UserDetailsService userDetailsService() {
return new InMemoryUserDetailsManager();
}
}
3. 创建控制器
创建一些简单的控制器来测试权限管理。
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
@Controller
public class TestController {
@GetMapping("/")
public String home() {
return "home"; // 返回 home 视图(可以是 Thymeleaf 模板)
}
@GetMapping("/admin")
public String admin() {
return "admin"; // 返回 admin 视图(需要ADMIN角色)
}
@GetMapping("/user")
public String user() {
return "user"; // 返回 user 视图(需要USER角色)
}
@GetMapping("/login")
public String login() {
return "login"; // 返回登录页面视图
}
}
4. 创建视图(可选)
创建一些简单的 Thymeleaf 模板作为视图。
src/main/resources/templates/home.html
<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">
<head>
<title>Home</title>
</head>
<body>
<h1>Home Page</h1>
<a href="/login">Login</a> |
<a href="/admin">Admin</a> |
<a href="/user">User</a>
</body>
</html>
src/main/resources/templates/admin.html
<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">
<head>
<title>Admin</title>
</head>
<body>
<h1>Admin Page</h1>
<p>You need ADMIN role to access this page.</p>
<a href="/login">Login</a> |
<a href="/">Home</a> |
<a href="/user">User</a>
</body>
</html>
src/main/resources/templates/user.html
<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">
<head>
<title>User</title>
</head>
<body>
<h1>User Page</h1>
<p>You need USER role to access this page.</p>
<a href="/login">Login</a> |
<a href="/">Home</a> |
<a href="/admin">Admin</a>
</body>
</html>
src/main/resources/templates/login.html
<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">
<head>
<title>Login</title>
</head>
<body>
<h1>Login Page</h1>
<form th:action="@{/login}" method="post">
<div>
<label> Username: <input type="text" name="username"/> </label>
</div>
<div>
<label> Password: <input type="password" name="password"/> </label>
</div>
<div>
<button type="submit">Sign in</button>
</div>
</form>
</body>
</html>
5. 运行应用
启动 Spring Boot 应用,并访问 http://localhost:8080
。你应该会看到首页,并能够通过点击链接访问登录页面,然后使用 admin/admin
或 user/user
登录来访问相应的受保护页面。