您现在的位置是:电脑教程 >>正文
基于Spring Security的身份验证与授权框架构建指南
电脑教程84953人已围观
简介环境:SpringBoot2.7.121. 简介Spring Security是一个功能强大且高度可定制的身份验证和访问控制框架,用于保护基于Spring的应用程序。它采用AOP思想,基于servle ...
环境 :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来保护你的应用程序并实现身份验证和授权功能。服务器租用
完毕!! !
Tags:
转载:欢迎各位朋友分享到网络,但转载请说明文章出处“信息技术视野”。http://www.bziz.cn/html/065a599929.html
相关文章
应用实时安全防护探索
电脑教程随着数字化转型进程的不断加快,应用程序安全作为安全防护关键一环,日益成为企业安全运营关注的焦点,运营人员需要为应用程序提供最佳的安全保护。当前常用的安全防护措施被视为一种附加安全层,它通过增加防御机制 ...
【电脑教程】
阅读更多创建绿色数据中心的三个关键战略
电脑教程要点:根据Dell Technologies近期委托Forrester的一项研究,企业平均过度配置了37%的存储环境,这表明大量客户可以通过整合实现收益。通过减少数据,增加驱动器密度和减少多余的硬件, ...
【电脑教程】
阅读更多CXO思享会走进联想 20余家行业头部企业共议智能化新增长
电脑教程3月9日,以“乘云而上 探路新增长”为主题的CXO思享会在联想集团举办。SAP、中联重科、IDC等20多家行业头部企业和机构有关负责人齐聚联想集团全球总部,就数字化、智能化时代如何创造新增长等话题进行 ...
【电脑教程】
阅读更多
热门文章
最新文章
友情链接
- 戴尔PowerFlex 4.0为客户的IT现代化之旅奠定了坚实的基础
- iOS系统升级——6s9.3.2与10.3.1的对比(探索新旧系统之间的优劣与差异)
- 秒懂1U、2U、4U和42U服务器
- SwatchTouch(探索SwatchTouch的无限可能)
- 戴尔科技领先的高清视频解决方案 助力广电行业实现转型升级
- 携程 SOA 的 Service Mesh 架构落地
- 一键Ghost使用教程(快速学习如何使用一键Ghost软件进行系统备份和还原)
- iOS启动U盘使用教程(从零开始,轻松掌握iOS启动U盘的使用技巧)
- 华硕主板重装系统教程(一步步教你如何重装系统,让华硕主板焕发新生)
- 如何装配和固态硬盘的完整教程(从购买到安装的一步步指南,让你的电脑速度翻倍) b2b信息平台亿华云香港物理机云服务器源码库企业服务器网站建设