iis服务器助手广告广告
返回顶部
首页 > 资讯 > 前端开发 > html >Spring Boot Security实现防重登录及在线总数的方法
  • 391
分享到

Spring Boot Security实现防重登录及在线总数的方法

2024-04-02 19:04:59 391人浏览 独家记忆
摘要

这篇文章主要讲解了“Spring Boot Security实现防重登录及在线总数的方法”,文中的讲解内容简单清晰,易于学习与理解,下面请大家跟着小编的思路慢慢深入,一起来研究和学习“spring Boot

这篇文章主要讲解了“Spring Boot Security实现防重登录及在线总数的方法”,文中的讲解内容简单清晰,易于学习与理解,下面请大家跟着小编的思路慢慢深入,一起来研究和学习“spring Boot Security实现防重登录及在线总数的方法”吧!

环境:Spring Boot 2.2.11.RELEASE + JPA2

Security流程处理

Security的核心是Filter,下图是Security的执行流程

Spring Boot Security实现防重登录及在线总数的方法

详细步骤:

1.1

UsernamePassWordAuthenticationFilter的父类是AbstractAuthenticationProcessingFilter首先执行父类中的doFilter方法。

Spring Boot Security实现防重登录及在线总数的方法

1.2 执行

UsernamePasswordAuthenticationFilter中的attemptAuthentication方法

Spring Boot Security实现防重登录及在线总数的方法

这里实例化

UsernamePasswordAuthenticationToken对象存入用户名及密码进行接下来的验证

1.3 进入验证

this.getAuthenticationManager().authenticate(authRequest)  这里使用的是系统提供的ProviderManager对象进行验证

Spring Boot Security实现防重登录及在线总数的方法

关键是下面的这个for循环

Spring Boot Security实现防重登录及在线总数的方法

这里先判断AuthenticationProvider是否被支持

Class<? extends Authentication> toTest = authentication.getClass();

这里的toTest就是

UsernamePasswordAuthenticationFilter类中调用的如下对象

Spring Boot Security实现防重登录及在线总数的方法

1.4 既然要验证用户名密码,那我们肯定地提供一个AuthenticationProvider对象同时必须还得要支持

UsernamePasswordAuthenticationToken对象类型的。所以我们提供如下一个DaoAuthenticationProvider子类,查看该类

Spring Boot Security实现防重登录及在线总数的方法

关键在这个父类中,该父类中如下方法:

public boolean supports(Class<?> authentication) {         return (UsernamePasswordAuthenticationToken.class                 .isAssignableFrom(authentication));     }

也就说明我们只需要提供DaoAuthenticationProvider一个子类就能对用户进行验证了。

1.5 自定义DaoAuthenticationProvider子类

@Bean     public DaoAuthenticationProvider daoAuthenticationProvider() {         DaoAuthenticationProvider daoAuthen = new DaoAuthenticationProvider() ;         daoAuthen.setPasswordEncoder(passwordEncoder());         daoAuthen.setUserDetailsService(userDetailsService());         daoAuthen.setHideUserNotFoundExceptions(false) ;         return daoAuthen ;     }

1.6 执行前面for中的如下代码

result = provider.authenticate(authentication);

这里进入了DaoAuthenticationProvider的父类

AbstractUserDetailsAuthenticationProvider中的authenticate方法

该方法的核心方法

Spring Boot Security实现防重登录及在线总数的方法

retrieveUser方法在子类DaoAuthenticationProvider中实现

Spring Boot Security实现防重登录及在线总数的方法

如果这里返回了UserDetails(查询到用户)将进入下一步

1.7 进入密码的验证

Spring Boot Security实现防重登录及在线总数的方法

这里调用子类DaoAuthenticationProvider的方法

Spring Boot Security实现防重登录及在线总数的方法

剩下的就是成功后的事件处理,如果有异常进行统一的异常处理

Security登录授权认证

  • 实体类

@Entity @Table(name = "T_USERS") public class Users implements UserDetails, Serializable {   private static final long serialVersionUID = 1L;     @Id   @GeneratedValue(generator = "system-uuid")   @GenericGenerator(name = "system-uuid", strategy = "uuid")   private String id ;   private String username ;   private String password ; }
  •  DAO

public interface UsersRepository extends JpaRepository<Users, String>, JpaSpecificationExecutor<Users> {     Users findByUsernameAndPassword(String username, String password) ;     Users findByUsername(String username) ; }
  •  Security 配置

@Configuration public class SecurityConfig extends WEBSecurityConfigurerAdapter {          @Resource     private UsersRepository ur ;     @Resource     private LoGoutSuccesshandler logoutSuccessHandler ;          @Bean     public UserDetailsService userDetailsService() {         return username -> {             Users user = ur.findByUsername(username) ;             if (user == null) {                 throw new UsernameNotFoundException("用户名不存在") ;             }             return user ;         };     }          @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() ;             }         };     }          @Bean     public DaoAuthenticationProvider daoAuthenticationProvider() {         DaoAuthenticationProvider daoAuthen = new DaoAuthenticationProvider() ;         daoAuthen.setPasswordEncoder(passwordEncoder());         daoAuthen.setUserDetailsService(userDetailsService());         daoAuthen.setHideUserNotFoundExceptions(false) ;         return daoAuthen ;     }          @Bean     public SessionReGIStry sessionRegistry() {         return new SessionRegistryImpl() ;     }          // 这个不配置sessionRegistry中的session不失效     @Bean     public httpsessionEventPublisher HttpSessionEventPublisher() {         return new HttpSessionEventPublisher();     }          @Override     protected void configure(HttpSecurity http) throws Exception {         http             .csrf().disable()             .authorizeRequests()             .antMatchers("/pos/**")             .authenticated()         .and()             .fORMLogin()             .loginPage("/sign/login")         .and()             .logout()             .logoutSuccessHandler(logoutSuccessHandler)             .logoutUrl("/sign/logout");     // 这里配置最大同用户登录个数         http.sessionManagement().maximumSessions(1).expiredUrl("/sign/login?expired").sessionRegistry(sessionRegistry()) ;     }      }
  •  Controller相关接口

@Controller public class LoginController {          @RequestMapping("/sign/login")     public String login() {         return "login" ;     }      } @RestController @RequestMapping("/sign") public class LogoutController {          @GetMapping("/logout")     public Object logout(HttpServletRequest request) {         HttpSession session = request.getSession(false);         if (session != null) {             session.invalidate();         }         SecurityContext context = SecurityContextHolder.getContext();         context.setAuthentication(null);         SecurityContextHolder.clearContext();         return "success" ;     }      } @RestController @RequestMapping("/pos") public class PosController {          @GetMapping("")     public Object get() {         return "pos success" ;     }      } // 通过下面接口获取在线人数 @RestController @RequestMapping("/sessions") public class SessionController {          @Resource     private SessionRegistry sessionRegistry ;          @GetMapping("")     public Object list() {         return sessionRegistry.getAllPrincipals() ;     }      }

测试

在chrome浏览器用zs用户登录

Spring Boot Security实现防重登录及在线总数的方法

用360浏览器也用zs登录

Spring Boot Security实现防重登录及在线总数的方法

360登录后刷新chrome浏览器

Spring Boot Security实现防重登录及在线总数的方法

登录已经失效了,配置的最大登录个数也生效了。

完毕!!!

感谢各位的阅读,以上就是“Spring Boot Security实现防重登录及在线总数的方法”的内容了,经过本文的学习后,相信大家对Spring Boot Security实现防重登录及在线总数的方法这一问题有了更深刻的体会,具体使用情况还需要大家实践验证。这里是编程网,小编将为大家推送更多相关知识点的文章,欢迎关注!

--结束END--

本文标题: Spring Boot Security实现防重登录及在线总数的方法

本文链接: https://www.lsjlt.com/news/70714.html(转载时请注明来源链接)

有问题或投稿请发送至: 邮箱/279061341@qq.com    QQ/279061341

本篇文章演示代码以及资料文档资料下载

下载Word文档到电脑,方便收藏和打印~

下载Word文档
猜你喜欢
软考高级职称资格查询
推荐阅读
编程网,编程工程师的家园,是目前国内优秀的开源技术社区之一,形成了由开源软件库、代码分享、资讯、协作翻译、讨论区和博客等几大频道内容,为IT开发者提供了一个发现、使用、并交流开源技术的平台。
  • 官方手机版

  • 微信公众号

  • 商务合作