SpringSecurity实现验证码功能

x33g5p2x  于2022-03-23 转载在 Spring  
字(15.9k)|赞(0)|评价(0)|浏览(275)

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>com.alibaba</groupId>
  30. <artifactId>druid-spring-boot-starter</artifactId>
  31. <version>1.1.10</version>
  32. </dependency>
  33. <dependency>
  34. <groupId>org.mybatis.spring.boot</groupId>
  35. <artifactId>mybatis-spring-boot-starter</artifactId>
  36. <version>2.2.2</version>
  37. </dependency>
  38. <dependency>
  39. <groupId>mysql</groupId>
  40. <artifactId>mysql-connector-java</artifactId>
  41. <scope>runtime</scope>
  42. </dependency>
  43. <dependency>
  44. <groupId>com.github.penggle</groupId>
  45. <artifactId>kaptcha</artifactId>
  46. <version>2.3.2</version>
  47. </dependency>
  48. <dependency>
  49. <groupId>org.springframework.boot</groupId>
  50. <artifactId>spring-boot-starter-test</artifactId>
  51. <scope>test</scope>
  52. </dependency>
  53. <dependency>
  54. <groupId>org.springframework.security</groupId>
  55. <artifactId>spring-security-test</artifactId>
  56. <scope>test</scope>
  57. </dependency>
  58. </dependencies>
  59. <build>
  60. <resources>
  61. <resource>
  62. <directory>src/main/java</directory>
  63. <includes>
  64. <include>**/*.xml</include>
  65. </includes>
  66. </resource>
  67. <resource>
  68. <directory>src/min/resources</directory>
  69. </resource>
  70. </resources>
  71. <plugins>
  72. <plugin>
  73. <groupId>org.springframework.boot</groupId>
  74. <artifactId>spring-boot-maven-plugin</artifactId>
  75. </plugin>
  76. </plugins>
  77. </build>
  78. </project>

2.建表语句

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

3. application.properties

  1. spring.datasource.url=jdbc:mysql://localhost:3306/demo?useUnicode=true&characterEncoding=utf8&useSSL=false&serverTimezone=Asia/Shanghai
  2. spring.datasource.type=com.alibaba.druid.pool.DruidDataSource
  3. spring.datasource.username=root
  4. spring.datasource.password=root

4.model

  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. public class User implements UserDetails {
  9. private Integer id;
  10. private String username;
  11. private String password;
  12. private Boolean enabled;
  13. private Boolean locked;
  14. private List<Role> roles;
  15. public Integer getId() {
  16. return id;
  17. }
  18. public void setId(Integer id) {
  19. this.id = id;
  20. }
  21. public void setUsername(String username) {
  22. this.username = username;
  23. }
  24. @Override
  25. public Collection<? extends GrantedAuthority> getAuthorities() {
  26. List<SimpleGrantedAuthority> list = new ArrayList<>();
  27. for (Role role : roles) {
  28. list.add(new SimpleGrantedAuthority("ROLE_" + role.getName()));
  29. }
  30. return list;
  31. }
  32. @Override
  33. public String getPassword() {
  34. return password;
  35. }
  36. @Override
  37. public String getUsername() {
  38. return username;
  39. }
  40. // 账户是否未过期
  41. @Override
  42. public boolean isAccountNonExpired() {
  43. return true;
  44. }
  45. // 账户是否未锁定
  46. @Override
  47. public boolean isAccountNonLocked() {
  48. return !locked;
  49. }
  50. // 凭证是否未过期
  51. @Override
  52. public boolean isCredentialsNonExpired() {
  53. return true;
  54. }
  55. @Override
  56. public boolean isEnabled() {
  57. return enabled;
  58. }
  59. public void setPassword(String password) {
  60. this.password = password;
  61. }
  62. public void setEnabled(Boolean enabled) {
  63. this.enabled = enabled;
  64. }
  65. public void setLocked(Boolean locked) {
  66. this.locked = locked;
  67. }
  68. public List<Role> getRoles() {
  69. return roles;
  70. }
  71. public void setRoles(List<Role> roles) {
  72. this.roles = roles;
  73. }
  74. @Override
  75. public String toString() {
  76. return "User{" +
  77. "id=" + id +
  78. ", username='" + username + '\'' +
  79. ", password='" + password + '\'' +
  80. ", enabled=" + enabled +
  81. ", locked=" + locked +
  82. '}';
  83. }
  84. }
  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.controller

  1. package com.yl.securitydemo.controller;
  2. import com.google.code.kaptcha.Producer;
  3. import org.springframework.beans.factory.annotation.Autowired;
  4. import org.springframework.web.bind.annotation.GetMapping;
  5. import org.springframework.web.bind.annotation.RestController;
  6. import javax.imageio.ImageIO;
  7. import javax.servlet.ServletOutputStream;
  8. import javax.servlet.http.HttpServletResponse;
  9. import javax.servlet.http.HttpSession;
  10. import java.awt.image.BufferedImage;
  11. @RestController
  12. public class KaptchaController {
  13. @Autowired
  14. Producer producer;
  15. @GetMapping("/hello")
  16. public String hello() {
  17. return "hello";
  18. }
  19. //生成验证码
  20. @GetMapping("/getVerifyCode")
  21. public void getVerifyCode(HttpServletResponse response, HttpSession session) throws Exception{
  22. response.setContentType("image/jpeg");
  23. String text = producer.createText();
  24. session.setAttribute("vf",text);
  25. BufferedImage image = producer.createImage(text);
  26. try(ServletOutputStream sos = response.getOutputStream()) {
  27. ImageIO.write(image,"jpg",sos);
  28. }
  29. }
  30. }

8.验证码配置

  1. package com.yl.securitydemo.config;
  2. import com.google.code.kaptcha.Producer;
  3. import com.google.code.kaptcha.impl.DefaultKaptcha;
  4. import com.google.code.kaptcha.util.Config;
  5. import org.springframework.context.annotation.Bean;
  6. import org.springframework.context.annotation.Configuration;
  7. import java.util.Properties;
  8. @Configuration
  9. public class VerifyCodeConfig {
  10. @Bean
  11. Producer producer() {
  12. Properties properties = new Properties();
  13. properties.setProperty("kaptcha.image.width","150");
  14. properties.setProperty("kaptcha.image.height","50");
  15. properties.setProperty("kaptcha.textproducer.char.string","0123456789");
  16. properties.setProperty("kaptcha.textproducer.char.length","4");
  17. DefaultKaptcha defaultKaptcha = new DefaultKaptcha();
  18. defaultKaptcha.setConfig(new Config(properties));
  19. return defaultKaptcha;
  20. }
  21. }

9.自定义AuthenticationProvider,对验证码进行校验

  1. package com.yl.securitydemo.config;
  2. import org.apache.tomcat.util.http.fileupload.servlet.ServletRequestContext;
  3. import org.springframework.context.annotation.Configuration;
  4. import org.springframework.security.authentication.AuthenticationServiceException;
  5. import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
  6. import org.springframework.security.authentication.dao.DaoAuthenticationProvider;
  7. import org.springframework.security.core.AuthenticationException;
  8. import org.springframework.security.core.userdetails.UserDetails;
  9. import org.springframework.stereotype.Service;
  10. import org.springframework.web.context.request.RequestContextHolder;
  11. import org.springframework.web.context.request.ServletRequestAttributes;
  12. import javax.servlet.http.HttpServletRequest;
  13. public class MyAuthenticationProvider extends DaoAuthenticationProvider {
  14. @Override
  15. protected void additionalAuthenticationChecks(UserDetails userDetails, UsernamePasswordAuthenticationToken authentication) throws AuthenticationException {
  16. //校验密码前先校验验证码
  17. HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
  18. String code = request.getParameter("code");
  19. String vf = (String)request.getSession().getAttribute("vf");
  20. if (code == null || vf == null || !code.equals(vf)) {
  21. throw new AuthenticationServiceException("验证码错误");
  22. }
  23. //校验密码
  24. super.additionalAuthenticationChecks(userDetails, authentication);
  25. }
  26. }

10.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 javax.servlet.ServletException;
  20. import javax.servlet.http.HttpServletRequest;
  21. import javax.servlet.http.HttpServletResponse;
  22. import java.io.IOException;
  23. @Configuration
  24. public class SecurityConfig extends WebSecurityConfigurerAdapter {
  25. @Autowired
  26. UserService userService;
  27. @Bean
  28. PasswordEncoder passwordEncoder() {
  29. return new BCryptPasswordEncoder();
  30. }
  31. @Bean
  32. MyAuthenticationProvider myAuthenticationProvider() {
  33. MyAuthenticationProvider provider = new MyAuthenticationProvider();
  34. provider.setPasswordEncoder(passwordEncoder());
  35. provider.setUserDetailsService(userService);
  36. return provider;
  37. }
  38. @Override
  39. @Bean
  40. protected AuthenticationManager authenticationManager() throws Exception {
  41. return new ProviderManager(myAuthenticationProvider());
  42. }
  43. @Override
  44. protected void configure(AuthenticationManagerBuilder auth) throws Exception {
  45. auth.userDetailsService(userService);
  46. }
  47. @Override
  48. protected void configure(HttpSecurity http) throws Exception {
  49. http.authorizeRequests()
  50. .antMatchers("/getVerifyCode")
  51. .permitAll()
  52. .anyRequest()
  53. .authenticated()
  54. .and()
  55. .formLogin()
  56. .successHandler(new AuthenticationSuccessHandler() {
  57. @Override
  58. public void onAuthenticationSuccess(HttpServletRequest request, HttpServletResponse response, Authentication authentication) throws IOException, ServletException {
  59. response.setContentType("text/html;charset=utf-8");
  60. response.getWriter().write("login success");
  61. }
  62. })
  63. .failureHandler(new AuthenticationFailureHandler() {
  64. @Override
  65. public void onAuthenticationFailure(HttpServletRequest request, HttpServletResponse response, AuthenticationException exception) throws IOException, ServletException {
  66. response.setContentType("text/html;charset=utf-8");
  67. response.getWriter().write("login fail");
  68. }
  69. })
  70. .permitAll()
  71. .and()
  72. .csrf().disable();
  73. }
  74. }

11.测试

1.不携带验证码,登陆失败

2.携带错误验证码,登录失败

3.携带正确的验证码,登录成功

相关文章