前言
- 开发的小程序手机号短信验证码登录这一个功能,入参只有手机号。
结局
- 盗刷、 恶意刷。
解决方案
1. nginx
只允许referer是小程序来源的请求
# 你的接口
location ^~ /api/
{
if ($http_referer !~* "^https://servicewechat.com/【你的小程序appid】/\d+/page-frame.html$") {
return 444;
}
2. 利用小程序code来进行验证
- 利用小程序code,在后端静默获取openid,根据openid结合当前时间戳,生成加密串返回给后端。
- 前端请求短信接口时需要将openid和生成的加密串传给后端。
- 后端解析加密串后,判断解密后的openid是否一致、时间戳是否有效。
加密和解密过程都在后端进行,避免微信小程序被抓包反编译后能够找到加密方法。
伪代码实现逻辑
- 前端
export default {
mounted() {
wx.login({
success: function(res) {
const {
code
} = res
if (code) {
// 后端code获取openid接口
codeToOpenid({
code
}).then(data => {
if (data) {
const {
openid, cryptoKey } = data
that.openid = data.openid
that.cryptoKey = data.cryptoKey
}
})
} else {
console.log('登录失败!' + res.errMsg)
}
}
});
},
methods: {
// 获取验证码
getCode() {
const checkPhone = /^1[3-9]\d{9}$/.test(this.phone)
if (!checkPhone) {
uni.showToast({
icon: 'none',
t