基于Spring Security的身份验证与授权框架构建指南
环境:SpringBoot2.7.12
1. 简介
Spring Security是基于架构建一个功能强大且高度可定制的身份验证和访问控制框架 ,用于保护基于Spring的份验应用程序 。它采用AOP思想 ,证授基于servlet过滤器实现安全框架。权框
Spring Security具有以下优势 :
丰富的基于架构建功能:Spring Security提供了完善的认证机制和方法级的授权功能,可以轻松地扩展以满足自定义需求 。服务器租用份验强大的证授社区支持 :与所有Spring项目一样,Spring Security的权框真正强大之处在于可以轻松扩展以满足自定义要求 。此外 ,基于架构建它拥有一个活跃的份验社区,提供了丰富的证授资源和支持。与Spring生态系统的权框集成:Spring Security与Spring生态系统中的源码库其他组件紧密集成,如Spring MVC、基于架构建Spring Boot等,份验使得在构建安全应用程序时更加便捷。证授高度可定制:Spring Security提供了大量的配置选项和扩展点,可以根据具体需求进行定制。本篇文章将会介绍常用的配置及相应的扩展点。
2. 实战案例
2.1 自定义配置
在Spring Security5.7之前版本通过继承WebSecurityConfigurerAdapter类
复制public class SecurityConfig extends WebSecurityConfigurerAdapter { }1.2.5.7之后版本
复制@Bean public SecurityFilterChain apiSecurityFilterChain(HttpSecurity http) throws Exception { // ... }1.2.3.4.在这里每定义一个SecurityFilterChain所注入的免费模板HttpSecurity都是唯一的实例对象。
后续所有的配置都是基于Spring Security5.7.8版本
2.2 自定义验证器
复制@Component public class MemeryAuthticationProvider implements AuthenticationProvider { @Override public Authentication authenticate(Authentication authentication) throws AuthenticationException { UsernamePasswordAuthenticationToken token = (UsernamePasswordAuthenticationToken) authentication ; Object principal = token.getPrincipal() ; Object credentials = token.getCredentials() ; User user = users.get(principal) ; // notNull(user, "用户名或密码错误") ; if (user == null) { return null ; } if (!user.getPassword().equals(credentials)) { throw new RuntimeException("密码错误") ; } return new UsernamePasswordAuthenticationToken(principal, credentials, user.getAuthorities()) ; } @Override public boolean supports(Class<?> authentication) { return UsernamePasswordAuthenticationToken.class.isAssignableFrom(authentication) ; } }1.2.3.4.5.6.7.8.9.10.11.12.13.14.15.16.17.18.19.20.21.22.23.24.25.26.27.28.29.通过上面自定义认证器可以实现自己的验证逻辑。
2.2 自定义UserDetailsService
通过自定义UserDetailsService也可以实现对应的逻辑,只不过这种方式你还需要提供一个PasswordEncoder
复制@Bean public UserDetailsService userDetailsService() { return new UserDetailsService() { @Override public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException { return users.get(username) ; } }; } @Bean public PasswordEncoder passwordEncoder() { return new PasswordEncoder() { @Override public boolean matches(CharSequence rawPassword, String encodedPassword) { return rawPassword.equals(encodedPassword) ; } @Override public String encode(CharSequence rawPassword) { return rawPassword.toString() ; } }; }1.2.3.4.5.6.7.8.9.10.11.12.13.14.15.16.17.18.19.20.21.22.23.24.2.3 拦截指定路径的请求
复制@Bean public SecurityFilterChain apiSecurityFilterChain(HttpSecurity http) throws Exception { http.csrf().disable() ; // 该过滤器链,高防服务器只匹配/api/**路径的请求 http.requestMatcher(new AntPathRequestMatcher("/api/**")) ; // 也可以这样配置多个 // http.requestMatchers().antMatchers("/api/**", "/admin/**") ; // ... DefaultSecurityFilterChain chain = http.build(); return chain ; }1.2.3.4.5.6.7.8.9.10.11.2.4 拦截指定路径及权限
复制@Bean public SecurityFilterChain apiSecurityFilterChain(HttpSecurity http) throws Exception { http.csrf().disable() ; http.authorizeHttpRequests().requestMatchers(new AntPathRequestMatcher("/api/save")).hasAnyRole("C") ; http.authorizeHttpRequests().requestMatchers(new AntPathRequestMatcher("/api/find")).hasAuthority("ROLE_U") ; DefaultSecurityFilterChain chain = http.build(); return chain ; }1.2.3.4.5.6.7.8.2.5 自定义授权决定
复制http.authorizeHttpRequests(registry -> { registry.antMatchers("/api/{ id}").access(new AuthorizationManager<RequestAuthorizationContext>() { @Override public AuthorizationDecision check(Supplier<Authentication> authentication, RequestAuthorizationContext object) { Map<String, String> variables = object.getVariables() ; // 返回的路径是/api/666则进行拦截并且指定具有D的权限 return new AuthorityAuthorizationDecision(variables.get("id").equals("666"), Arrays.asList(new SimpleGrantedAuthority("D"))) ; } }) ; }) ;1.2.3.4.5.6.7.8.9.10.11.2.6 自定义异常处理
复制http.exceptionHandling(customizer -> { customizer.accessDeniedHandler(new AccessDeniedHandler() { @Override public void handle(HttpServletRequest request, HttpServletResponse response, AccessDeniedException accessDeniedException) throws IOException, ServletException { Map<String, Object> errors = new HashMap<>() ; response.setContentType("application/json;charset=utf-8") ; errors.put("code", -1) ; errors.put("status", response.getStatus()) ; errors.put("message", accessDeniedException.getMessage()) ; errors.put("details", ExceptionUtils.getMessage(accessDeniedException)) ; response.getWriter().println(new ObjectMapper().writeValueAsString(errors)) ; } }) ; }) ;1.2.3.4.5.6.7.8.9.10.11.12.13.14.15.2.7 自定义角色继承
复制@Bean public RoleHierarchy hierarchyVoter() { RoleHierarchyImpl hierarchy = new RoleHierarchyImpl(); // ADMIN自动拥有MANAGER的权限 hierarchy.setHierarchy("ROLE_ADMIN > ROLE_MANAGER"); return hierarchy ; }1.2.3.4.5.6.7.2.8 自定义退出登录逻辑
复制http.logout().logoutUrl("/logout").addLogoutHandler(new LogoutHandler() { @Override public void logout(HttpServletRequest request, HttpServletResponse response, Authentication authentication) { System.out.println("退出登录") ; } }).logoutSuccessHandler(new LogoutSuccessHandler() { @Override public void onLogoutSuccess(HttpServletRequest request, HttpServletResponse response, Authentication authentication) throws IOException, ServletException { response.setContentType("text/html;charset=utf-8"); PrintWriter out = response.getWriter() ; out.println("<h2>退出登录成功</h2>") ; out.close() ; } }) ;1.2.3.4.5.6.7.8.9.10.11.12.13.14.15.2.9 自定义登录失败逻辑
复制http .formLogin() .failureHandler(new AuthenticationFailureHandler() { @Override public void onAuthenticationFailure(HttpServletRequest request, HttpServletResponse response, AuthenticationException exception response.setContentType("application/json;charset=UTF-8") ; PrintWriter out = response.getWriter() ; out.println("{ \"code\": -1, \"message\": \"" + getRootCause(exception).getMessage() + "\"}") ; out.close(); } });1.2.3.4.5.6.7.8.9.10.11.2.10 自定义过滤器
复制@Bean public PackAuthenticationFilter packAuthenticationFilter() { return new PackAuthenticationFilter() ; } // 添加自定义过滤器到Security Filter Chain中 http.addFilterBefore(packAuthenticationFilter(), RequestCacheAwareFilter.class) ;1.2.3.4.5.6.2.11 配置多个过滤器链
复制@Bean public SecurityFilterChain apiSecurityFilterChain(HttpSecurity http) throws Exception { // 拦截/api/** http.requestMatcher(new AntPathRequestMatcher("/api/**")) ; } @Bean public SecurityFilterChain apiSecurityFilterChain(HttpSecurity http) throws Exception { // 拦截/admin/** http.requestMatcher(new AntPathRequestMatcher("/admin/**")) ; }1.2.3.4.5.6.7.8.9.10.2.12 开启全局方法拦截
复制@Configuration @EnableGlobalMethodSecurity(jsr250Enabled = true, prePostEnabled = true, securedEnabled = true) public class SecurityConfig { } // 使用 @GetMapping("/find") @PreAuthorize("hasRole(GUEST)") public Object find(HttpServletResponse response) throws Exception { return "find method invoke..." ; }1.2.3.4.5.6.7.8.9.2.13 国际化支持
复制@Bean public ReloadableResourceBundleMessageSource messageSource() { ReloadableResourceBundleMessageSource messageSource = new ReloadableResourceBundleMessageSource(); // 这里会按照顺序查找的 messageSource.addBasenames( "classpath:org/springframework/security/messages", "classpath:messages/messages" ) ; return messageSource ; }1.2.3.4.5.6.7.8.9.10.2.14 防止重复登录
复制http.sessionManagement().maximumSessions(1).expiredSessionStrategy(new SessionInformationExpiredStrategy() { @Override public void onExpiredSessionDetected(SessionInformationExpiredEvent event) throws IOException, ServletException { HttpServletResponse response = event.getResponse() ; response.setContentType("application/json;charset=UTF-8"); PrintWriter out = response.getWriter(); out.println("{ \"code\": -1, \"message\": \"会话已过期,或重复登录\"}"); out.close(); } }) ;1.2.3.4.5.6.7.8.9.10.注意:你的UserDetails必须重写equals和hashCode方法
总结 :以上是在实际开发中经常会应用到的一些配置及相应功能的香港云服务器使用 。Spring Security是一个强大的安全认证框架,它提供了丰富的安全功能来保护您的应用程序。通过本文的基础配置示例,你可以轻松地开始使用Spring Security来保护你的应用程序并实现身份验证和授权功能。模板下载
完毕 ! ! !
相关文章
网络安全入口涵盖了几种设计模式,包括全局路由模式、全局卸载模式和健康终端监控模式。网络安全入口侧重于:全局路由、低延迟故障切换和在边缘处减轻攻击。上图包含了3个需求:网络安全入口模式封装了全局路由模式2025-12-07
探索LGG5广角镜头的独特魅力(解析LGG5广角镜头的拍摄效果和应用场景)
在现代社会中,手机已经成为了人们生活中必不可少的一部分。而随着科技的不断发展,手机摄像功能也逐渐得到了提升,从最初的简单拍照到如今的多功能摄像器材,手机摄影技术的发展蓬勃而迅猛。而LGG5作为一款颇受2025-12-07
使用U盘进行深度技术安装的完整教程(通过U盘轻松安装深度技术,让你快速上手)
在这个数字化时代,深度技术已经成为了一个非常重要的领域。如果你对深度技术感兴趣,想要快速上手,那么使用U盘进行深度技术安装将是一个非常不错的选择。本文将为你提供一份完整的教程,教你如何使用U盘来安装深2025-12-07
对于任何数据中心来说,最重要的任务之一是环境监测和管理。 高温和高湿度会损坏 IT 设备,导致它们出现故障。 这可能会给在数据中心内工作的任何人带来不舒服的条件。幸运的是,有许多系统和技术可以帮助监控2025-12-07
据Bleeping Computer消息,来自纽约的37岁的男子John Telusma因在跨国网络犯罪组织运营的Infraud卡片门户上出售、使用被盗和受损信用卡、个人信息、财务信息而被判处四年有期2025-12-07
用大白菜制作U盘系统教程(简单易学的DIYU盘系统制作方法,让你的U盘更加实用)
随着科技的不断发展,越来越多的人喜欢将操作系统安装在U盘上,便于携带和使用。而大白菜正是一种能够帮助我们制作U盘系统的神奇工具。本文将为大家介绍使用大白菜制作U盘系统的详细步骤和注意事项。1.安装大白2025-12-07

最新评论