Springboot+SpringSecurity+jwt++Swagger2 验证码验证

 

第一步:加入工具类包

 <!--加入验证码工具包-->
 <dependency>
     <groupId>cn.hutool</groupId>
      <artifactId>hutool-all</artifactId>
     <version>4.5.11</version>
 </dependency>

第二步 :加入图片验证工具类

package com.**.code;

import javax.imageio.ImageIO;
import java.awt.*;
import java.awt.geom.AffineTransform;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.io.OutputStream;
import java.util.Arrays;
import java.util.Random;

public class CodeUtils {

    //使用到Algerian字体,系统里没有的话需要安装字体,字体只显示大写,去掉了1,0,i,o几个容易混淆的字符
    public static final String VERIFY_CODES = "23456789ABCDEFGHJKLMNPQRSTUVWXYZ";
    private static Random random = new Random();


    /**
     * 使用系统默认字符源生成验证码
     * @param verifySize    验证码长度
     * @return
     */
    public static String generateVerifyCode(int verifySize){
        return generateVerifyCode(verifySize, VERIFY_CODES);
    }
    /**
     * 使用指定源生成验证码
     * @param verifySize    验证码长度
     * @param sources   验证码字符源
     * @return
     */
    public static String generateVerifyCode(int verifySize, String sources){
        if(sources == null || sources.length() == 0){
            sources = VERIFY_CODES;
        }
        int codesLen = sources.length();
        Random rand = new Random(System.currentTimeMillis());
        StringBuilder verifyCode = new StringBuilder(verifySize);
        for(int i = 0; i < verifySize; i++){
            verifyCode.append(sources.charAt(rand.nextInt(codesLen-1)));
        }
        return verifyCode.toString();
    }

    /**
     * 输出指定验证码图片流
     * @param w
     * @param h
     * @param os
     * @param code
     * @throws IOException
     */
    public static void outputImage(int w, int h, OutputStream os, String code) throws IOException {
        int verifySize = code.length();
        BufferedImage image = new BufferedImage(w, h, BufferedImage.TYPE_INT_RGB);
        Random rand = new Random();
        Graphics2D g2 = image.createGraphics();
        g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING,RenderingHints.VALUE_ANTIALIAS_ON);
        Color[] colors = new Color[5];
        Color[] colorSpaces = new Color[] { Color.WHITE, Color.CYAN,
                Color.GRAY, Color.LIGHT_GRAY, Color.MAGENTA, Color.ORANGE,
                Color.PINK, Color.YELLOW };
        float[] fractions = new float[colors.length];
        for(int i = 0; i < colors.length; i++){
            colors[i] = colorSpaces[rand.nextInt(colorSpaces.length)];
            fractions[i] = rand.nextFloat();
        }
        Arrays.sort(fractions);

        g2.setColor(Color.GRAY);// 设置边框色
        g2.fillRect(0, 0, w, h);

        Color c = getRandColor(200, 250);
        g2.setColor(c);// 设置背景色
        g2.fillRect(0, 2, w, h-4);

        //绘制干扰线
        Random random = new Random();
        g2.setColor(getRandColor(160, 200));// 设置线条的颜色
        for (int i = 0; i < 20; i++) {
            int x = random.nextInt(w - 1);
            int y = random.nextInt(h - 1);
            int xl = random.nextInt(6) + 1;
            int yl = random.nextInt(12) + 1;
            g2.drawLine(x, y, x + xl + 40, y + yl + 20);
        }

        // 添加噪点
        float yawpRate = 0.05f;// 噪声率
        int area = (int) (yawpRate * w * h);
        for (int i = 0; i < area; i++) {
            int x = random.nextInt(w);
            int y = random.nextInt(h);
            int rgb = getRandomIntColor();
            image.setRGB(x, y, rgb);
        }

        shear(g2, w, h, c);// 使图片扭曲

        g2.setColor(getRandColor(100, 160));
        int fontSize = h-4;
        Font font = new Font("Algerian", Font.ITALIC, fontSize);
        g2.setFont(font);
        char[] chars = code.toCharArray();
        for(int i = 0; i < verifySize; i++){
            AffineTransform affine = new AffineTransform();
            affine.setToRotation(Math.PI / 4 * rand.nextDouble() * (rand.nextBoolean() ? 1 : -1), (w / verifySize) * i + fontSize/2, h/2);
            g2.setTransform(affine);
            g2.drawChars(chars, i, 1, ((w-10) / verifySize) * i + 5, h/2 + fontSize/2 - 10);
        }

        g2.dispose();
        ImageIO.write(image, "jpg", os);
    }

    private static Color getRandColor(int fc, int bc) {
        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);
    }

    private static int getRandomIntColor() {
        int[] rgb = getRandomRgb();
        int color = 0;
        for (int c : rgb) {
            color = color << 8;
            color = color | c;
        }
        return color;
    }

    private static int[] getRandomRgb() {
        int[] rgb = new int[3];
        for (int i = 0; i < 3; i++) {
            rgb[i] = random.nextInt(255);
        }
        return rgb;
    }

    private static void shear(Graphics g, int w1, int h1, Color color) {
        shearX(g, w1, h1, color);
        shearY(g, w1, h1, color);
    }

    private static void shearX(Graphics g, int w1, int h1, Color color) {

        int period = random.nextInt(2);

        boolean borderGap = true;
        int frames = 1;
        int phase = random.nextInt(2);

        for (int i = 0; i < h1; i++) {
            double d = (double) (period >> 1)
                    * Math.sin((double) i / (double) period
                    + (6.2831853071795862D * (double) phase)
                    / (double) frames);
            g.copyArea(0, i, w1, 1, (int) d, 0);
            if (borderGap) {
                g.setColor(color);
                g.drawLine((int) d, i, 0, i);
                g.drawLine((int) d + w1, i, w1, i);
            }
        }

    }

    private static void shearY(Graphics g, int w1, int h1, Color color) {

        int period = random.nextInt(40) + 10; // 50;
        boolean borderGap = true;
        int frames = 20;
        int phase = 7;
        for (int i = 0; i < w1; i++) {
            double d = (double) (period >> 1)
                    * Math.sin((double) i / (double) period
                    + (6.2831853071795862D * (double) phase)
                    / (double) frames);
            g.copyArea(i, 0, 1, h1, 0, (int) d);
            if (borderGap) {
                g.setColor(color);
                g.drawLine(i, (int) d, i, 0);
                g.drawLine(i, (int) d + h1, i, h1);
            }
        }
    }
}

第三步:加入类


import lombok.AllArgsConstructor;
import lombok.Data;

/**
 * 验证的id和图片的属性
 * */
@Data
@AllArgsConstructor
public class ImgResult {
    private String img;
    private String uuid;


}

第四步:加入验证码controller层


import com.cxht.common.code.CodeUtils;
import com.cxht.common.code.ImgResult;
import com.sun.org.apache.xerces.internal.impl.dv.util.Base64;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.util.UUID;
import java.util.concurrent.TimeUnit;

@Controller
@RequestMapping("/code")
@Api(value = "验证码", tags = {"验证码"})
public class CodeController {

    // 登录验证码过期时间:单位 分钟
    @Value("${loginCode.expiration}")
    private Long expiration;

    @Value("${loginCode.prefix}")
    private String prefix;

    @Autowired
    private StringRedisTemplate redisTemplate;


    /**
     * 获取验证码
     */
    @GetMapping("/vCode")
    @ResponseBody
    @ApiOperation(value="获取验证码")
    public ImgResult getCode() throws IOException {

        // 生成随机字串
        String verifyCode = CodeUtils.generateVerifyCode(4);
        String uuid = UUID.randomUUID().toString();
        // 存入redis
        redisTemplate.opsForValue().set(prefix + uuid,verifyCode, expiration, TimeUnit.MINUTES);
        // 生成图片
        int w = 111, h = 36;
        ByteArrayOutputStream stream = new ByteArrayOutputStream();
        CodeUtils.outputImage(w, h, stream, verifyCode);
        try {
            return new ImgResult(Base64.encode(stream.toByteArray()),uuid);
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        } finally {
            stream.close();
        }
    }

}

第五步:我们这里做些环境的配置

#加入redis 配置
redis:
    database: 1
    host: localhost
    port: 6379
    password:
    jedis:
      pool:
        max-active: 8
        max-idle: 8
        max-wait: -1
        min-idle: 0

#加入验证码属性
loginCode:
  expiration: 20 #登录验证码过期时间,单位 分钟
  prefix: login_code #验证码redis的key值前缀



第六步:我们给个页面由于项目中用的是前后台分离,这里的login,htnl 页面只是让大家看下效果!!!

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>登陆</title>
    <!--引入css-->
    <link rel="stylesheet" href="/assets/common/layui/css/layui.css">
    <link rel="stylesheet" href="/assets/common/module/admin.css">
    <link id="layuicss-layer" rel="stylesheet" href="/assets/common/layui/css/modules/layer/default/layer.css?v=3.1.1" media="all">
    <!--引入js配置文件-->
    <script type="text/javascript" src="/assets/common/layui/layui.js"></script>
    <script type="text/javascript" src="/assets/common/js/common.js"></script>
    <script type="text/javascript" src="/assets/common/plugins/jquery/jquery-3.2.1.min.js"></script>
</head>
<body>
<h1>登陆</h1>
<form method="post" action="/login">
    <div>
        用户名:<input type="text" name="username">
    </div>
    <div>
        密 码:<input type="password" name="password">
    </div>
    <div>
        验证码:<input type="text" class="form-control" name="verifyCode" required="required" placeholder="验证码">
        <input id="uuid" type="hidden" name="uuid" />
        <img  id="vCode" title="看不清,请点我" onclick="getVerifyCode()" onmouseover="mouseover(this)" />
    </div>
    <div>
        <label><input type="checkbox" name="remember-me"/>自动登录</label>
    </div>
    <div>
        <button type="submit">立即登陆</button>
    </div>
</form>

<script>
    $(function() {
        getVerifyCode();
    })

    function getVerifyCode() {
        //var url = "/vCode?" + Math.random();
        var url ="/code/vCode"
        $.ajax({
            //请求方式
            type : "GET",
            //请求的媒体类型
            contentType: "application/json;charset=UTF-8",
            //请求地址
            url : url,
            //请求成功
            success : function(result) {
                console.log(result);
                $("#uuid").val(result.uuid);
                $("#vCode").attr("src","data:image/png;base64," + result.img);
            },
            //请求失败,包含具体的错误信息
            error : function(e){
                console.log(e.status);
                console.log(e.responseText);
            }
        });
    }

    function mouseover(obj) {
        obj.style.cursor = "pointer";
    }
</script>

</body>
</html>

来,我们看看效果!!!!!

 

 

好了 ,到这我们验证码的生成就结束了 。。。。。接下来我们和SpringSecurity整合了。。。。。。

----------------------------------------------------------------------- 整合----------------------------------------------------- 

 

第七步:加入过滤器fFile,CodeFilter.java

package com.cxht.core.code;

import com.cxht.core.constant.Constant;
import org.apache.commons.lang3.StringUtils;
import org.springframework.boot.configurationprocessor.json.JSONException;
import org.springframework.boot.configurationprocessor.json.JSONObject;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.security.web.WebAttributes;
import org.springframework.util.AntPathMatcher;
import org.springframework.util.PathMatcher;
import org.springframework.web.filter.OncePerRequestFilter;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

public class CodeFilter extends OncePerRequestFilter {

    private static final PathMatcher pathMatcher = new AntPathMatcher();

    /**属性 */
    private StringRedisTemplate stringRedisTemplate;
    /**属性 */
    private String prefix;

    public CodeFilter(StringRedisTemplate stringRedisTemplate, String prefix) {
        this.stringRedisTemplate = stringRedisTemplate;
        this.prefix = prefix;
    }


    @Override
    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws ServletException, IOException {
        response.setCharacterEncoding("utf-8");
        response.setContentType("application/json; charset=utf-8");
        // 拦截 /login的POST请求
        if(isProtectedUrl(request)) {
            String uuid = request.getParameter("uuid"); //图片验证码的 key
            String vCode = request.getParameter("code");// 图片验证码的 value
            if(!validateVerify(request, uuid, vCode)) {
                //手动设置异常
                // request.getSession().setAttribute("SPRING_SECURITY_LAST_EXCEPTION",new VerifyCodeException("验证码输入错误"));
                JSONObject o = new JSONObject();
                try {
                    o.put("msg","验证码已失效");
                } catch (JSONException e) {e.printStackTrace();}
                response.getWriter().write(o.toString());
                // 转发到错误Url
                // request.getRequestDispatcher("/login/error").forward(request,response);
            } else {
                filterChain.doFilter(request,response);
            }
        } else {
            filterChain.doFilter(request,response);
        }
    }


    /**
     * 验证验证码合法性
     * @param uuid  验证key
     * @param vCode 验证值
     * @return
     */
    private boolean validateVerify(HttpServletRequest request, String uuid, String vCode) {
        // 查询验证码
        String code = stringRedisTemplate.opsForValue().get(prefix + uuid);
        // 清除验证码
        stringRedisTemplate.delete(prefix + uuid);
        if (StringUtils.isBlank(code)) {
            return false;
        }
        if (StringUtils.isBlank(vCode) || !vCode.equalsIgnoreCase(code)) {
            return false;
        }
        logger.info("验证码:" + code + "用户输入:" + vCode);
        return true;
    }

    /** 如果不加入它,就会直接走用户密码和姓名的验证 --拦截 /login的POST请求*/
    private boolean isProtectedUrl(HttpServletRequest request) {
        return "POST".equals(request.getMethod()) && pathMatcher.match(Constant.LOGIN_SIGN, request.getServletPath());
    }

}

第八步:将我们的CodeFile 过滤器加入到我们框架SpringSecurity的过滤链当中去(这里的配置类配置有点乱,不要在意细节,只要找到我们加入的验证码的入口就行。。。。)



import com.etoak.util.code.VerifyFilter;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.method.configuration.EnableGlobalMethodSecurity;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter;


@EnableWebSecurity
@Configuration
@EnableGlobalMethodSecurity(prePostEnabled = true)
public class SecurityConfig extends WebSecurityConfigurerAdapter {

      @Autowired
      //因为UserDetailsService的实现类实在太多啦,这里设置一下我们要注入的实现类
      private UserDetailsService userDetailsService;

      // 配置文件验证码的时长
      @Value("${loginCode.prefix}")
      private String prefix;

      @Autowired
      private StringRedisTemplate redisTemplate;

      @Bean//密码解密方式
      public BCryptPasswordEncoder bCryptPasswordEncoder(){
         return new BCryptPasswordEncoder();
      }

     @Override
     protected void configure(AuthenticationManagerBuilder auth) throws Exception {
        auth.userDetailsService(userDetailsService).passwordEncoder(bCryptPasswordEncoder());
    }


     @Override
     protected void configure(HttpSecurity http) throws Exception {
         http.cors().and().csrf().disable()
                  //配置swagger2 的文档文件---》
                  //swagger2不需要验证,就能访问的url
                  .authorizeRequests()
                  .antMatchers("/templates/**").permitAll()
                  .antMatchers("/list","/user/add","/user/receive","/code/vCode").permitAll()
                  .antMatchers("/v2/api-docs", "/configuration/ui", "/swagger-resources", "/configuration/security", "/swagger-ui.html", "/webjars/**","/swagger-resources/configuration/ui","/swagge‌​r-ui.html").permitAll()
                   //RBAC动态url认证
                  .anyRequest().access("@rbacauthorityservice.hasPermission(request,authentication)")
                  .and()
                   //加入验证码过滤器 addFilterBefore();
                  .addFilterBefore(new VerifyFilter(redisTemplate,prefix), UsernamePasswordAuthenticationFilter.class)
                  .addFilter(new JWTAuthenticationFilter(authenticationManager()))
                  .addFilter(new JWTAuthorizationFilter(authenticationManager(),userDetailsService()));
                  // 不需要session,如果不禁掉session会存在只要登录就是不需要token就去访问有权限的路径。。。。。。。哈哈
                 // .sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS);
         /**权限认证拦截器*/
        // http.addFilterBefore(myFilterSecurityInterceptor, FilterSecurityInterceptor.class);
    }

加入这么多看的人也烦.....................

那么我们只要找到我们过滤器链加入我们的过滤器就可以,首先我们找到addFile() 这个方法之前加入我们的addFileBefore() :这个方法(根据字面的意思就是在addFile()之前执行过滤)。。。。。其他和你没有任何的关系,

到这我们就结束了,文章如果有不对的地方请谅解,感谢!!!!!!

 

参考资料:https://www.jianshu.com/p/fe80b335b868

 

 

 

 

 

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值