Spring Security:添加登录验证码


登录添加验证码是一个非常常见的需求,网上也有非常成熟的解决方案。在传统的登录流程中加入一个登录验证码也不是难事,但是如何在 Spring Security 中添加登录验证码,对于初学者来说还是一件蛮有挑战的事情,因为默认情况下,在 Spring Security 中我们并不需要自己写登录认证逻辑,只需要自己稍微配置一下就可以了,所以如果要添加登录验证码,就涉及到如何在 Spring Security 即有的认证体系中,加入自己的验证逻辑。

准备验证码

要有验证码,首先得先准备好验证码,本文采用 Java 自画的验证码,代码如下:

/**
 * 生成验证码的工具类
 */
public class VerifyCode {

	private int width = 100;// 生成验证码图片的宽度
	private int height = 50;// 生成验证码图片的高度
	private String[] fontNames = { "宋体", "楷体", "隶书", "微软雅黑" };
	private Color bgColor = new Color(255, 255, 255);// 定义验证码图片的背景颜色为白色
	private Random random = new Random();
	private String codes = "0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ";
	private String text;// 记录随机字符串

	/**
	 * 获取一个随意颜色
	 *
	 * @return
	 */
	private Color randomColor() {
		int red = random.nextInt(150);
		int green = random.nextInt(150);
		int blue = random.nextInt(150);
		return new Color(red, green, blue);
	}

	/**
	 * 获取一个随机字体
	 *
	 * @return
	 */
	private Font randomFont() {
		String name = fontNames[random.nextInt(fontNames.length)];
		int style = random.nextInt(4);
		int size = random.nextInt(5) + 24;
		return new Font(name, style, size);
	}

	/**
	 * 获取一个随机字符
	 *
	 * @return
	 */
	private char randomChar() {
		return codes.charAt(random.nextInt(codes.length()));
	}

	/**
	 * 创建一个空白的BufferedImage对象
	 *
	 * @return
	 */
	private BufferedImage createImage() {
		BufferedImage image = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
		Graphics2D g2 = (Graphics2D) image.getGraphics();
		g2.setColor(bgColor);// 设置验证码图片的背景颜色
		g2.fillRect(0, 0, width, height);
		return image;
	}

	public BufferedImage getImage() {
		BufferedImage image = createImage();
		Graphics2D g2 = (Graphics2D) image.getGraphics();
		StringBuffer sb = new StringBuffer();
		for (int i = 0; i < 4; i++) {
			String s = randomChar() + "";
			sb.append(s);
			g2.setColor(randomColor());
			g2.setFont(randomFont());
			float x = i * width * 1.0f / 4;
			g2.drawString(s, x, height - 15);
		}
		this.text = sb.toString();
		drawLine(image);
		return image;
	}

	/**
	 * 绘制干扰线
	 *
	 * @param image
	 */
	private void drawLine(BufferedImage image) {
		Graphics2D g2 = (Graphics2D) image.getGraphics();
		int num = 5;
		for (int i = 0; i < num; i++) {
			int x1 = random.nextInt(width);
			int y1 = random.nextInt(height);
			int x2 = random.nextInt(width);
			int y2 = random.nextInt(height);
			g2.setColor(randomColor());
			g2.setStroke(new BasicStroke(1.5f));
			g2.drawLine(x1, y1, x2, y2);
		}
	}

	public String getText() {
		return text;
	}

	public static void output(BufferedImage image, OutputStream out) throws IOException {
		ImageIO.write(image, "JPEG", out);
	}
}

这个工具类很常见,网上也有很多,就是画一个简单的验证码,通过流将验证码写到前端页面,提供验证码的 Controller 如下:

@RestController
public class VerifyCodeController {

	@GetMapping("/vercode")
	public void code(HttpServletRequest req, HttpServletResponse resp) throws IOException {
		VerifyCode vc = new VerifyCode();
		BufferedImage image = vc.getImage();
		String text = vc.getText();
		HttpSession session = req.getSession();
		session.setAttribute("index_code", text);
		VerifyCode.output(image, resp.getOutputStream());
	}

}

这里创建了一个 VerifyCode 对象,将生成的验证码字符保存到 session 中,然后通过流将图片写到前端,img 标签如下:

<img src="/vercode" alt="">

展示效果如下:
在这里插入图片描述

自定义过滤器

在登陆页展示验证码这个就不需要我多说了,接下来我们来看看如何自定义验证码处理器:

@Component
public class VerifyCodeFilter extends GenericFilterBean {

	private String defaultFilterProcessUrl = "/login";

	@Override
	public void doFilter(ServletRequest req, ServletResponse res, FilterChain chain)
			throws IOException, ServletException {
		HttpServletRequest request = (HttpServletRequest) req;
		HttpServletResponse response = (HttpServletResponse) res;
		if ("POST".equalsIgnoreCase(request.getMethod()) && defaultFilterProcessUrl.equals(request.getServletPath())) {
			// 验证码验证
			String requestCaptcha = request.getParameter("code");
			String genCaptcha = (String) request.getSession().getAttribute("index_code");
			if (StringUtils.isEmpty(requestCaptcha))
				throw new AuthenticationServiceException("验证码不能为空!");
			if (!genCaptcha.toLowerCase().equals(requestCaptcha.toLowerCase())) {
				throw new AuthenticationServiceException("验证码错误!");
			}
		}
		chain.doFilter(request, response);
	}

}

自定义过滤器继承自 GenericFilterBean,并实现其中的 doFilter 方法,在 doFilter 方法中,当请求方法是 POST,并且请求地址是 /login时,获取参数中的 code 字段值,该字段保存了用户从前端页面传来的验证码,然后获取 session 中保存的验证码,如果用户没有传来验证码,则抛出验证码不能为空异常,如果用户传入了验证码,则判断验证码是否正确,如果不正确则抛出异常,否则执行 chain.doFilter(request, response); 使请求继续向下走。

配置

最后在 Spring Security 的配置中,配置过滤器,如下:

@Configuration
public class SecurityConfig extends WebSecurityConfigurerAdapter{
	
	@Autowired
    private VerifyCodeFilter verifyCodeFilter;
	
	@Bean
    PasswordEncoder passwordEncoder() {
        return NoOpPasswordEncoder.getInstance();
    }
	
    @Override
    protected void configure(AuthenticationManagerBuilder auth) throws Exception {
        auth.inMemoryAuthentication()
                .withUser("javakf")
                .password("123").roles("admin");
    }
    
    @Override
    public void configure(WebSecurity web) throws Exception {
        web.ignoring().antMatchers("/vercode.html", "/vercode");
    }

    @Override
    protected void configure(HttpSecurity http) throws Exception {
    	http.addFilterBefore(verifyCodeFilter, UsernamePasswordAuthenticationFilter.class);
        http.authorizeRequests()
                .anyRequest().authenticated()
                .and()
                .formLogin()
                .and()
                .csrf().disable();
    }
    
}

这里只贴出了部分核心代码,即 http.addFilterBefore(verifyCodeFilter, UsernamePasswordAuthenticationFilter.class); ,如此之后,整个配置就算完成了。

测试

接下来在登录中,就需要传入验证码了,如果不传或者传错,都会抛出异常,例如不传的话,抛出如下异常:
在这里插入图片描述

org.springframework.security.authentication.AuthenticationServiceException: 验证码不能为空!
  • 5
    点赞
  • 10
    收藏
    觉得还不错? 一键收藏
  • 2
    评论
要实现自定义短信验证码登录,可以按照以下步骤进行: 1. 添加依赖 在项目中添加 Spring SecuritySpring Security SMS 模块的依赖。 ``` <dependency> <groupId>org.springframework.security</groupId> <artifactId>spring-security-core</artifactId> <version>5.2.2.RELEASE</version> </dependency> <dependency> <groupId>com.github.lanceshohara</groupId> <artifactId>spring-security-sms</artifactId> <version>1.0.2</version> </dependency> ``` 2. 配置 Spring SecuritySpring Security 配置文件中添加配置,包括短信验证码登录相关的配置。 ``` @Configuration @EnableWebSecurity public class SecurityConfig extends WebSecurityConfigurerAdapter { @Autowired private UserDetailsService userDetailsService; @Autowired private SmsCodeAuthenticationSecurityConfig smsCodeAuthenticationSecurityConfig; @Override protected void configure(HttpSecurity http) throws Exception { http .authorizeRequests() .antMatchers("/login/sms").permitAll() .anyRequest().authenticated() .and() .apply(smsCodeAuthenticationSecurityConfig) .and() .formLogin() .loginPage("/login") .loginProcessingUrl("/login/form") .usernameParameter("username") .passwordParameter("password") .defaultSuccessUrl("/") .permitAll() .and() .logout() .logoutUrl("/logout") .logoutSuccessUrl("/") .permitAll(); } @Override protected void configure(AuthenticationManagerBuilder auth) throws Exception { auth.userDetailsService(userDetailsService); } @Bean public PasswordEncoder passwordEncoder() { return new BCryptPasswordEncoder(); } } ``` 其中,`SmsCodeAuthenticationSecurityConfig` 是短信验证码登录的相关配置类,需要单独实现。 3. 实现短信验证码登录相关配置 实现 `SmsCodeAuthenticationSecurityConfig` 配置类,其中包括一个短信验证码过滤器和一个短信验证码认证提供者。 ``` @Configuration public class SmsCodeAuthenticationSecurityConfig extends SecurityConfigurerAdapter<DefaultSecurityFilterChain, HttpSecurity> { @Autowired private UserDetailsService userDetailsService; @Autowired private SmsCodeAuthenticationSuccessHandler smsCodeAuthenticationSuccessHandler; @Autowired private SmsCodeAuthenticationFailureHandler smsCodeAuthenticationFailureHandler; @Override public void configure(HttpSecurity http) throws Exception { SmsCodeAuthenticationFilter smsCodeAuthenticationFilter = new SmsCodeAuthenticationFilter(); smsCodeAuthenticationFilter.setAuthenticationManager(http.getSharedObject(AuthenticationManager.class)); smsCodeAuthenticationFilter.setAuthenticationSuccessHandler(smsCodeAuthenticationSuccessHandler); smsCodeAuthenticationFilter.setAuthenticationFailureHandler(smsCodeAuthenticationFailureHandler); SmsCodeAuthenticationProvider smsCodeAuthenticationProvider = new SmsCodeAuthenticationProvider(); smsCodeAuthenticationProvider.setUserDetailsService(userDetailsService); http.authenticationProvider(smsCodeAuthenticationProvider) .addFilterAfter(smsCodeAuthenticationFilter, UsernamePasswordAuthenticationFilter.class); } } ``` 其中,`SmsCodeAuthenticationFilter` 是短信验证码过滤器,需要单独实现。`SmsCodeAuthenticationSuccessHandler` 和 `SmsCodeAuthenticationFailureHandler` 分别是短信验证码认证成功和失败的处理器,也需要单独实现。 4. 实现短信验证码过滤器 实现 `SmsCodeAuthenticationFilter` 过滤器,重写 `attemptAuthentication` 方法,来处理短信验证码认证请求。 ``` public class SmsCodeAuthenticationFilter extends AbstractAuthenticationProcessingFilter { public static final String SPRING_SECURITY_FORM_MOBILE_KEY = "mobile"; public static final String SPRING_SECURITY_FORM_CODE_KEY = "code"; private String mobileParameter = SPRING_SECURITY_FORM_MOBILE_KEY; private String codeParameter = SPRING_SECURITY_FORM_CODE_KEY; private boolean postOnly = true; public SmsCodeAuthenticationFilter() { super(new AntPathRequestMatcher("/login/sms", "POST")); } @Override public Authentication attemptAuthentication(HttpServletRequest request, HttpServletResponse response) throws AuthenticationException, IOException, ServletException { if (postOnly && !request.getMethod().equals("POST")) { throw new AuthenticationServiceException("Authentication method not supported: " + request.getMethod()); } String mobile = obtainMobile(request); String code = obtainCode(request); if (mobile == null) { mobile = ""; } if (code == null) { code = ""; } mobile = mobile.trim(); SmsCodeAuthenticationToken authRequest = new SmsCodeAuthenticationToken(mobile, code); setDetails(request, authRequest); return this.getAuthenticationManager().authenticate(authRequest); } protected String obtainMobile(HttpServletRequest request) { return request.getParameter(mobileParameter); } protected String obtainCode(HttpServletRequest request) { return request.getParameter(codeParameter); } protected void setDetails(HttpServletRequest request, SmsCodeAuthenticationToken authRequest) { authRequest.setDetails(authenticationDetailsSource.buildDetails(request)); } public void setMobileParameter(String mobileParameter) { this.mobileParameter = mobileParameter; } public void setCodeParameter(String codeParameter) { this.codeParameter = codeParameter; } public void setPostOnly(boolean postOnly) { this.postOnly = postOnly; } public final String getMobileParameter() { return mobileParameter; } public final String getCodeParameter() { return codeParameter; } } ``` 其中,`SmsCodeAuthenticationToken` 是短信验证码认证的 token 类型,需要单独实现。 5. 实现短信验证码认证提供者 实现 `SmsCodeAuthenticationProvider` 提供者,重写 `authenticate` 方法,来进行短信验证码认证。 ``` public class SmsCodeAuthenticationProvider implements AuthenticationProvider { private UserDetailsService userDetailsService; @Override public Authentication authenticate(Authentication authentication) throws AuthenticationException { SmsCodeAuthenticationToken authenticationToken = (SmsCodeAuthenticationToken) authentication; UserDetails userDetails = userDetailsService.loadUserByUsername((String) authenticationToken.getPrincipal()); SmsCodeAuthenticationToken authenticationResult = new SmsCodeAuthenticationToken(userDetails.getUsername(), userDetails.getPassword(), userDetails.getAuthorities()); authenticationResult.setDetails(authenticationToken.getDetails()); return authenticationResult; } @Override public boolean supports(Class<?> authentication) { return SmsCodeAuthenticationToken.class.isAssignableFrom(authentication); } public UserDetailsService getUserDetailsService() { return userDetailsService; } public void setUserDetailsService(UserDetailsService userDetailsService) { this.userDetailsService = userDetailsService; } } ``` 6. 实现短信验证码认证成功和失败的处理器 实现 `SmsCodeAuthenticationSuccessHandler` 和 `SmsCodeAuthenticationFailureHandler` 处理器,来处理短信验证码认证成功和失败的情况。 ``` public class SmsCodeAuthenticationSuccessHandler extends SavedRequestAwareAuthenticationSuccessHandler { @Override public void onAuthenticationSuccess(HttpServletRequest request, HttpServletResponse response, Authentication authentication) throws ServletException, IOException { super.onAuthenticationSuccess(request, response, authentication); } } ``` ``` public class SmsCodeAuthenticationFailureHandler extends SimpleUrlAuthenticationFailureHandler { @Override public void onAuthenticationFailure(HttpServletRequest request, HttpServletResponse response, AuthenticationException exception) throws IOException, ServletException { super.onAuthenticationFailure(request, response, exception); } } ``` 7. 编写控制器 编写控制器,处理短信验证码登录的请求。 ``` @Controller public class LoginController { private final static String SMS_LOGIN_PAGE = "sms-login"; @RequestMapping("/login/sms") public String smsLogin() { return SMS_LOGIN_PAGE; } @RequestMapping(value = "/login/sms", method = RequestMethod.POST) public void smsLogin(HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException { String mobile = request.getParameter("mobile"); String code = request.getParameter("code"); SmsCodeAuthenticationToken token = new SmsCodeAuthenticationToken(mobile, code); AuthenticationManager authenticationManager = new ProviderManager(Collections.singletonList(new SmsCodeAuthenticationProvider())); Authentication authentication = authenticationManager.authenticate(token); SecurityContextHolder.getContext().setAuthentication(authentication); request.getRequestDispatcher("/").forward(request, response); } } ``` 其中,`SmsCodeAuthenticationToken` 是短信验证码认证的 token 类型,需要单独实现。 以上就是实现自定义短信验证码登录的步骤。
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值