阿里云滑块验证 vue+java Springboot使用案例

12 篇文章 0 订阅
11 篇文章 0 订阅


网上搜了大堆没用。没办法 记录下 帮助有缘人。

阿里云接口文档:

前端:https://help.aliyun.com/document_detail/121898.html
后端java:https://help.aliyun.com/document_detail/122003.html

废话不多说 直接上

index.html 里面引入案例的script

<!DOCTYPE html>
<html>
  <head>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width,initial-scale=1.0">
    <title>aliyunhuakuai</title>
  </head>
  <body>
    <div id="app"></div>
    <!-- built files will be auto injected -->
    <script type="text/javascript" charset="utf-8" src="//g.alicdn.com/sd/nch5/index.js?t=2015052012"></script>
  </body>
</html>

创建vue组件(样式可注释)

<template>
  <!-- <div id="__nc" style="margin:2.53vw auto;">
        <div id="nc"></div>
  </div>-->
  <div
    id="__nc"
    style="margin-left:auto;margin-right:auto;width:80%;height:100px;padding-top:100px;"
  >
    <div id="nc"></div>
  </div>
</template>
<script>
// import { Indicator, Toast } from "mint-ui";
import axios from "axios";
export default {
  name: "aliVerify",
  data() {
    return {
      nc: null
    };
  },

  mounted() {
    // var that = this
    var nc_token = [
      "FFFF0N0N000000001B6A",
      new Date().getTime(),
      Math.random()
    ].join(":");
    var scene = "nc_activity_h5";
    var nc = NoCaptcha.init({
      renderTo: "#nc",
      appkey: "FFFF0N0N000000001B6A",
      scene: scene,
      token: nc_token,
      trans: { key1: "code200" },
      elementID: ["usernameID"],
      is_Opt: 0,
      language: "cn",
      timeout: 10000,
      retryTimes: 5,
      errorTimes: 5,
      inline: false,
      apimap: {
        // 'analyze': '//a.com/nocaptcha/analyze.jsonp',
        // 'uab_Url': '//aeu.alicdn.com/js/uac/909.js',
      },
      bannerHidden: false,
      initHidden: false,
      callback: function(data) {
        console.log(data);
        var params = {
          sign: data.sig,
          sessionId: data.csessionid,
          token: nc_token,
          scene: scene
        };
        axios.post("/test/test1", params).then(response => {
          console.log(response);
        });
        // verify(data.sig,nc_token,scene,data.csessionid);
        // console.log(nc_token);
        // console.log(scene);
        // console.log(data);
        // setTimeout(() => {
        // nc.reset();//重置初始化状态
        // }, 1500);
      },
      error: function(e) {
        // Toast("系统繁忙,请稍后再试")
        console.log("error======");
        console.log(e);
        nc.reset();
      }
    });
    NoCaptcha.setEnabled(true);
    nc.reset(); //请务必确保这里调用一次reset()方法

    NoCaptcha.upLang("cn", {
      LOADING: "加载中...", //加载
      SLIDER_LABEL: "请向右滑动完成签到", //等待滑动
      CHECK_Y: "验证通过", //通过
      ERROR_TITLE: "非常抱歉,这出错了...", //拦截
      CHECK_N: "验证未通过", //准备唤醒二次验证
      OVERLAY_INFORM: "经检测你当前操作环境存在风险,请输入验证码", //二次验证
      TIPS_TITLE: "验证码错误,请重新输入" //验证码输错时的提示
    });

    this.nc = nc;
  },

  methods: {
    refreshNC() {
      this.nc.reset();
    }
  }
};
</script>
<style>
/* 滑动条高度、边框、背景色等 */
._nc .stage1 .slider {
  height: 52px;
  border-radius: 26px;
  box-shadow: 0 0 3px #999;
  background-color: #ddd;
}

/* 滑动条 */
._nc .stage1 .track div {
  border-radius: 26px;
  color: #fff;
}

/* 滑动条背景色-正常 */
._nc .stage1 .bg-green {
  background-color: #78c430;
}

/* 滑动条背景色-失败 */
._nc .stage1 .bg-red {
  background-color: #ff5500;
}

/* 各个状态的icon */
/* 等待滑动:"icon iconfont icon-slide-arrow"
验证出错:"icon no iconfont icon-close"
验证通过:"icon yes iconfont icon-ok" */

._nc .stage1 .button {
  border-radius: 26px;
}

/* 刷新链接 */
._nc .stage3 .menu.refresh {
  left: 50%;
  transform: translateX(-50%);
}

._nc .stage3 .menu.feedback {
  display: none;
}

._nc .stage3 .menu.nc-sep {
  display: none;
}

/* ._nc .stage3 .title{
    display: none;
} */
</style>

配置路由

import Vue from 'vue'
import Router from 'vue-router'
import HelloWorld from '@/components/HelloWorld'
import test from '@/pages/test'//改成自己的组件

Vue.use(Router)

export default new Router({
  routes: [
    {
      path: '/',
      name: 'HelloWorld',
      component: HelloWorld
    },
    {
      path: '/test',//改成自己的路由
      name: 'test',
      component: test//改成自己的组件
    },
  ]
})

前端就结束了!

后端JAVA 代码(SDK包 请官网下载 或者MAVEN)

maven POM文件

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>
    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>2.3.0.RELEASE</version>
        <relativePath/> <!-- lookup parent from repository -->
    </parent>
    <groupId>com.lyl</groupId>
    <artifactId>alihk</artifactId>
    <version>0.0.1-SNAPSHOT</version>
    <name>alihk</name>
    <description>Demo project for Spring Boot</description>

    <properties>
        <java.version>1.8</java.version>
    </properties>

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

        <dependency>
            <groupId>org.projectlombok</groupId>
            <artifactId>lombok</artifactId>
            <optional>true</optional>
        </dependency>
        <dependency>
            <groupId>org.apache.commons</groupId>
            <artifactId>commons-lang3</artifactId>
        </dependency>
        <dependency>
            <groupId>com.alibaba</groupId>
            <artifactId>fastjson</artifactId>
            <version>1.2.16</version>
        </dependency>
        <dependency>
			<groupId>com.aliyun</groupId>
			<artifactId>aliyun-java-sdk-afs</artifactId>
			<version>1.0.0</version>
		</dependency>
		<dependency>
			<groupId>com.aliyun</groupId>
			<artifactId>aliyun-java-sdk-core</artifactId>
			<version>3.0.6</version>
		</dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
            <exclusions>
                <exclusion>
                    <groupId>org.junit.vintage</groupId>
                    <artifactId>junit-vintage-engine</artifactId>
                </exclusion>
            </exclusions>
        </dependency>
    </dependencies>

    <build>
        <plugins>
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
            </plugin>
        </plugins>
    </build>

</project>

Controller

package com.lyl.alihk.controller;

import com.lyl.alihk.service.SildeVerifyService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;

@RestController
@RequestMapping("/test")
public class AliHkController {
    @Autowired
    SildeVerifyService sildeVerifyService;

    @PostMapping("/test")
    public String isValid(HttpServletRequest httpRequest, @RequestParam String sign, @RequestParam String sessionId ,@RequestParam String token,@RequestParam String scene) {
        sildeVerifyService.isValid(httpRequest,sign,sessionId,token,scene);
        return "I";
    }
}

Service

package com.lyl.alihk.service;


import com.alibaba.fastjson.JSON;
import com.aliyuncs.DefaultAcsClient;
import com.aliyuncs.IAcsClient;
import com.aliyuncs.afs.model.v20180112.AuthenticateSigRequest;
import com.aliyuncs.afs.model.v20180112.AuthenticateSigResponse;
import com.aliyuncs.exceptions.ClientException;
import com.aliyuncs.profile.DefaultProfile;
import com.aliyuncs.profile.IClientProfile;
import com.lyl.alihk.utils.IpUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import sun.net.util.IPAddressUtil;

import javax.servlet.http.HttpServletRequest;

@Slf4j
@Service
public class SildeVerifyService {

    @Value("${aliyun.regionId}")
    private String RegionID;
    @Value("${aliyun.accessKeyId}")
    private String AccessKeyId;
    @Value("${aliyun.accessKeySecret}")
    private String AccessKeySecret;
    @Value("${aliyun.product}")
    private String Product;
    @Value("${aliyun.domain}")
    private String Domain;



    private static IClientProfile profile;

    private IClientProfile initProfile() throws ClientException {
        // Create a new IClientProfile instance
        //IClientProfile可以复用,建议将其设置成应用程序全局唯一。
        if (null == profile) {
            synchronized (SildeVerifyService.class) {
                if (null == profile) {
                    profile = DefaultProfile.getProfile(RegionID, AccessKeyId, AccessKeySecret);
                }
            }
        }
        return profile;
    }

    //验签
    public boolean isValid(HttpServletRequest httpRequest,String sign, String sessionId ,String token,String scene) {
        try {
            IAcsClient client = new DefaultAcsClient(initProfile());
            DefaultProfile.addEndpoint(RegionID, RegionID, Product, Domain);

            AuthenticateSigRequest request = new AuthenticateSigRequest();
            request.setSessionId(sessionId);// 会话ID。必填参数,从前端获取,不可更改。
            request.setSig(sign);// 签名串。必填参数,从前端获取,不可更改。
            request.setToken(token);// 请求唯一标识。必填参数,从前端获取,不可更改。
            request.setScene(scene);// 场景标识。必填参数,从前端获取,不可更改。
            request.setAppKey("FFFF0N0N888888881B6A");// 应用类型标识。必填参数,后端填写。
            request.setRemoteIp(IpUtils.getRealIpAddress(httpRequest));// 客户端IP。必填参数,后端填写。

            log.info("阿里云滑块验签-request:"+ JSON.toJSONString(request));
            //response的code枚举:100验签通过,900验签失败
            AuthenticateSigResponse response = client.getAcsResponse(request);
            log.info("阿里云滑块验签-response:"+ JSON.toJSONString(response));

            if(response!=null && response.getCode().equals(100))
                return true;

        } catch (ClientException ce) {
            log.error("初始化IClientProfile异常",ce);
        } catch (Exception e) {
            log.error("阿里云滑块验签异常",e);
        }
        return false;
    }

}

yml文件配置

#阿里云滑块验证配置
aliyun:
  regionId: **  			#改成自己的配置
  accessKeyId: ****   		#改成自己的配置
  accessKeySecret: ****     #改成自己的配置
  product: ****      		#改成自己的配置
  domain: *****     		#改成自己的配置

结束!

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值