SS 可能是指 Spring Security,这是一个广泛使用的开源安全框架,用于保护Spring应用程序。以下是 Spring Security 的使用方法大全
安装和配置 1 安装 Spring Security 使用 Maven 或 Gradle: 在项目的 pom.xml 中添加 Spring Security 依赖项:<dependencies> <dependency> <groupId>org.springframework.security</groupId> <artifactId>spring-security-core</artifactId> <version>最新版本</version> </dependency> <!-- 其他依赖项 --> </dependencies> 手动下载: 下载最新版本的 Spring Security JAR 文件,放在项目的 lib 目录中。 2 配置 Spring Security 在 main/java 包下创建 SecurityConfig 类: package com.example.security; import org.springframework.beans.factory.annotation.EnableAutoConfiguration; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.ComponentScan; import org.springframework.security.beans.factory.annotation.EnableWebSecurity; import org.springframework.security.config.annotation.web.builders.WebSecurity; import org.springframework.security.config.annotation.web.servlet.PetStoreWebSecurityConfigurer; @EnableWe...
安装和配置
1 安装 Spring Security
- 使用 Maven 或 Gradle:
- 在项目的
pom.xml中添加 Spring Security 依赖项:<dependencies> <dependency> <groupId>org.springframework.security</groupId> <artifactId>spring-security-core</artifactId> <version>最新版本</version> </dependency> <!-- 其他依赖项 --> </dependencies>
- 在项目的
- 手动下载:
- 下载最新版本的 Spring Security JAR 文件,放在项目的
lib目录中。
- 下载最新版本的 Spring Security JAR 文件,放在项目的
2 配置 Spring Security
-
在
main/java包下创建SecurityConfig类:package com.example.security; import org.springframework.beans.factory.annotation.EnableAutoConfiguration; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.ComponentScan; import org.springframework.security.beans.factory.annotation.EnableWebSecurity; import org.springframework.security.config.annotation.web.builders.WebSecurity; import org.springframework.security.config.annotation.web.servlet.PetStoreWebSecurityConfigurer; @EnableWebSecurity @ComponentScan public class SecurityConfig { @Bean public WebSecurity webSecurity() { return new WebSecurity().addSecurityFilterChain("/**", new PetStoreWebSecurityConfigurer()); } } -
在
main/resources目录下创建application.properties:# 认证配置 security.enable.autoconfiguration=true security Spring Security配置... # 记住我功能 remember_meEnabled=true remember_me.cookie.name=REMEMBER_ME
安全配置
1 启用 WebSecurity
在 SecurityConfig 类中使用 @EnableWebSecurity 注解,启用 WebSecurity。
2 配置用户和角色
-
创建用户数据库表:
CREATE TABLE `users` ( id INT PRIMARY KEY AUTO_INCREMENT, username VARCHAR(255) UNIQUE NOT NULL, password VARCHAR(255) NOT NULL, email VARCHAR(255) NOT NULL ); CREATE TABLE `roles` ( id INT PRIMARY KEY AUTO_INCREMENT, name VARCHAR(255) NOT NULL ); -
创建
UserDetailsService实现类:package com.example.security.service; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.security.core.userdetails.UserDetailsService; import org.springframework.security.core.userdetails.User; import org.springframework.security.core.userdetails.UsernameNotFoundException; @Service @Transactional public class CustomUserDetailsService implements UserDetailsService { @Autowired private UserRepository userRepository; @Override public User loadUserByUsername(String username) throws UsernameNotFoundException { User user = userRepository.findByUsername(username); return new User(user.getUsername(), user.getPassword(), user.getAuthorities(), true, true, System.currentTimeMillis()); } }
3 配置密码编码器
- **在
application.properties中添加密码编码器配置:Spring Security: passwordEncoder=org.springframework.security.crypto.password.PBCipher或者:
Spring Security: passwordEncoder=org.springframework.security.crypto.password.Pbkdf2PasswordEncoder
4 配置 RoleHierarchy
-
创建
RoleHierarchyConfig类:package com.example.security.config; import org.springframework.security.userdetails.RoleHierarchy; import org.springframework.security.userdetails.User; import org.springframework.security.userdetails.UserDetailsService; import org.springframework.security.userdetails.UserRole; import org.springframework.security.userdetails.config.RoleHierarchyConfigurer; public class RoleHierarchyConfig { public RoleHierarchy roleHierarchy() { return new RoleHierarchy( UserRole.ROLE_ADMIN, new User[]{new User(null, null, "ROLE_USER", "ROLE_ADMIN")}, "ROLE_ADMIN" ); } }
认证方法
1 安全过滤器链
- **在
SecurityConfig中添加安全过滤器链:@Bean public WebSecurity webSecurity() { return new WebSecurity() .addSecurityFilterChain("/**", new PetStoreWebSecurityConfigurer()) .addSecurityFilterChain("/api/auth", new CustomAuthenticationFilter()); }
2 自定义认证逻辑
-
**创建
CustomAuthenticationFilter继承AbstractAuthenticationFilter:package com.example.security.filter; import org.springframework.security.authentication.AbstractAuthenticationFilter; import org.springframework.security.authentication.AuthenticationException; import org.springframework.security.authentication.UsernameUsernamePasswordAuth; import org.springframework.security.core.Authentication; import org.springframework.security.core.context.SecurityContextHolder; public class CustomAuthenticationFilter extends AbstractAuthenticationFilter { @Override protected Authentication attemptAuthentication( UsernameUsernamePasswordAuth auth, HttpServletRequest request, HttpServletResponse response, FilterChain chain) { // 自定义认证逻辑 return super.attemptAuthentication(auth, request, response, chain); } }
授权(权限管理)
1 使用 @PreAuthorize 和 @PostAuthorize
- **在控制器方法上使用注解:
@PreAuthorize("hasRole('ROLE_ADMIN')") @GetMapping("/admin") public String adminPage() { return "admin"; }
2 使用 PermissionEvaluator
-
**创建
PermissionEvaluator实现类:package com.example.security.evaluator; import org.springframework.security.access.PermissionEvaluator; import org.springframework.security.core.context.SecurityContextHolder; import org.springframework.security.web.access.WebAccessEvaluator; public class WebPermissionEvaluator extends WebAccessEvaluator { @Override public boolean supports(Class<?> cls, Class<?> domainClass, String type) { return true; } @Override public PermissionEvaluator evaluatePermission( PermissionEvaluator.PermissionType type, Object domainObject, String permission, Object[] parameters) { // 定义权限逻辑 return true; } }
过滤器链和拦截器
1 自定义过滤器
-
**创建自定义过滤器实现
Filter接口:package com.example.security.filter; import org.springframework.security.filter.FilterChain; import org.springframework.security.web.filter.AbstractFilter; import org.springframework.security.web.filter.PathMatchFilter; import org.springframework.security.web.filter.SecurityFilterChain; public class CustomFilter extends PathMatchFilter { public CustomFilter() { super(new SecurityFilterChain()); } @Override protected boolean supports(RequestContext requestContext, String chain) { return "/api/".equals(requestContext.getRequest().getRequestUri()); } @Override public FilterChain doFilter(RequestContext requestContext, FilterChain filterChain) { // 定义拦截逻辑 return filterChain.next(requestContext); } }
2 配置过滤器链
- **在
SecurityConfig中添加过滤器链:@Bean public WebSecurity webSecurity() { return new WebSecurity() .addSecurityFilterChain("/**", new CustomFilter()); }
其他高级功能
1 记住我功能
- **在
application.properties中配置:remember_meEnabled=true remember_me.cookie.name=REMEMBER_ME
2 多因素认证(MFA)
- **使用
spring-security-mfa模块:<dependency> <groupId>org.springframework.security</groupId> <artifactId>spring-security-mfa</artifactId> <version>最新版本</version> </dependency> - **配置 MFA:
@Bean public MultiFactorAuthenticationConfig mfaConfig() { return new MultiFactorAuthenticationConfig(); }
3 权限分配
- **使用
RoleHierarchyConfigurer:@Bean public RoleHierarchyConfigurer roleHierarchyConfigurer() { return new RoleHierarchyConfigurer() .withUserDetailsService(userDetailsService) .addRoleHierarchy(new RoleHierarchy( UserRole.ROLE_ADMIN, new User[]{new User(null, null, "ROLE_USER", "ROLE_ADMIN")}, "ROLE_ADMIN" )); }
4 API Key认证
-
**创建
ApiKeyWebSecurityConfigurer:package com.example.security.config; import org.springframework.security.config.annotation.web.servlet.ApiKeyWebSecurityConfigurer; import org.springframework.security.web.servlet.ApiKeyFilter; public class ApiKeyWebSecurityConfigurer extends Api

相关文章







