《Java后端安全开发Spring Security开发REST服务》4章-4——短信验证码

本文详细介绍了在Java后端使用Spring Security框架开发REST服务时,如何配置和重构验证码功能,特别是短信验证码的生成、发送、验证过程。内容涵盖了配置类、验证码基础类、图形验证码和短信验证码的实现,以及相关过滤器和处理器的配置和重构。
摘要由CSDN通过智能技术生成

在这里插入图片描述
在这里插入图片描述
在这里插入图片描述
在这里插入图片描述

1. 配置相关

1.1 AbstractChannelSecurityConfig

抽象类,封装了Http页面的认证逻辑
applyPasswordAuthenticationConfig设置HttpSecurity的默认表单登录授权认证路由,和imoocAuthenticationSuccessHandler、imoocAuthenticationFailureHandler

extends WebSecurityConfigurerAdapter
implements WebSecurityConfigurer
extends SecurityConfigurer<Filter, T>
applyPasswordAuthenticationConfig

/**
 * 
 */
package com.wxm.spring.security.core.authentication;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.web.authentication.AuthenticationFailureHandler;
import org.springframework.security.web.authentication.AuthenticationSuccessHandler;

import com.wxm.spring.security.core.properties.SecurityConstants;

/**
 * @author zhailiang
 *
 */
public class AbstractChannelSecurityConfig extends WebSecurityConfigurerAdapter {
   

	@Autowired
	protected AuthenticationSuccessHandler imoocAuthenticationSuccessHandler;
	
	@Autowired
	protected AuthenticationFailureHandler imoocAuthenticationFailureHandler;
	
	protected void applyPasswordAuthenticationConfig(HttpSecurity http) throws Exception {
   
		http.formLogin()
			.loginPage(SecurityConstants.DEFAULT_UNAUTHENTICATION_URL)
			.loginProcessingUrl(SecurityConstants.DEFAULT_LOGIN_PROCESSING_URL_FORM)
			.successHandler(imoocAuthenticationSuccessHandler)
			.failureHandler(imoocAuthenticationFailureHandler);
	}
	
}

1.2 BrowserSecurityConfig

  1. @Autowired装载SecurityProperties,读取application.properties中的配置项
  2. 继承AbstractChannelSecurityConfig,在configure中调用AbstractChannelSecurityConfig.applyPasswordAuthenticationConfig,实现浏览器特有的设置:
    验证码配置:.apply(validateCodeSecurityConfig)
    短信配置:.apply(smsCodeAuthenticationSecurityConfig)
    记住我配置:
    .rememberMe()
    .tokenRepository(persistentTokenRepository())
    .tokenValiditySeconds(securityProperties.getBrowser().getRememberMeSeconds())
    .userDetailsService(userDetailsService)
    白名单配置:
    .authorizeRequests()
    .antMatchers(
    SecurityConstants.DEFAULT_UNAUTHENTICATION_URL,
    SecurityConstants.DEFAULT_LOGIN_PROCESSING_URL_MOBILE,
    securityProperties.getBrowser().getLoginPage(),
    SecurityConstants.DEFAULT_VALIDATE_CODE_URL_PREFIX+"/*",
    //securityProperties.getBrowser().getSignUpUrl(),
    //securityProperties.getBrowser().getSession().getSessionInvalidUrl()+".json",
    //securityProperties.getBrowser().getSession().getSessionInvalidUrl()+".html",
    “/user/regist”)
    .permitAll()
    .anyRequest()
    .authenticated()
    关闭CSFR:
    .csrf().disable();

extends AbstractChannelSecurityConfig
configure


```java
/**
 * 
 */
package com.wxm.spring.security.browser;

import javax.sql.DataSource;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.security.web.authentication.rememberme.JdbcTokenRepositoryImpl;
import org.springframework.security.web.authentication.rememberme.PersistentTokenRepository;

import com.wxm.spring.security.core.authentication.AbstractChannelSecurityConfig;
import com.wxm.spring.security.core.authentication.mobile.SmsCodeAuthenticationSecurityConfig;
import com.wxm.spring.security.core.properties.SecurityConstants;
import com.wxm.spring.security.core.properties.SecurityProperties;
import com.wxm.spring.security.core.validate.code.ValidateCodeSecurityConfig;

/**
 * @author zhailiang
 *
 */
@Configuration
public class BrowserSecurityConfig extends AbstractChannelSecurityConfig {
   

	@Autowired
	private SecurityProperties securityProperties;
	
	@Autowired
	private DataSource dataSource;
	
	@Autowired
	private UserDetailsService userDetailsService;
	
	@Autowired
	private SmsCodeAuthenticationSecurityConfig smsCodeAuthenticationSecurityConfig;
	
	@Autowired
	private ValidateCodeSecurityConfig validateCodeSecurityConfig;
	
	//@Autowired
	//private SpringSocialConfigurer imoocSocialSecurityConfig;
	
	//@Autowired
	//private SessionInformationExpiredStrategy sessionInformationExpiredStrategy;
	
	//@Autowired
	//private InvalidSessionStrategy invalidSessionStrategy;
	
	@Override
	protected void configure(HttpSecurity http) throws Exception {
   
		
		applyPasswordAuthenticationConfig(http);
		
		http
			.apply(validateCodeSecurityConfig)
				.and()
			.apply(smsCodeAuthenticationSecurityConfig)
				.and()
			//.apply(imoocSocialSecurityConfig)
				//.and()
			.rememberMe()
				.tokenRepository(persistentTokenRepository())
				.tokenValiditySeconds(securityProperties.getBrowser().getRememberMeSeconds())
				.userDetailsService(userDetailsService)
				.and()
			//.sessionManagement()
				//.invalidSessionStrategy(invalidSessionStrategy)
				//.maximumSessions(securityProperties.getBrowser().getSession().getMaximumSessions())
				//.maxSessionsPreventsLogin(securityProperties.getBrowser().getSession().isMaxSessionsPreventsLogin())
				//.expiredSessionStrategy(sessionInformationExpiredStrategy)
				//.and()
				//.and()
			.authorizeRequests()
				.antMatchers(
					SecurityConstants.DEFAULT_UNAUTHENTICATION_URL,
					SecurityConstants.DEFAULT_LOGIN_PROCESSING_URL_MOBILE,
					securityProperties.getBrowser().getLoginPage(),
					SecurityConstants.DEFAULT_VALIDATE_CODE_URL_PREFIX+"/*",
					//securityProperties.getBrowser().getSignUpUrl(),
					//securityProperties.getBrowser().getSession().getSessionInvalidUrl()+".json",
					//securityProperties.getBrowser().getSession().getSessionInvalidUrl()+".html",
					"/user/regist")
					.permitAll()
				.anyRequest()
				.authenticated()
				.and()
			.csrf().disable();
		
	}

	@Bean
	public PasswordEncoder passwordEncoder() {
   
		return new BCryptPasswordEncoder();
	}
	
	@Bean
	public PersistentTokenRepository persistentTokenRepository() {
   
		JdbcTokenRepositoryImpl tokenRepository = new JdbcTokenRepositoryImpl();
		tokenRepository.setDataSource(dataSource);
//		tokenRepository.setCreateTableOnStartup(true);
		return tokenRepository;
	}
}

1.3 ValidateCodeSecurityConfig

将validateCodeFilter插入到AbstractPreAuthenticatedProcessingFilter之前

extends SecurityConfigurerAdapter
implements SecurityConfigurer
configure

/**
 * 
 */
package com.wxm.spring.security.core.validate.code;

import javax.servlet.Filter;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.config.annotation.SecurityConfigurerAdapter;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.web.DefaultSecurityFilterChain;
import org.springframework.security.web.authentication.preauth.AbstractPreAuthenticatedProcessingFilter;
import org.springframework.stereotype.Component;

/**
 * @author zhailiang
 *
 */
@Component("validateCodeSecurityConfig")
public class ValidateCodeSecurityConfig extends SecurityConfigurerAdapter<DefaultSecurityFilterChain, HttpSecurity> {
   

	@Autowired
	private Filter validateCodeFilter;
	
	@Override
	public void configure(HttpSecurity http) throws Exception {
   
		http.addFilterBefore(validateCodeFilter, AbstractPreAuthenticatedProcessingFilter.class);
	}
}

1.4 SmsCodeAuthenticationSecurityConfig

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值