Spring Security渐入佳境(三) -- 图片验证码,模拟短信登录以及RememberMe的使用

(一)图片验证码

<1>图片验证码对象

public class ImageCode {
    private BufferedImage image;//验证码图片
	private String code;//验证码
    private LocalDateTime expireTime;//过期时间
    //构造函数(图片,验证码,过期秒数)
    public ImageCode(BufferedImage image, String code, long lengthOfLiveTime) {
    	this.image = image;
    	this.code = code;
        this.expireTime = LocalDateTime.now().plusSeconds(lengthOfLiveTime);
    }
    //构造函数(图片,验证码,过期时间)
    public ImageCode(BufferedImage image, String code, LocalDateTime expireTime){
    	this.image = image;
    	this.code = code;
        this.expireTime = expireTime;
    }
    //是否过期
    public boolean isExpired(){
        return this.getExpireTime().isBefore(LocalDateTime.now());
    }
    //getter and setter...
}

<2>图片验证码生成器

//验证码生成器接口
public interface ValidateCodeGenerator {

	ValidateCode generate(ServletWebRequest request);
}
//图片验证码生成器
@Component("imageValidateCodeGenerator")
public class ImageCodeGenerator implements ValidateCodeGenerator {
    /**
     * 生成图形码
     * @param request
     * @return
     */
    @Override
    public ImageCode generate(ServletWebRequest request) {
        int width = ServletRequestUtils.getIntParameter(request.getRequest(), "width", 67);
        int height = ServletRequestUtils.getIntParameter(request.getRequest(), "height", 25);
        BufferedImage image = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);

        Graphics g = image.getGraphics();

        Random random = new Random();

        g.setColor(getRandColor(200, 250));
        g.fillRect(0, 0, width, height);
        g.setFont(new Font("Times New Roman", Font.ITALIC, 20));
        g.setColor(getRandColor(160, 200));
        for (int i = 0; i < 155; i++) {
            int x = random.nextInt(width);
            int y = random.nextInt(height);
            int xl = random.nextInt(12);
            int yl = random.nextInt(12);
            g.drawLine(x, y, x + xl, y + yl);
        }

        String sRand = "";
        //验证码位数
        for (int i = 0; i < 4; i++) {
            String rand = String.valueOf(random.nextInt(10));
            sRand += rand;
            g.setColor(new Color(20 + random.nextInt(110), 20 + random.nextInt(110), 20 + random.nextInt(110)));
            g.drawString(rand, 13 * i + 6, 16);
        }

        g.dispose();
		//图形验证码过期时间
        return new ImageCode(image, sRand, 60);
    }
    /**
     * 生成随机背景条纹
     *
     * @param fc
     * @param bc
     * @return
     */
    private Color getRandColor(int fc, int bc) {
        Random random = new Random();
        if (fc > 255) {
            fc = 255;
        }
        if (bc > 255) {
            bc = 255;
        }
        int r = fc + random.nextInt(bc - fc);
        int g = fc + random.nextInt(bc - fc);
        int b = fc + random.nextInt(bc - fc);
        return new Color(r, g, b);
    }
}

<3>控制器

@RestController
public class ValidateCodeController {
	public static String SESSION_KEY = "SESSION_IMAGE_CODE_KEY";
    private SessionStrategy sessionStrategy = new HttpSessionSessionStrategy();
    @Autowired
    ValidateCodeGenerator imageGenerator;
    @GetMapping("/code/image")
    public void getImageCode(HttpServletRequest request, HttpServletResponse response) throws IOException {
        ImageCode imageCode = (ImageCode) imageGenerator.generate(new ServletWebRequest(request));
        //将验证码存入session
        sessionStrategy.setAttribute(new ServletWebRequest(request), SESSION_KEY, imageCode);
        ImageIO.write(imageCode.getImage(), "JPEG", response.getOutputStream());
    }
    }
}

<4>SpringSecurity配置

因为获取图形验证码不需认证,因此需要对这段URL放行。

@Configuration
@EnableWebSecurity
public class BrowserSecurityConfig extends WebSecurityConfigurerAdapter {
    @Override
    protected void configure(HttpSecurity http) throws Exception {
    //...
        //其他的配置与之前的章节一样
		.authorizeRequests()//对请求授权
	    .antMatchers("/authentication/login","/login.html","/imageCode")
	    .permitAll()
	//...    
    }
}

<5>HTML页面调整

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
    <body>
    <p>账户密码登陆界面</p>
        <form action="/accessIn/form" method="post">
            <p>
                <label>Username</label> <input type="text" name="username" id="username" >
            </p>
            <p>
                <label>Password</label> <input type="password" name="password" id="password">
            </p>
            <p>
                <b>图形验证码:</b>
                <b>
                    <input type="text" name="imageCode"/>
                    <img src="/imageCode"/>
                </b>
            </p>
            <input type="submit" value="Login"/>
        </form>
    </body>
</html>

<6>校验图形验证码逻辑

自定义一个校验验证码的异常:

//AuthenticationException是security对认证中产生的异常定义的一个基类
public class ValidateCodeException extends AuthenticationException {
    public ValidateCodeException(String msg) {
        super(msg);
    }
}

自定义一个图形验证码的校验过滤器:

@Component("imageCodeFilter")
public class ValidateCodeFilter extends OncePerRequestFilter implements InitializingBean  {//每个请求过滤一次
    /**
     * 验证码校验失败处理器
     */
    @Autowired
    private AuthenticationFailureHandler authenticationFailureHandler;
    /**
     * 存放所有需要校验验证码的url
     */
    private Set<String> urls = new HashSet<>();
    /**
     * 验证请求url与配置的url是否匹配的工具类
     */
    private AntPathMatcher pathMatcher = new AntPathMatcher();
 	/** 初始化bean的时候执行,可以针对某个具体的bean进行配置。
 	 * afterPropertiesSet 必须实现 InitializingBean接口。
     * 初始化要拦截的url配置信息(该方法会在初始化bean的时候执行)
     */
    @Override
    public void afterPropertiesSet() throws ServletException {
        super.afterPropertiesSet();
        String[] configUrls = StringUtils.splitByWholeSeparatorPreserveAllTokens("/test1/*,/test2/*", ",");
        for(String url: configUrls){
            urls.add(url);
        }
        //登录请求是一定要校验图形验证码的,因此一定放入校验集合中
        urls.add("/accessIn/form");
    }
    
    @Override
    protected void doFilterInternal(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, FilterChain filterChain) throws ServletException, IOException {
    	boolean checkUrl = false;
        for(String url:urls){
        	//正则匹配
            if(pathMatcher.match(url, httpServletRequest.getRequestURI())){
                checkUrl = true;
                break;
            }
        }
        if(checkUrl && StringUtils.equals(request.getMethod(),"POST")) {
            logger.info("校验请求(" + httpServletRequest.getRequestURI() + ")中的验证码");
            try {
                validate(new ServletWebRequest(httpServletRequest, httpServletResponse));
                logger.info("验证码校验通过");
            } catch (ValidateCodeException exception) {
                authenticationFailureHandler.onAuthenticationFailure(httpServletRequest, httpServletResponse, exception);
                //校验验证码失败就返回不继续执行过滤器链了
                return;
            }
        }
        //传递下去继续执行
        filterChain.doFilter(httpServletRequest, httpServletResponse);
    }
    //校验逻辑
    private void validate(ServletWebRequest request) {

        ImageCode codeInSession = (ImageCode) sessionStrategy.getAttribute(request, ValidateCodeController.SESSION_KEY);

        String codeInRequest;
        try {
            codeInRequest = ServletRequestUtils.getStringParameter(request.getRequest(),
                    processorType.getParamNameOnValidate());
        } catch (ServletRequestBindingException e) {
            throw new ValidateCodeException("获取验证码的值失败");
        }

        if (StringUtils.isBlank(codeInRequest)) {
            throw new ValidateCodeException("验证码的值不能为空");
        }

        if (codeInSession == null) {
            throw new ValidateCodeException( "验证码不存在");
        }

        if (codeInSession.isExpired()) {
            sessionStrategy.removeAttribute(request, ValidateCodeController.SESSION_KEY);
            throw new ValidateCodeException( "验证码已过期");
        }

        if (!StringUtils.equals(codeInSession.getCode(), codeInRequest)) {
            throw new ValidateCodeException( "验证码不匹配");
        }
		//校验完,验证码失效
        sessionStrategy.removeAttribute(request, ValidateCodeController.SESSION_KEY);
    }
}

加入到springSecurity的配置中:
将自定义的图形验证码过滤器置于过滤器链UsernamePasswordAuthenticationFilter之前。

@Configuration
@EnableWebSecurity
public class BrowserSecurityConfig extends WebSecurityConfigurerAdapter {
//...
    @Override
    protected void configure(HttpSecurity http) throws Exception {
    //...
		http.addFilterBefore(imageCodeFilter, UsernamePasswordAuthenticationFilter.class);
	//...
	}
}

<7>完成效果

在这里插入图片描述
登录页面上,若未输入,或输入错图形验证码,会返回错误信息。

(二)模拟短信登录及图形验证码优化重构

<1>短信验证码对象

由于短信验证码和图形验证码都有验证码和过期时间的属性,因此设计为图形验证码继承短信验证码。

//短信验证码
public class ValidateCode{
	private String code;//验证码
    private LocalDateTime expireTime;//过期时间
    //构造函数(验证码,过期秒数)
    public ValidateCode(String code, long lengthOfLiveTime) {
    	this.code = code;
        this.expireTime = LocalDateTime.now().plusSeconds(lengthOfLiveTime);
    }
    //构造函数(验证码,过期时间)
    public ValidateCode(String code, LocalDateTime expireTime){
    	this.code = code;
        this.expireTime = expireTime;
    }
    //是否过期
    public boolean isExpired(){
        return this.getExpireTime().isBefore(LocalDateTime.now());
    }
    //getter and setter...
}
//图形验证码
public class ImageCode extends ValidateCode{
    private BufferedImage image;//验证码图片

    public ImageCode(BufferedImage image, String code, long lengthOfLiveTime) {
        super(code, lengthOfLiveTime);
        this.image = image;
    }

    public ImageCode(BufferedImage image, String code, LocalDateTime expireTime) {
        super(code, expireTime);
        this.image = image;
    }

    public BufferedImage getImage() {
        return image;
    }

    public void setImage(BufferedImage image) {
        this.image = image;
    }
}

<2>短信验证码生成器,短信验证码发送器

@Component("smsValidateCodeGenerator")
public class SmsCodeGenerator implements ValidateCodeGenerator {
    @Override
    public ValidateCode generate(ServletWebRequest request) {
    	//随机6位数
        String code = RandomStringUtils.randomNumeric(6);
        return new ValidateCode(code, securityProperties.getValidate().getSms().getLengthOfLiveTime());
    }
}
public interface SmsCodeSender {
    void send(String mobile, String code);
}
public class DefaultSmsCodeSender implements SmsCodeSender {
    @Override
    public void send(String mobile, String code) {
        System.out.println("模拟向手机号:"+mobile+"发送短信验证码:"+code);
    }
}

<3>可配置类

@Configuration
public class ValidateCodeBeanConfig {
    @Bean//相当于在ImageCodeGenerator上添加@Component注解
    @ConditionalOnMissingBean(name = "imageCodeGenerator")//若读取到名为imageCodeGenerator的对象则直接返回,就不加载下面的bean生成方法了
    public ValidateCodeGenerator imageCodeGenerator(){
        return new ImageCodeGenerator();
    }
    @Bean
    @ConditionalOnMissingBean(SmsCodeSender.class)//找到类型为SmsCodeSender的类,就不加载下面的bean生成方法了
    public SmsCodeSender smsCodeSender(){
        return new DefaultSmsCodeSender();
    }
}

<4>控制器

@RestController
public class ValidateCodeController {
	public static String SESSION_KEY = "SESSION_IMAGE_CODE_KEY";
    private SessionStrategy sessionStrategy = new HttpSessionSessionStrategy();
    @Autowired
    private ValidateCodeGenerator imageGenerator;
    @Autowired
    private ValidateCodeGenerator smsGenerator;
    @Autowired
    private SmsCodeSender smsCodeSender;
    @GetMapping("/code/image")
    public void getImageCode(HttpServletRequest request, HttpServletResponse response) throws IOException {
        ImageCode imageCode = (ImageCode) imageGenerator.generate(new ServletWebRequest(request));
        //将验证码存入session
        sessionStrategy.setAttribute(new ServletWebRequest(request), SESSION_KEY, imageCode);
        ImageIO.write(imageCode.getImage(), "JPEG", response.getOutputStream());
    }
	@GetMapping("/code/sms")
    public void getSmsCode(HttpServletRequest request, HttpServletResponse response) throws IOException {
        ValidateCode smsCode = smsGenerator.generate(new ServletWebRequest(request));
        sessionStrategy.setAttribute(new ServletWebRequest(request), "SESSION_SMS_CODE_KEY", smsCode);
        String mobile = ServletRequestUtils.getStringParameter(request, "mobile");
        smsCodeSender.send(mobile ,smsCode.getCode());
    }
}

<5>HTML页面

<p>手机号登陆界面</p>
<form action="/accessIn/mobile" method="post">
    <p>
        <label>手机号:</label> <input type="text" name="mobile" id="mobile" value="18888888888">
    </p>
    <p>
        <label>手机验证码:</label> <input type="text" name="smsCode" id="smsCode">
        <a href="/code/sms?mobile=18888888888">发送验证码</a>
    </p>

    <input type="submit" value="Login">
</form>

<6>仿造UsernamePasswordAuthenticationFilter写SmsAuthenticationFilter

不同于图形验证码过滤器,短信验证码过滤器不走用户名密码校验的逻辑,因此与图形验证码过滤器的写法差别很大。
在这里插入图片描述
新增短信凭证类型:

public class SmsAuthenticationToken extends AbstractAuthenticationToken {
    private static final long serialVersionUID = 420L;
    private final Object principal;

    public SmsAuthenticationToken(String mobile) {
        super((Collection)null);
        this.principal = mobile;
        this.setAuthenticated(false);
    }

    public SmsAuthenticationToken(Object principal, Collection<? extends GrantedAuthority> authorities) {
        super(authorities);
        this.principal = principal;
        super.setAuthenticated(true);
    }

    @Override
    public Object getCredentials() {//短信验证码登录不需要密码,因此返回null
        return null;
    }

    public Object getPrincipal() {
        return this.principal;
    }

    public void setAuthenticated(boolean isAuthenticated) throws IllegalArgumentException {
        if (isAuthenticated) {
            throw new IllegalArgumentException("Cannot set this token to trusted - use constructor which takes a GrantedAuthority list instead");
        } else {
            super.setAuthenticated(false);
        }
    }

    public void eraseCredentials() {
        super.eraseCredentials();
    }
}

仿造UsernamePasswordAuthenticationFilter编写SmsAuthenticationFilter:

public class SmsAuthenticationFilter extends AbstractAuthenticationProcessingFilter {
    public static final String SPRING_SECURITY_FORM_SMS_KEY = "mobile";
    private String usernameParameter = "mobile";
    private boolean postOnly = true;

    public SmsAuthenticationFilter() {
        super(new AntPathRequestMatcher("/accessIn/mobile", "POST"));
    }

    public Authentication attemptAuthentication(HttpServletRequest request, HttpServletResponse response) throws AuthenticationException {
        if (this.postOnly && !request.getMethod().equals("POST")) {
            throw new AuthenticationServiceException("Authentication method not supported: " + request.getMethod());
        } else {
            String mobile = this.obtainMobile(request);
            if (mobile == null) {
                mobile = "";
            }

            mobile = mobile.trim();
            SmsAuthenticationToken authRequest = new SmsAuthenticationToken(mobile);
            this.setDetails(request, authRequest);
            return this.getAuthenticationManager().authenticate(authRequest);
        }
    }

    private String obtainMobile(HttpServletRequest request) {
        return request.getParameter("mobile");
    }


    protected void setDetails(HttpServletRequest request, SmsAuthenticationToken authRequest) {
        authRequest.setDetails(this.authenticationDetailsSource.buildDetails(request));
    }

    public void setUsernameParameter(String usernameParameter) {
        Assert.hasText(usernameParameter, "Username parameter must not be empty or null");
        this.usernameParameter = usernameParameter;
    }

    public void setPostOnly(boolean postOnly) {
        this.postOnly = postOnly;
    }

    public final String getUsernameParameter() {
        return this.usernameParameter;
    }
}

SmsAuthenticationProvider :

public class SmsAuthenticationProvider implements AuthenticationProvider {//在注入前使用,因此不使用自动注入
    private UserDetailsService userDetailsService;
    @Override
    public Authentication authenticate(Authentication authentication) throws AuthenticationException {

        UserDetails userDetails = userDetailsService.loadUserByUsername(authentication.getPrincipal().toString());
        if(userDetails == null){
            throw new InternalAuthenticationServiceException("无法获取用户信息!");
        }
        SmsAuthenticationToken smsAuthenticationToken = new SmsAuthenticationToken(userDetails, userDetails.getAuthorities());
        smsAuthenticationToken.setDetails(userDetails);
        return smsAuthenticationToken;
    }
	//根据AuthenticationToken类型判定是否是该Provider可处理的类型
    @Override
    public boolean supports(Class<?> aClass) {
        return aClass.isAssignableFrom(SmsAuthenticationToken.class);
    }

    public UserDetailsService getUserDetailsService() {
        return userDetailsService;
    }

    public void setUserDetailsService(UserDetailsService userDetailsService) {
        this.userDetailsService = userDetailsService;
    }
}

SpringSecrity子配置:

@Component
public class SmsAuthenticationSecurityConfig extends SecurityConfigurerAdapter<DefaultSecurityFilterChain, HttpSecurity> {
    @Autowired
    private AuthenticationSuccessHandler authenticationSuccessHandler;
    @Autowired
    private AuthenticationFailureHandler authenticationfailureHandler;
    @Autowired
    private UserDetailsService userDetailsService;
    @Override
    public void configure(HttpSecurity http) throws Exception {
        SmsAuthenticationFilter smsAuthenticationFilter = new SmsAuthenticationFilter();
        //getSharedObject这个对象里面存放着顶级的运行时对象,可用于获取所有的运行时信息。
        smsAuthenticationFilter.setAuthenticationManager(http.getSharedObject(AuthenticationManager.class));
        smsAuthenticationFilter.setAuthenticationSuccessHandler(authenticationSuccessHandler);
        smsAuthenticationFilter.setAuthenticationFailureHandler(authenticationfailureHandler);

        SmsAuthenticationProvider smsAuthenticationProvider = new SmsAuthenticationProvider();
        smsAuthenticationProvider.setUserDetailsService(userDetailsService);
        //注册自定义的AuthenticationProvider
        http.authenticationProvider(smsAuthenticationProvider)
                .addFilterAfter(smsAuthenticationFilter, UsernamePasswordAuthenticationFilter.class);
    }
}
/**配置到主配置中**/
//...
 http.apply(smsAuthenticationSecurityConfig)
                .and()
//...

(三)RememberMe

在开发中,有时会有这种需求:已经登录成功的用户在一段时间内不需要再校验用户民密码,直接有访问权限。这时就需要用RememberMe功能。

1、如何使用?

所需的依赖

这里省略SpringSecurity的相关依赖以及数据库驱动的相关依赖。
SpringBoot对jdbc的支持:

<dependency>
  <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-jdbc</artifactId>
</dependency>
Html(登录界面)

增加记住我的CheckBox,属性 name=“remember-me” 这是固定的。后台会自动读取该属性,并运用。

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
    <body>
    <p>登陆界面一</p>
        <form action="/accessIn" method="post">
            <p>
                <label>Username</label> <input type="text" name="username" id="username" >
            </p>
            <p>
                <label>Password</label> <input type="password" name="password" id="password">
            </p>
            <p>
                <b>图形验证码:</b>
                <b>
                    <input type="text" name="imageCode">
                    <img src="/imageCode?width=80">
                </b>
            </p>
            <p><input type="checkbox" name="remember-me" value="true">记住我</p>
            <input type="submit" value="Login">
        </form>
    </body>
</html>
SpringSecurity配置

加载RememberMe相关的数据源,以及数据传输层。

@Configuration
@EnableWebSecurity
public class BrowserSecurityConfig extends WebSecurityConfigurerAdapter {
    @Autowired
    private DataSource dataSource;
    @Autowired
    private MyUserDetailsService myUserDetailsService;
    @Bean
    public PersistentTokenRepository persistentTokenRepository(){
        JdbcTokenRepositoryImpl jdbcTokenRepository = new JdbcTokenRepositoryImpl();
        jdbcTokenRepository.setDataSource(dataSource);
        //该属性设置为true会在启动时自动建RememberMe相关的表(persistent_logins),若表已存在会报错
        jdbcTokenRepository.setCreateTableOnStartup(true);
        return jdbcTokenRepository;
    }
    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http.formLogin()//表单登陆
             //.loginPage("/login.html")
               .loginPage("/authentication/login")
               .loginProcessingUrl("/accessIn/form")//该项告诉springSecurity发送登陆校验请求的URL
                                               // 若不配置该项,formLogin对应的过滤器只认包含/login的登陆请求
       .and()
           .rememberMe()
               .tokenRepository(persistentTokenRepository())
               .tokenValiditySeconds(3600)//token 3600秒后失效
               .userDetailsService(myUserDetailsService)//指定userDetailsService(加载登录用户信息)
       .and()
           .authorizeRequests()//对请求授权
               .antMatchers("/login").permitAll()
               .anyRequest()
               .authenticated()//进行身份认证
       .and()
           .csrf().disable();
    }
}

2、开发中问题记录

问题:
jdbcTokenRepository没有setDataSource方法。

@Bean
    public PersistentTokenRepository persistentTokenRepository(){
        JdbcTokenRepositoryImpl jdbcTokenRepository = new JdbcTokenRepositoryImpl();
        jdbcTokenRepository.setDataSource(dataSource);//没有添加jdbc依赖导致该方法不存在
        //该属性设置为true会在启动时自动建RememberMe相关的表(persistent_logins),若表已存在会报错
        jdbcTokenRepository.setCreateTableOnStartup(true);
        return jdbcTokenRepository;
    }

解决方法:
添加SpringBoot对jdbc的支持依赖:

<dependency>
  <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-jdbc</artifactId>
</dependency>

注:

具体重置方法,源码解析可参考 Spring Security渐入佳境(三)[附] – 配置化重构,验证码逻辑优化重构,RememberMe源码解析

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

Funnee

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值