集群环境下的Session并发管理

x33g5p2x  于2022-04-15 转载在 其他  
字(14.6k)|赞(0)|评价(0)|浏览(279)

1.pom.xml

  1. <?xml version="1.0" encoding="UTF-8"?>
  2. <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  3. xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
  4. <modelVersion>4.0.0</modelVersion>
  5. <parent>
  6. <groupId>org.springframework.boot</groupId>
  7. <artifactId>spring-boot-starter-parent</artifactId>
  8. <version>2.6.4</version>
  9. <relativePath/> <!-- lookup parent from repository -->
  10. </parent>
  11. <groupId>com.yl</groupId>
  12. <artifactId>securitydemo</artifactId>
  13. <version>0.0.1-SNAPSHOT</version>
  14. <name>securitydemo</name>
  15. <description>Demo project for Spring Boot</description>
  16. <properties>
  17. <java.version>11</java.version>
  18. </properties>
  19. <dependencies>
  20. <dependency>
  21. <groupId>org.springframework.boot</groupId>
  22. <artifactId>spring-boot-starter-security</artifactId>
  23. </dependency>
  24. <dependency>
  25. <groupId>org.springframework.boot</groupId>
  26. <artifactId>spring-boot-starter-web</artifactId>
  27. </dependency>
  28. <dependency>
  29. <groupId>org.springframework.boot</groupId>
  30. <artifactId>spring-boot-starter-jdbc</artifactId>
  31. </dependency>
  32. <dependency>
  33. <groupId>com.alibaba</groupId>
  34. <artifactId>druid-spring-boot-starter</artifactId>
  35. <version>1.1.10</version>
  36. </dependency>
  37. <dependency>
  38. <groupId>org.mybatis.spring.boot</groupId>
  39. <artifactId>mybatis-spring-boot-starter</artifactId>
  40. <version>2.2.2</version>
  41. </dependency>
  42. <dependency>
  43. <groupId>mysql</groupId>
  44. <artifactId>mysql-connector-java</artifactId>
  45. <scope>runtime</scope>
  46. </dependency>
  47. <dependency>
  48. <groupId>com.github.penggle</groupId>
  49. <artifactId>kaptcha</artifactId>
  50. <version>2.3.2</version>
  51. </dependency>
  52. <dependency>
  53. <groupId>org.springframework.session</groupId>
  54. <artifactId>spring-session-data-redis</artifactId>
  55. </dependency>
  56. <dependency>
  57. <groupId>org.springframework.boot</groupId>
  58. <artifactId>spring-boot-starter-data-redis</artifactId>
  59. </dependency>
  60. <dependency>
  61. <groupId>org.springframework.boot</groupId>
  62. <artifactId>spring-boot-starter-test</artifactId>
  63. <scope>test</scope>
  64. </dependency>
  65. <dependency>
  66. <groupId>org.springframework.security</groupId>
  67. <artifactId>spring-security-test</artifactId>
  68. <scope>test</scope>
  69. </dependency>
  70. </dependencies>
  71. <build>
  72. <resources>
  73. <resource>
  74. <directory>src/main/java</directory>
  75. <includes>
  76. <include>**/*.xml</include>
  77. </includes>
  78. </resource>
  79. <resource>
  80. <directory>src/min/resources</directory>
  81. </resource>
  82. </resources>
  83. <plugins>
  84. <plugin>
  85. <groupId>org.springframework.boot</groupId>
  86. <artifactId>spring-boot-maven-plugin</artifactId>
  87. </plugin>
  88. </plugins>
  89. </build>
  90. </project>

2.application.properties

  1. server.port=8080
  2. spring.datasource.url=jdbc:mysql://localhost:3306/demo?useUnicode=true&characterEncoding=utf8&useSSL=false&serverTimezone=Asia/Shanghai
  3. spring.datasource.type=com.alibaba.druid.pool.DruidDataSource
  4. spring.datasource.driver-class-name = com.mysql.cj.jdbc.Driver
  5. spring.datasource.username=root
  6. spring.datasource.password=root
  7. spring.redis.host=192.168.244.136
  8. spring.redis.port=6379
  9. spring.redis.password=root123

3.建表语句

  1. DROP TABLE IF EXISTS `role`;
  2. CREATE TABLE `role` (
  3. `id` int(11) NOT NULL AUTO_INCREMENT,
  4. `name` varchar(100) CHARACTER SET utf8mb4 COLLATE utf8mb4_0900_ai_ci NULL DEFAULT NULL,
  5. `description` varchar(100) CHARACTER SET utf8mb4 COLLATE utf8mb4_0900_ai_ci NULL DEFAULT NULL,
  6. PRIMARY KEY (`id`) USING BTREE
  7. ) ENGINE = InnoDB AUTO_INCREMENT = 4 CHARACTER SET = utf8mb4 COLLATE = utf8mb4_0900_ai_ci ROW_FORMAT = Dynamic;
  8. -- ----------------------------
  9. -- Records of role
  10. -- ----------------------------
  11. INSERT INTO `role` VALUES (1, 'ROLE_db', '数据库管理员');
  12. INSERT INTO `role` VALUES (2, 'ROLE_admin', '系统管理员');
  13. INSERT INTO `role` VALUES (3, 'ROLE_user', '用户');
  14. -- ----------------------------
  15. -- Table structure for user
  16. -- ----------------------------
  17. DROP TABLE IF EXISTS `user`;
  18. CREATE TABLE `user` (
  19. `id` int(11) NOT NULL AUTO_INCREMENT,
  20. `username` varchar(100) CHARACTER SET utf8mb4 COLLATE utf8mb4_0900_ai_ci NULL DEFAULT NULL,
  21. `password` varchar(100) CHARACTER SET utf8mb4 COLLATE utf8mb4_0900_ai_ci NULL DEFAULT NULL,
  22. `enabled` tinyint(1) NULL DEFAULT NULL,
  23. `locked` tinyint(1) NULL DEFAULT NULL,
  24. PRIMARY KEY (`id`) USING BTREE
  25. ) ENGINE = InnoDB AUTO_INCREMENT = 4 CHARACTER SET = utf8mb4 COLLATE = utf8mb4_0900_ai_ci ROW_FORMAT = Dynamic;
  26. -- ----------------------------
  27. -- Records of user
  28. -- ----------------------------
  29. INSERT INTO `user` VALUES (1, 'root', '$2a$10$O8G0X/sUPAA76MV7U3BwY.3Uo8/QMBcqK678Rwkoz.fowbce.CLtO', 1, 0);
  30. INSERT INTO `user` VALUES (2, 'admin', '$2a$10$O8G0X/sUPAA76MV7U3BwY.3Uo8/QMBcqK678Rwkoz.fowbce.CLtO', 1, 0);
  31. INSERT INTO `user` VALUES (3, 'tom', '$2a$10$O8G0X/sUPAA76MV7U3BwY.3Uo8/QMBcqK678Rwkoz.fowbce.CLtO', 1, 0);
  32. -- ----------------------------
  33. -- Table structure for user_role_ref
  34. -- ----------------------------
  35. DROP TABLE IF EXISTS `user_role_ref`;
  36. CREATE TABLE `user_role_ref` (
  37. `id` int(11) NOT NULL AUTO_INCREMENT,
  38. `user_id` int(11) NULL DEFAULT NULL,
  39. `role_id` int(11) NULL DEFAULT NULL,
  40. PRIMARY KEY (`id`) USING BTREE
  41. ) ENGINE = InnoDB AUTO_INCREMENT = 5 CHARACTER SET = utf8mb4 COLLATE = utf8mb4_0900_ai_ci ROW_FORMAT = Dynamic;
  42. -- ----------------------------
  43. -- Records of user_role_ref
  44. -- ----------------------------
  45. INSERT INTO `user_role_ref` VALUES (1, 1, 1);
  46. INSERT INTO `user_role_ref` VALUES (2, 1, 2);
  47. INSERT INTO `user_role_ref` VALUES (3, 2, 2);
  48. INSERT INTO `user_role_ref` VALUES (4, 3, 3);
  49. SET FOREIGN_KEY_CHECKS = 1;

4.实体类

  1. package com.yl.securitydemo.model;
  2. import org.springframework.security.core.GrantedAuthority;
  3. import org.springframework.security.core.authority.SimpleGrantedAuthority;
  4. import org.springframework.security.core.userdetails.UserDetails;
  5. import java.util.ArrayList;
  6. import java.util.Collection;
  7. import java.util.List;
  8. import java.util.Objects;
  9. public class User implements UserDetails {
  10. private Integer id;
  11. private String username;
  12. private String password;
  13. private Boolean enabled;
  14. private Boolean locked;
  15. private List<Role> roles;
  16. public Integer getId() {
  17. return id;
  18. }
  19. public void setId(Integer id) {
  20. this.id = id;
  21. }
  22. public void setUsername(String username) {
  23. this.username = username;
  24. }
  25. @Override
  26. public Collection<? extends GrantedAuthority> getAuthorities() {
  27. List<SimpleGrantedAuthority> list = new ArrayList<>();
  28. for (Role role : roles) {
  29. list.add(new SimpleGrantedAuthority("ROLE_" + role.getName()));
  30. }
  31. return list;
  32. }
  33. @Override
  34. public String getPassword() {
  35. return password;
  36. }
  37. @Override
  38. public String getUsername() {
  39. return username;
  40. }
  41. // 账户是否未过期
  42. @Override
  43. public boolean isAccountNonExpired() {
  44. return true;
  45. }
  46. // 账户是否未锁定
  47. @Override
  48. public boolean isAccountNonLocked() {
  49. return !locked;
  50. }
  51. // 凭证是否未过期
  52. @Override
  53. public boolean isCredentialsNonExpired() {
  54. return true;
  55. }
  56. @Override
  57. public boolean isEnabled() {
  58. return enabled;
  59. }
  60. public void setPassword(String password) {
  61. this.password = password;
  62. }
  63. public void setEnabled(Boolean enabled) {
  64. this.enabled = enabled;
  65. }
  66. public void setLocked(Boolean locked) {
  67. this.locked = locked;
  68. }
  69. public List<Role> getRoles() {
  70. return roles;
  71. }
  72. public void setRoles(List<Role> roles) {
  73. this.roles = roles;
  74. }
  75. @Override
  76. public boolean equals(Object o) {
  77. if (this == o) return true;
  78. if (o == null || getClass() != o.getClass()) return false;
  79. User user = (User) o;
  80. return username.equals(user.username);
  81. }
  82. @Override
  83. public int hashCode() {
  84. return Objects.hash(username);
  85. }
  86. @Override
  87. public String toString() {
  88. return "User{" +
  89. "id=" + id +
  90. ", username='" + username + '\'' +
  91. ", password='" + password + '\'' +
  92. ", enabled=" + enabled +
  93. ", locked=" + locked +
  94. '}';
  95. }
  96. }
  1. package com.yl.securitydemo.model;
  2. import java.io.Serializable;
  3. public class Role implements Serializable {
  4. private Integer id;
  5. private String name;
  6. private String description;
  7. public Integer getId() {
  8. return id;
  9. }
  10. public void setId(Integer id) {
  11. this.id = id;
  12. }
  13. public String getName() {
  14. return name;
  15. }
  16. public void setName(String name) {
  17. this.name = name;
  18. }
  19. public String getDescription() {
  20. return description;
  21. }
  22. public void setDescription(String description) {
  23. this.description = description;
  24. }
  25. @Override
  26. public String toString() {
  27. return "Role{" +
  28. "id=" + id +
  29. ", name='" + name + '\'' +
  30. ", description='" + description + '\'' +
  31. '}';
  32. }
  33. }
  1. package com.yl.securitydemo.model;
  2. import java.io.Serializable;
  3. public class UserRoleRef implements Serializable {
  4. private Integer id;
  5. private Integer userId;
  6. private Integer roleId;
  7. public Integer getId() {
  8. return id;
  9. }
  10. public void setId(Integer id) {
  11. this.id = id;
  12. }
  13. public Integer getUserId() {
  14. return userId;
  15. }
  16. public void setUserId(Integer userId) {
  17. this.userId = userId;
  18. }
  19. public Integer getRoleId() {
  20. return roleId;
  21. }
  22. public void setRoleId(Integer roleId) {
  23. this.roleId = roleId;
  24. }
  25. @Override
  26. public String toString() {
  27. return "UserRoleRef{" +
  28. "id=" + id +
  29. ", userId=" + userId +
  30. ", roleId=" + roleId +
  31. '}';
  32. }
  33. }

5.mapper及其xml文件

  1. package com.yl.securitydemo.mapper;
  2. import com.yl.securitydemo.model.Role;
  3. import com.yl.securitydemo.model.User;
  4. import org.apache.ibatis.annotations.Mapper;
  5. import java.util.List;
  6. @Mapper
  7. public interface UserMapper {
  8. User loadUserByUsername(String username);
  9. List<Role> getRolesByUserId(Integer userId);
  10. }
  1. <?xml version="1.0" encoding="UTF-8"?>
  2. <!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
  3. <mapper namespace="com.yl.securitydemo.mapper.UserMapper">
  4. <select id="loadUserByUsername" resultType="com.yl.securitydemo.model.User">
  5. select * from user where username = #{username}
  6. </select>
  7. <select id="getRolesByUserId" resultType="com.yl.securitydemo.model.Role">
  8. select * from role where id in (select role_id from user_role_ref where user_id = #{userId})
  9. </select>
  10. </mapper>

6.userservice

  1. package com.yl.securitydemo.service;
  2. import com.yl.securitydemo.mapper.UserMapper;
  3. import com.yl.securitydemo.model.User;
  4. import org.springframework.beans.factory.annotation.Autowired;
  5. import org.springframework.security.core.userdetails.UserDetails;
  6. import org.springframework.security.core.userdetails.UserDetailsService;
  7. import org.springframework.security.core.userdetails.UsernameNotFoundException;
  8. import org.springframework.stereotype.Service;
  9. @Service
  10. public class UserService implements UserDetailsService {
  11. @Autowired
  12. UserMapper userMapper;
  13. @Override
  14. public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
  15. User user = userMapper.loadUserByUsername(username);
  16. if (user == null) {
  17. throw new UsernameNotFoundException("用户名不存在");
  18. }
  19. user.setRoles(userMapper.getRolesByUserId(user.getId()));
  20. return user;
  21. }
  22. }

7.security的配置

  1. package com.yl.securitydemo.config;
  2. import com.yl.securitydemo.service.UserService;
  3. import org.springframework.beans.factory.annotation.Autowired;
  4. import org.springframework.context.annotation.Bean;
  5. import org.springframework.context.annotation.Configuration;
  6. import org.springframework.security.authentication.AuthenticationManager;
  7. import org.springframework.security.authentication.ProviderManager;
  8. import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
  9. import org.springframework.security.config.annotation.web.builders.HttpSecurity;
  10. import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
  11. import org.springframework.security.core.Authentication;
  12. import org.springframework.security.core.AuthenticationException;
  13. import org.springframework.security.core.userdetails.UserDetailsService;
  14. import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
  15. import org.springframework.security.crypto.password.NoOpPasswordEncoder;
  16. import org.springframework.security.crypto.password.PasswordEncoder;
  17. import org.springframework.security.web.authentication.AuthenticationFailureHandler;
  18. import org.springframework.security.web.authentication.AuthenticationSuccessHandler;
  19. import org.springframework.security.web.session.HttpSessionEventPublisher;
  20. import org.springframework.session.FindByIndexNameSessionRepository;
  21. import org.springframework.session.security.SpringSessionBackedSessionRegistry;
  22. import javax.servlet.ServletException;
  23. import javax.servlet.http.HttpServletRequest;
  24. import javax.servlet.http.HttpServletResponse;
  25. import java.io.IOException;
  26. @Configuration
  27. public class SecurityConfig extends WebSecurityConfigurerAdapter {
  28. @Autowired
  29. UserService userService;
  30. @Autowired
  31. FindByIndexNameSessionRepository sessionRepository;
  32. // @Autowired
  33. // MyWebAuthenticationDetailsSource myWebAuthenticationDetailsSource;
  34. @Bean
  35. PasswordEncoder passwordEncoder() {
  36. return new BCryptPasswordEncoder();
  37. }
  38. // @Bean
  39. // MyAuthenticationProvider myAuthenticationProvider() {
  40. // MyAuthenticationProvider provider = new MyAuthenticationProvider();
  41. // provider.setPasswordEncoder(passwordEncoder());
  42. // provider.setUserDetailsService(userService);
  43. // return provider;
  44. // }
  45. @Bean
  46. SpringSessionBackedSessionRegistry sessionRegistry() {
  47. return new SpringSessionBackedSessionRegistry(sessionRepository);
  48. }
  49. // @Bean
  50. // HttpSessionEventPublisher httpSessionEventPublisher() {
  51. // return new HttpSessionEventPublisher();
  52. // }
  53. // @Override
  54. // @Bean
  55. // protected AuthenticationManager authenticationManager() throws Exception {
  56. // return new ProviderManager(myAuthenticationProvider());
  57. // }
  58. @Override
  59. protected void configure(AuthenticationManagerBuilder auth) throws Exception {
  60. auth.userDetailsService(userService);
  61. }
  62. @Override
  63. protected void configure(HttpSecurity http) throws Exception {
  64. http.authorizeRequests()
  65. // .antMatchers("/getVerifyCode")
  66. // .permitAll()
  67. .anyRequest()
  68. .authenticated()
  69. .and()
  70. .formLogin()
  71. // .authenticationDetailsSource(myWebAuthenticationDetailsSource)
  72. .permitAll()
  73. .and()
  74. .csrf().disable()
  75. .sessionManagement()
  76. .maximumSessions(1) //限制能登录的用户个数为1
  77. .maxSessionsPreventsLogin(true)// 禁止后面的用户登录
  78. .sessionRegistry(sessionRegistry());
  79. }
  80. }

8.controller

  1. package com.yl.securitydemo.controller;
  2. import org.springframework.beans.factory.annotation.Value;
  3. import org.springframework.web.bind.annotation.GetMapping;
  4. import org.springframework.web.bind.annotation.RestController;
  5. import javax.servlet.http.HttpSession;
  6. @RestController
  7. public class HelloController {
  8. @GetMapping("/hello")
  9. public String hello() {
  10. return "hello";
  11. }
  12. @Value("${server.port}")
  13. Integer port;
  14. @GetMapping("/get")
  15. public String get(HttpSession session) {
  16. return session.getAttribute("name") + ":" + port;
  17. }
  18. @GetMapping("/set")
  19. public String set(HttpSession session){
  20. session.setAttribute("name","yl");
  21. return String.valueOf(port);
  22. }
  23. }

9.测试

1.打包项目,并且以8080和8081两个端口号启动两个实例

2.在客户端A登录admin账号,并且访问8080端口的hello接口

3.在客户端B再登录admin账号,访问8081端口的hello接口,登录发现账号已经登录了,成功限制用户的登录个数为1

相关文章