目录
一、页面需求展示
二、验证方式—按钮组件
三、手机短信验证
四、邮件验证
五、图片验证邮件验证
💟 创作不易,不妨点赞💚评论❤️收藏💙一下
一、页面需求展示
二、验证方式—按钮组件
2.1前端
<el-form-item label="验证方式">
<el-button type="primary" icon="el-icon-phone" circle @click.prevent="verModeFn(1)"></el-button>
<el-button type="success" icon="el-icon-message" circle @click.prevent="verModeFn(2)"></el-button>
<el-button type="warning" icon="el-icon-camera" circle @click.prevent="verModeFn(3)"></el-button>
</el-form-item>
<el-form-item v-if="verMode == 1" label="手机号" prop="telephone">
</el-form-item>
<el-form-item v-if="verMode == 1" label="短信验证">
</el-form-item>
<el-form-item v-if="verMode == 2" label="邮箱" prop="email">
</el-form-item>
<el-form-item v-if="verMode == 2" label="邮件验证">
</el-form-item>
<el-form-item v-if="verMode == 3" label="图片验证">
</el-form-item>
<script>
export default {
data() {
return {
verMode : '3' , //验证方式
}
},
methods:{
//验证方式点击方法
verModeFn(vo){
this.verMode = vo
},
}
</script>
三、手机短信验证
3.1 前端
<el-form-item v-if="verMode == 1" label="手机号" prop="telephone">
<el-row>
<el-col :span="13">
<el-input v-model="user.telephone"></el-input>
</el-col>
<el-col :span="11">
<el-button type="success" style="margin-left: 5px;padding: 10px 6px"
@click.prevent="sendSmsCodeFn"
:disabled="btnDisabled"
>短信发送{{seconds}}秒</el-button>
</el-col>
</el-row>
</el-form-item>
<el-form-item v-if="verMode == 1" label="短信验证">
<el-row>
<el-col :span="13">
<el-input v-model="user.codeSms"></el-input>
</el-col>
<el-col :spam="11">
<span style="color:red">{{errorMsg.message}}</span>
</el-col>
</el-row>
</el-form-item>
<script>
export default {
data() {
return {
user:{
userName:'',
password:'',
telephone:'', //手机号
},
errorMsg: {},
verMode : '3' , //验证方式
btnDisabled : false , //倒计时控制变量,可用不可用
seconds: 10 , //默认倒计时秒数
timer : null , //接收定时器,清除定时器
},
methods:{
//验证方式点击方法
verModeFn(vo){
this.verMode = vo
},
//发送短信验证--
async sendSmsCodeFn(){
let {data:baseResult} = await this.$axios.post(`/user-service/sms/code`,this.user);
this.errorMsg = baseResult ;
//按钮不可用
this.btnDisabled = true ;
//倒计时
this.timer = setInterval(() => {
if(this.seconds <= 1){
//结束,重置秒数
this.seconds = 10 ;
this.btnDisabled = false ;
//停止定时器
clearInterval(this.timer);
}else{
this.seconds-- ;
}
}, 1000);
},
}
</script>
3.2后端
生成短信验证码,保存在redis中
@RestController
@RequestMapping("/sms")
public class SmsController {
@Resource
private StringRedisTemplate stringRedisTemplate ;
@PostMapping("/code")
public BaseResult sendSms(@RequestBody TbUser user){
//获取当前毫秒值
long start = System.currentTimeMillis();
try {
//发送短信
//1.生成验证码,随机4位数
String code = RandomStringUtils.randomNumeric(4);
System.out.println("短信验证码:" + code);
//存放在redis中
stringRedisTemplate.opsForValue().set("smsPhone"+user.getTelephone(),code,1, TimeUnit.HOURS);
//发送短信
SendSmsResponse smsResponse = SmsUtil.sendSms(user.getTelephone(), user.getUserName(), code, "", "");
if ("OK".equalsIgnoreCase(smsResponse.getCode())){
return BaseResult.ok("短信发送成功,请查收!");
}else {
return BaseResult.error(smsResponse.getMessage());
}
} catch (ClientException e) {
//获取结束时间毫秒值
long end = System.currentTimeMillis();
System.out.println(end -start);
return BaseResult.error("短信发送失败!");
}
}
}
点击登录进行短信验证码判断是否正确
@RestController
@RequestMapping("/user")
public class UserController {
@Resource
private UserService userService ;
@Resource
private JwtProperties jwtProperties ;
@Resource
private StringRedisTemplate stringRedisTemplate ;
@PostMapping("/login")
public BaseResult login(@RequestBody TbUser user) throws Exception {
//手机短信验证
if (user.getCodeSms() != null) {
//获取短信验证码
String sms = "smsPhone" + user.getTelephone() ;
String keySms = stringRedisTemplate.opsForValue().get(sms);
stringRedisTemplate.delete(keySms);
if (keySms == null ){
return BaseResult.error("短信验证码无效!");
}
if (!keySms.equalsIgnoreCase(user.getCodeSms())){
return BaseResult.error("短信验证码错误!");
}
}
//登录对用户名和密码进行判断
//调用userService接口中的方法login进行实现类编写,判断用户名和密码是否正确
TbUser findUser = userService.login(user);
if (findUser != null){
//设置token
String token = JwtUtils.generateToken(findUser, jwtProperties.getExpire(), jwtProperties.getPrivateKey());
return BaseResult.ok("登录成功,欢迎"+findUser.getUserName(),findUser).append("token",token);
}else {
return BaseResult.error("用户名或密码不正确!");
}
}
}
四、邮件验证
4.1 前端
<el-form-item v-if="verMode == 2" label="邮箱" prop="email">
<el-row>
<el-col :span="13">
<el-input v-model="user.email"></el-input>
</el-col>
<el-col :span="11">
<el-button type="success" style="margin-left: 5px;padding: 10px 6px"
@click.prevent="emailCodeFn"
:disabled="btnDisabled"
>邮件发送{{seconds}}秒</el-button>
</el-col>
</el-row>
</el-form-item>
<el-form-item v-if="verMode == 2" label="邮件验证">
<el-row>
<el-col :span="13">
<el-input v-model="user.emailCode"></el-input>
</el-col>
<el-col :spam="11">
<span style="color:red">{{errorMsg.message}}</span>
</el-col>
</el-row>
</el-form-item>
<script>
export default {
data() {
return {
user:{
userName:'',
password:'',
email : ''
},
errorMsg: {},
verMode : '3' , //验证方式
btnDisabled : false , //倒计时控制变量,可用不可用
seconds: 10 , //默认倒计时秒数
timer : null , //接收定时器,清除定时器
},
methods:{
//验证方式点击方法
verModeFn(vo){
this.verMode = vo
},
//发送邮箱验证
async emailCodeFn(){
let {data:baseResult} = await this.$axios.post(`/user-service/email/send`,this.user);
this.errorMsg = baseResult ;
if(baseResult.code == 20000){
this.btnDisabled = true ;
this.timer = setInterval(() => {
if(this.seconds <= 1){
this.seconds = 10 ;
this.btnDisabled = false ;
clearInterval(this.timer);
}else {
this.seconds-- ;
}
}, 1000);
}
}
}
</script>
4.2后端
生成短信验证码,保存在redis中
@RestController
@RequestMapping("/email")
public class EmailController {
@Resource
private StringRedisTemplate stringRedisTemplate ;
@Resource
private JavaMailSender javaMailSender ;
@PostMapping("/send")
public BaseResult send(@RequestBody TbUser tbUser){
try {
//随机生成验证码
String code = RandomStringUtils.randomNumeric(4);
System.out.println("邮件验证码:"+code);
//保存到redis
String key = "email"+tbUser.getUserName();
stringRedisTemplate.opsForValue().set(key,code,1, TimeUnit.HOURS);
//发送
EmailUtils.sendEmail(javaMailSender,tbUser.getEmail(),"邮件验证码为:"+code);
//返回
return BaseResult.ok("邮件发送成功!");
} catch (Exception e) {
e.getMessage();
return BaseResult.error("发送邮件失败!");
}
}
}
点击登录进行邮件验证码判断是否正确
@RestController
@RequestMapping("/user")
public class UserController {
@Resource
private UserService userService ;
@Resource
private JwtProperties jwtProperties ;
@Resource
private StringRedisTemplate stringRedisTemplate ;
@PostMapping("/login")
public BaseResult login(@RequestBody TbUser user) throws Exception {
//邮箱验证
if (user.getEmailCode() != null){
//获取邮箱验证码
String keyEmail = "email"+user.getUserName();
String redisEmail = stringRedisTemplate.opsForValue().get(keyEmail);
stringRedisTemplate.delete(keyEmail);
if (redisEmail == null){
return BaseResult.error("email验证码无效!");
}
if (!redisEmail.equalsIgnoreCase(user.getEmailCode())){
return BaseResult.error("email验证码错误!");
}
}
//登录对用户名和密码进行判断
//调用userService接口中的方法login进行实现类编写,判断用户名和密码是否正确
TbUser findUser = userService.login(user);
if (findUser != null){
//设置token
String token = JwtUtils.generateToken(findUser, jwtProperties.getExpire(), jwtProperties.getPrivateKey());
return BaseResult.ok("登录成功,欢迎"+findUser.getUserName(),findUser).append("token",token);
}else {
return BaseResult.error("用户名或密码不正确!");
}
}
}
五、图片验证邮件验证
5.1 前端
<el-form-item v-if="verMode == 3" label="图片验证">
<el-row>
<el-col :span="11">
<el-input v-model="user.verifyCode"></el-input>
</el-col>
<el-col :span="13" >
<img :src="imgSrc" v-if="user.userName != ''"
style="width: 90px;height: 39px;padding-left: 4px"
@click.prevent="changeVerifyCode"
/>
<span>看不清?<a href="" @click.prevent="changeVerifyCode">换一张</a></span>
</el-col>
</el-row>
<span style="color:red">{{errorMsg.message}}</span>
</el-form-item>
<el-form-item>
<script>
export default {
data() {
return {
user:{
userName:'',
password:'',
verifyCode:'', //图片验证码
},
imgSrc: '', //绑定图片
errorMsg: {},
verMode : '3' , //验证方式
},
methods:{
//验证方式点击方法
verModeFn(vo){
this.verMode = vo
},
//图片验证码
changeVerifyCode(){
if(this.user.userName){
//使用时间对验证码进行标识
//与用户名进行绑定,只要用户名失去焦点就对图片验证码进行一个更新
this.imgSrc = `http://localhost:10010/user-service/verifycode?userName=${this.user.userName}&t=${new Date().getTime()}`
}else{
this.errorMsg.message = '用户不能为空';
}
},
}
</script>
5.2后端
生成图片验证码,保存在redis中
@Controller
@RequestMapping("/verifycode")
public class VerifyCodeController {
@Resource
private StringRedisTemplate stringRedisTemplate ;
@GetMapping
public void verifyCodeFn(String userName,HttpServletResponse response) throws Exception {
//准备数据
//字体只显示大写,去掉了1,0,i,o几个容易混淆的字符
String VERIFY_CODES = "23456789ABCDEFGHJKLMNPQRSTUVWXYZ";
int IMG_WIDTH = 72;
int IMG_HEIGTH = 27;
Random random = new Random();
//创建图片
BufferedImage image = new BufferedImage(IMG_WIDTH, IMG_HEIGTH, BufferedImage.TYPE_INT_RGB);
//画板
Graphics g = image.getGraphics();
//填充背景
g.setColor(Color.WHITE);
g.fillRect(1,1,IMG_WIDTH-2,IMG_HEIGTH-2);
g.setFont(new Font("楷体", Font.BOLD,25));
StringBuilder sb = new StringBuilder();
//写字
for(int i = 1 ; i <= 4 ; i ++){
//随机颜色
g.setColor(new Color(random.nextInt(255),random.nextInt(255),random.nextInt(255)));
int len = random.nextInt(VERIFY_CODES.length());
String str = VERIFY_CODES.substring(len,len+1);
sb.append(str);
g.drawString(str, IMG_WIDTH / 6 * i , 22 );
}
//将验证码存放到redis
//设置名称login+username ,过期时间1小时
stringRedisTemplate.opsForValue().set( "login" + userName , sb.toString() , 1 , TimeUnit.HOURS);
// 生成随机干扰线
for (int i = 0; i < 30; i++) {
//随机颜色
g.setColor(new Color(random.nextInt(255),random.nextInt(255),random.nextInt(255)));
int x = random.nextInt(IMG_WIDTH - 1);
int y = random.nextInt(IMG_HEIGTH - 1);
int x1 = random.nextInt(12) + 1;
int y1 = random.nextInt(6) + 1;
g.drawLine(x, y, x - x1, y - y1);
}
//响应到浏览器
ImageIO.write(image,"jpeg", response.getOutputStream());
}
}
点击登录进行图片验证码判断是否正确
@RestController
@RequestMapping("/user")
public class UserController {
@Resource
private UserService userService ;
@Resource
private JwtProperties jwtProperties ;
@Resource
private StringRedisTemplate stringRedisTemplate ;
@PostMapping("/login")
public BaseResult login(@RequestBody TbUser user) throws Exception {
//校验图片验证码
if (!user.getVerifyCode().equals("")) {
//获取验证码
String key = "login" + user.getUserName() ;
String verify = stringRedisTemplate.opsForValue().get(key);
//删除验证码
stringRedisTemplate.delete(key);
if (verify == null) {
return BaseResult.error("图片验证码无效!");
}
if (!verify.equalsIgnoreCase(user.getVerifyCode())) {
return BaseResult.error("图片验证码错误!");
}
}
//登录对用户名和密码进行判断
//调用userService接口中的方法login进行实现类编写,判断用户名和密码是否正确
TbUser findUser = userService.login(user);
if (findUser != null){
//设置token
String token = JwtUtils.generateToken(findUser, jwtProperties.getExpire(), jwtProperties.getPrivateKey());
return BaseResult.ok("登录成功,欢迎"+findUser.getUserName(),findUser).append("token",token);
}else {
return BaseResult.error("用户名或密码不正确!");
}
}
}
写到最后
四季轮换,已经数不清凋零了多少, 愿我们往后能向心而行,一路招摇胜!
🐋 你的支持认可是我创作的动力
💟 创作不易,不妨点赞💚评论❤️收藏💙一下
😘 感谢大佬们的支持,欢迎各位前来不吝赐教