SpringBootSecurity防重登录及在线总数

 环境:Spring Boot 2.2.11.RELEASE + JPA2

创新互联-专业网站定制、快速模板网站建设、高性价比广西网站开发、企业建站全套包干低至880元,成熟完善的模板库,直接使用。一站式广西网站制作公司更省心,省钱,快速模板网站建设找我们,业务覆盖广西地区。费用合理售后完善,十余年实体公司更值得信赖。

Security流程处理

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

详细步骤:

1.1

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

1.2 执行

UsernamePasswordAuthenticationFilter中的attemptAuthentication方法

这里实例化

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

1.3 进入验证

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

关键是下面的这个for循环

这里先判断AuthenticationProvider是否被支持

 
 
 
 
  1. Class toTest = authentication.getClass();

这里的toTest就是

UsernamePasswordAuthenticationFilter类中调用的如下对象

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

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

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

 
 
 
 
  1. public boolean supports(Class authentication) {
  2.         return (UsernamePasswordAuthenticationToken.class
  3.                 .isAssignableFrom(authentication));
  4.     }

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

1.5 自定义DaoAuthenticationProvider子类

 
 
 
 
  1. @Bean
  2.     public DaoAuthenticationProvider daoAuthenticationProvider() {
  3.         DaoAuthenticationProvider daoAuthen = new DaoAuthenticationProvider() ;
  4.         daoAuthen.setPasswordEncoder(passwordEncoder());
  5.         daoAuthen.setUserDetailsService(userDetailsService());
  6.         daoAuthen.setHideUserNotFoundExceptions(false) ;
  7.         return daoAuthen ;
  8.     }

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

 
 
 
 
  1. result = provider.authenticate(authentication);

这里进入了DaoAuthenticationProvider的父类

AbstractUserDetailsAuthenticationProvider中的authenticate方法

该方法的核心方法

retrieveUser方法在子类DaoAuthenticationProvider中实现

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

1.7 进入密码的验证

这里调用子类DaoAuthenticationProvider的方法

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

Security登录授权认证

  • 实体类
 
 
 
 
  1. @Entity
  2. @Table(name = "T_USERS")
  3. public class Users implements UserDetails, Serializable {
  4.   private static final long serialVersionUID = 1L;
  5.     @Id
  6.   @GeneratedValue(generator = "system-uuid")
  7.   @GenericGenerator(name = "system-uuid", strategy = "uuid")
  8.   private String id ;
  9.   private String username ;
  10.   private String password ;
  11. }
  •  DAO
 
 
 
 
  1. public interface UsersRepository extends JpaRepository, JpaSpecificationExecutor {
  2.     Users findByUsernameAndPassword(String username, String password) ;
  3.     Users findByUsername(String username) ;
  4. }
  •  Security 配置
 
 
 
 
  1. @Configuration
  2. public class SecurityConfig extends WebSecurityConfigurerAdapter {
  3.     
  4.     @Resource
  5.     private UsersRepository ur ;
  6.     @Resource
  7.     private LogoutSuccessHandler logoutSuccessHandler ;
  8.     
  9.     @Bean
  10.     public UserDetailsService userDetailsService() {
  11.         return username -> {
  12.             Users user = ur.findByUsername(username) ;
  13.             if (user == null) {
  14.                 throw new UsernameNotFoundException("用户名不存在") ;
  15.             }
  16.             return user ;
  17.         };
  18.     }
  19.     
  20.     @Bean
  21.     public PasswordEncoder passwordEncoder() {
  22.         return new PasswordEncoder() {
  23.             @Override
  24.             public boolean matches(CharSequence rawPassword, String encodedPassword) {
  25.                 return rawPassword.equals(encodedPassword) ;
  26.             }
  27.             @Override
  28.             public String encode(CharSequence rawPassword) {
  29.                 return rawPassword.toString() ;
  30.             }
  31.         };
  32.     }
  33.     
  34.     @Bean
  35.     public DaoAuthenticationProvider daoAuthenticationProvider() {
  36.         DaoAuthenticationProvider daoAuthen = new DaoAuthenticationProvider() ;
  37.         daoAuthen.setPasswordEncoder(passwordEncoder());
  38.         daoAuthen.setUserDetailsService(userDetailsService());
  39.         daoAuthen.setHideUserNotFoundExceptions(false) ;
  40.         return daoAuthen ;
  41.     }
  42.     
  43.     @Bean
  44.     public SessionRegistry sessionRegistry() {
  45.         return new SessionRegistryImpl() ;
  46.     }
  47.     
  48.     // 这个不配置sessionRegistry中的session不失效
  49.     @Bean
  50.     public HttpSessionEventPublisher httpSessionEventPublisher() {
  51.         return new HttpSessionEventPublisher();
  52.     }
  53.     
  54.     @Override
  55.     protected void configure(HttpSecurity http) throws Exception {
  56.         http
  57.             .csrf().disable()
  58.             .authorizeRequests()
  59.             .antMatchers("/pos/**")
  60.             .authenticated()
  61.         .and()
  62.             .formLogin()
  63.             .loginPage("/sign/login")
  64.         .and()
  65.             .logout()
  66.             .logoutSuccessHandler(logoutSuccessHandler)
  67.             .logoutUrl("/sign/logout");
  68.     // 这里配置最大同用户登录个数
  69.         http.sessionManagement().maximumSessions(1).expiredUrl("/sign/login?expired").sessionRegistry(sessionRegistry()) ;
  70.     }
  71.     
  72. }
  •  Controller相关接口
 
 
 
 
  1. @Controller
  2. public class LoginController {
  3.     
  4.     @RequestMapping("/sign/login")
  5.     public String login() {
  6.         return "login" ;
  7.     }
  8.     
  9. }
  10. @RestController
  11. @RequestMapping("/sign")
  12. public class LogoutController {
  13.     
  14.     @GetMapping("/logout")
  15.     public Object logout(HttpServletRequest request) {
  16.         HttpSession session = request.getSession(false);
  17.         if (session != null) {
  18.             session.invalidate();
  19.         }
  20.         SecurityContext context = SecurityContextHolder.getContext();
  21.         context.setAuthentication(null);
  22.         SecurityContextHolder.clearContext();
  23.         return "success" ;
  24.     }
  25.     
  26. }
  27. @RestController
  28. @RequestMapping("/pos")
  29. public class PosController {
  30.     
  31.     @GetMapping("")
  32.     public Object get() {
  33.         return "pos success" ;
  34.     }
  35.     
  36. }
  37. // 通过下面接口获取在线人数
  38. @RestController
  39. @RequestMapping("/sessions")
  40. public class SessionController {
  41.     
  42.     @Resource
  43.     private SessionRegistry sessionRegistry ;
  44.     
  45.     @GetMapping("")
  46.     public Object list() {
  47.         return sessionRegistry.getAllPrincipals() ;
  48.     }
  49.     
  50. }

 测试:

在chrome浏览器用zs用户登录

用360浏览器也用zs登录

360登录后刷新chrome浏览器

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

完毕!!!

网站题目:SpringBootSecurity防重登录及在线总数
分享链接:http://www.hantingmc.com/qtweb/news10/87410.html

网站建设、网络推广公司-创新互联,是专注品牌与效果的网站制作,网络营销seo公司;服务项目有等

广告

声明:本网站发布的内容(图片、视频和文字)以用户投稿、用户转载内容为主,如果涉及侵权请尽快告知,我们将会在第一时间删除。文章观点不代表本网站立场,如需处理请联系客服。电话:028-86922220;邮箱:631063699@qq.com。内容未经允许不得转载,或转载时需注明来源: 创新互联