登录页面如何实现手机验证码

时间: 2023-11-04 15:06:12 浏览: 74
要实现手机验证码功能的登录页面,可以按照以下步骤进行: 1. 用户输入手机号码:在登录页面中添加一个手机号码输入框,要求用户输入手机号。 2. 生成验证码:后端服务器收到用户提交的手机号后,通过短信服务商的接口生成一个随机的验证码,并将该验证码与用户手机号绑定。 3. 发送验证码:将生成的验证码通过短信服务商的接口发送到用户的手机号上。 4. 验证码校验:用户收到验证码后,在登录页面中添加一个验证码输入框,要求用户输入收到的验证码。 5. 提交校验:用户在验证码输入框中输入完毕后,点击提交按钮。 6. 后端校验:后端服务器接收到用户提交的验证码后,与之前绑定的手机号对应的验证码进行比对,判断是否匹配。 7. 登录成功或失败:根据验证码校验的结果,如果匹配成功,则允许用户继续登录;如果匹配失败,则提示用户重新输入正确的验证码。 需要注意的是,要实现手机验证码功能,你需要获取一个可靠的短信服务商的接口,并将其集成到你的后端服务器中。此外,为了防止滥用,你可能还需要设置一些限制,比如每个手机号码一天只能请求一定次数的验证码。
相关问题

springsecurity实现手机验证码登录

Spring Security可以很方便地实现手机验证码登录,步骤如下: 1. 添加spring-security-web和spring-security-config依赖。 ```xml <dependency> <groupId>org.springframework.security</groupId> <artifactId>spring-security-web</artifactId> <version>${spring-security.version}</version> </dependency> <dependency> <groupId>org.springframework.security</groupId> <artifactId>spring-security-config</artifactId> <version>${spring-security.version}</version> </dependency> ``` 2. 创建一个实现UserDetailsService接口的类,该类用于根据不同的用户名加载用户信息。 ```java @Service public class UserDetailsServiceImpl implements UserDetailsService { @Autowired private UserMapper userMapper; @Override public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException { User user = userMapper.selectByUsername(username); if (user == null) { throw new UsernameNotFoundException("用户名不存在"); } return new UserPrincipal(user); } } ``` 3. 创建一个实现AuthenticationProvider接口的类,该类用于验证用户的手机号和验证码是否正确。 ```java @Service public class SmsCodeAuthenticationProvider implements AuthenticationProvider { @Autowired private RedisTemplate<String, String> redisTemplate; @Override public Authentication authenticate(Authentication authentication) throws AuthenticationException { SmsCodeAuthenticationToken authenticationToken = (SmsCodeAuthenticationToken) authentication; String mobile = authenticationToken.getPrincipal().toString(); String code = authenticationToken.getCredentials().toString(); String redisCode = redisTemplate.opsForValue().get(SmsCodeAuthenticationFilter.REDIS_SMS_CODE_KEY_PREFIX + mobile); if (StringUtils.isBlank(redisCode)) { throw new BadCredentialsException("验证码不存在或已过期"); } if (!StringUtils.equals(code, redisCode)) { throw new BadCredentialsException("验证码不正确"); } UserDetails userDetails = new UserPrincipal(new User(mobile, "", Collections.emptyList())); return new SmsCodeAuthenticationToken(userDetails, userDetails.getAuthorities()); } @Override public boolean supports(Class<?> authentication) { return SmsCodeAuthenticationToken.class.isAssignableFrom(authentication); } } ``` 4. 创建一个实现AuthenticationFilter接口的类,该类用于处理短信验证码登录请求。 ```java public class SmsCodeAuthenticationFilter extends AbstractAuthenticationProcessingFilter { public static final String SPRING_SECURITY_FORM_MOBILE_KEY = "mobile"; public static final String SPRING_SECURITY_FORM_CODE_KEY = "code"; public static final String REDIS_SMS_CODE_KEY_PREFIX = "SMS_CODE_"; private String mobileParameter = SPRING_SECURITY_FORM_MOBILE_KEY; private String codeParameter = SPRING_SECURITY_FORM_CODE_KEY; private boolean postOnly = true; public SmsCodeAuthenticationFilter() { super(new AntPathRequestMatcher("/login/mobile", "POST")); } @Override public Authentication attemptAuthentication(HttpServletRequest request, HttpServletResponse response) throws AuthenticationException, IOException, ServletException { if (postOnly && !request.getMethod().equals("POST")) { throw new AuthenticationServiceException("不支持的请求方式: " + request.getMethod()); } String mobile = obtainMobile(request); String code = obtainCode(request); if (StringUtils.isBlank(mobile)) { throw new UsernameNotFoundException("手机号不能为空"); } if (StringUtils.isBlank(code)) { throw new BadCredentialsException("验证码不能为空"); } SmsCodeAuthenticationToken authRequest = new SmsCodeAuthenticationToken(mobile, code); setDetails(request, authRequest); return this.getAuthenticationManager().authenticate(authRequest); } protected String obtainMobile(HttpServletRequest request) { return request.getParameter(mobileParameter); } protected String obtainCode(HttpServletRequest request) { return request.getParameter(codeParameter); } protected void setDetails(HttpServletRequest request, SmsCodeAuthenticationToken authRequest) { authRequest.setDetails(authenticationDetailsSource.buildDetails(request)); } public void setMobileParameter(String mobileParameter) { this.mobileParameter = mobileParameter; } public void setCodeParameter(String codeParameter) { this.codeParameter = codeParameter; } public void setPostOnly(boolean postOnly) { this.postOnly = postOnly; } public final String getMobileParameter() { return mobileParameter; } public final String getCodeParameter() { return codeParameter; } } ``` 5. 在WebSecurityConfigurerAdapter的子类中进行配置。 ```java @Configuration @EnableWebSecurity public class SecurityConfig extends WebSecurityConfigurerAdapter { @Autowired private UserDetailsServiceImpl userDetailsService; @Autowired private SmsCodeAuthenticationProvider smsCodeAuthenticationProvider; @Override protected void configure(HttpSecurity http) throws Exception { http.authorizeRequests() .antMatchers("/login/mobile").permitAll() .anyRequest().authenticated() .and() .formLogin().loginPage("/login").defaultSuccessURL("/home").permitAll() .and() .logout().logoutUrl("/logout").permitAll() .and() .addFilterBefore(smsCodeAuthenticationFilter(), UsernamePasswordAuthenticationFilter.class) .csrf().disable(); } @Override protected void configure(AuthenticationManagerBuilder auth) throws Exception { auth.authenticationProvider(smsCodeAuthenticationProvider) .userDetailsService(userDetailsService) .passwordEncoder(passwordEncoder()); } @Bean public PasswordEncoder passwordEncoder() { return new BCryptPasswordEncoder(); } @Bean public SmsCodeAuthenticationFilter smsCodeAuthenticationFilter() { SmsCodeAuthenticationFilter filter = new SmsCodeAuthenticationFilter(); filter.setAuthenticationManager(authenticationManager()); filter.setAuthenticationSuccessHandler((request, response, authentication) -> { response.setContentType("application/json;charset=UTF-8"); PrintWriter out = response.getWriter(); out.write("{\"code\": 0, \"message\": \"登录成功\"}"); out.flush(); out.close(); }); filter.setAuthenticationFailureHandler((request, response, exception) -> { response.setContentType("application/json;charset=UTF-8"); PrintWriter out = response.getWriter(); out.write("{\"code\": 1, \"message\": \"" + exception.getMessage() + "\"}"); out.flush(); out.close(); }); return filter; } } ``` 6. 在前端页面中添加短信验证码登录的表单。 ```html <form action="/login/mobile" method="post"> <div> <label>手机号:</label> <input type="text" name="mobile" /> </div> <div> <label>验证码:</label> <input type="text" name="code" /> <button type="button" onclick="sendSmsCode()">发送验证码</button> </div> <div> <button type="submit">登录</button> </div> </form> ``` 7. 在后端控制器中添加发送短信验证码的接口。 ```java @RestController public class SmsCodeController { @Autowired private RedisTemplate<String, String> redisTemplate; @GetMapping("/sms/code") public void sendSmsCode(String mobile) { String code = RandomStringUtils.randomNumeric(6); redisTemplate.opsForValue().set(SmsCodeAuthenticationFilter.REDIS_SMS_CODE_KEY_PREFIX + mobile, code, 5, TimeUnit.MINUTES); // 发送短信验证码 } } ``` 以上就是使用Spring Security实现手机验证码登录的全部步骤。

使用springboot实现手机验证码code登录

可以通过以下步骤使用springboot实现手机验证码登录: 1. 集成Spring Security依赖 在`pom.xml`文件中添加以下依赖: ``` <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-security</artifactId> </dependency> ``` 2. 实现UserDetailsService接口 创建一个类实现`UserDetailsService`接口,并在其中实现从数据库中获取用户信息的逻辑。例如: ``` @Service public class UserDetailsServiceImpl implements UserDetailsService { @Autowired private UserRepository userRepository; @Override public UserDetails loadUserByUsername(String phoneNumber) throws UsernameNotFoundException { User user = userRepository.findByPhoneNumber(phoneNumber); if (user == null) { throw new UsernameNotFoundException("User not found with phoneNumber: " + phoneNumber); } return new org.springframework.security.core.userdetails.User(user.getPhoneNumber(), user.getPassword(), new ArrayList<>()); } } ``` 3. 配置Spring Security 在`application.properties`文件中配置Spring Security相关属性: ``` # 禁用CSRF保护,因为我们将使用手机验证码进行登录 security.enable-csrf=false # 配置登录页面和处理登录请求的控制器 spring.security.loginProcessingUrl = /login spring.security.loginPage = /login.html ``` 4. 创建登录页面 创建一个名为`login.html`的登录页面,包含一个表单,用于输入手机号和验证码。例如: ``` <!DOCTYPE html> <html> <head> <meta charset="UTF-8"> <title>Login</title> </head> <body> <h2>Login</h2> <form action="/login" method="post"> <div> <label for="phoneNumber">Phone Number:</label> <input type="text" id="phoneNumber" name="phoneNumber" required> </div> <div> <label for="code">Code:</label> <input type="text" id="code" name="code" required> <button type="button" id="sendCode">Send Code</button> </div> <button type="submit">Login</button> </form> <script> // 发送验证码的逻辑 document.getElementById("sendCode").addEventListener("click", function() { var phoneNumber = document.getElementById("phoneNumber").value; // 调用后端API发送验证码 // ... }); </script> </body> </html> ``` 5. 实现发送验证码API 创建一个控制器,用于处理发送验证码的API请求。例如: ``` @RestController public class SMSController { @PostMapping("/sendCode") public ResponseEntity<?> sendCode(@RequestParam("phoneNumber") String phoneNumber) { // 调用发送短信验证码的服务 // ... return ResponseEntity.ok().build(); } } ``` 6. 实现登录API 创建一个控制器,用于处理登录API请求。在该控制器中,使用`AuthenticationManager`和`TokenBasedRememberMeServices`来实现登录逻辑。例如: ``` @RestController public class LoginController { @Autowired private AuthenticationManager authenticationManager; @Autowired private TokenBasedRememberMeServices rememberMeServices; @PostMapping("/login") public ResponseEntity<?> login(@RequestParam("phoneNumber") String phoneNumber, @RequestParam("code") String code, HttpServletRequest request, HttpServletResponse response) { // 校验验证码是否正确 // ... // 创建一个UsernamePasswordAuthenticationToken,以便交给AuthenticationManager进行验证 UsernamePasswordAuthenticationToken token = new UsernamePasswordAuthenticationToken(phoneNumber, code); // 让AuthenticationManager进行验证,并返回一个Authentication对象 Authentication authentication = authenticationManager.authenticate(token); // 让TokenBasedRememberMeServices进行处理,并返回一个RememberMeAuthenticationToken对象 RememberMeAuthenticationToken rememberMeToken = rememberMeServices .autoLogin(request, response); // 将两个Authentication对象合并成一个 Authentication mergedAuthentication = new PreAuthenticatedAuthenticationToken( authentication.getPrincipal(), authentication.getCredentials(), Stream.concat(authentication.getAuthorities().stream(), rememberMeToken.getAuthorities().stream()) .collect(Collectors.toList())); // 在SecurityContextHolder中存储合并后的Authentication对象 SecurityContextHolder.getContext().setAuthentication(mergedAuthentication); // 登录成功,返回一个空响应 return ResponseEntity.ok().build(); } } ``` 这样,我们就实现了使用springboot实现手机验证码登录。需要注意的是,该代码仅为示例,实际场景中可能需要根据具体需求进行修改。

相关推荐

最新推荐

recommend-type

Flutter 完美的验证码输入框实现

主要介绍了Flutter 完美的验证码输入框实现,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友们下面随着小编来一起学习学习吧
recommend-type

vue 实现用户登录方式的切换功能

主要介绍了vue 实现用户登录方式的切换功能,本文通过实例代码给大家介绍的非常详细,对大家的学习或工作具有一定的参考借鉴价值,需要的朋友可以参考下
recommend-type

软2一月考勤表-20230917-075457.xlsx

软2一月考勤表-20230917-075457.xlsx
recommend-type

RTL8188FU-Linux-v5.7.4.2-36687.20200602.tar(20765).gz

REALTEK 8188FTV 8188eus 8188etv linux驱动程序稳定版本, 支持AP,STA 以及AP+STA 共存模式。 稳定支持linux4.0以上内核。
recommend-type

管理建模和仿真的文件

管理Boualem Benatallah引用此版本:布阿利姆·贝纳塔拉。管理建模和仿真。约瑟夫-傅立叶大学-格勒诺布尔第一大学,1996年。法语。NNT:电话:00345357HAL ID:电话:00345357https://theses.hal.science/tel-003453572008年12月9日提交HAL是一个多学科的开放存取档案馆,用于存放和传播科学研究论文,无论它们是否被公开。论文可以来自法国或国外的教学和研究机构,也可以来自公共或私人研究中心。L’archive ouverte pluridisciplinaire
recommend-type

:YOLOv1目标检测算法:实时目标检测的先驱,开启计算机视觉新篇章

![:YOLOv1目标检测算法:实时目标检测的先驱,开启计算机视觉新篇章](https://img-blog.csdnimg.cn/img_convert/69b98e1a619b1bb3c59cf98f4e397cd2.png) # 1. 目标检测算法概述 目标检测算法是一种计算机视觉技术,用于识别和定位图像或视频中的对象。它在各种应用中至关重要,例如自动驾驶、视频监控和医疗诊断。 目标检测算法通常分为两类:两阶段算法和单阶段算法。两阶段算法,如 R-CNN 和 Fast R-CNN,首先生成候选区域,然后对每个区域进行分类和边界框回归。单阶段算法,如 YOLO 和 SSD,一次性执行检
recommend-type

设计算法实现将单链表中数据逆置后输出。用C语言代码

如下所示: ```c #include <stdio.h> #include <stdlib.h> // 定义单链表节点结构体 struct node { int data; struct node *next; }; // 定义单链表逆置函数 struct node* reverse(struct node *head) { struct node *prev = NULL; struct node *curr = head; struct node *next; while (curr != NULL) { next
recommend-type

c++校园超市商品信息管理系统课程设计说明书(含源代码) (2).pdf

校园超市商品信息管理系统课程设计旨在帮助学生深入理解程序设计的基础知识,同时锻炼他们的实际操作能力。通过设计和实现一个校园超市商品信息管理系统,学生掌握了如何利用计算机科学与技术知识解决实际问题的能力。在课程设计过程中,学生需要对超市商品和销售员的关系进行有效管理,使系统功能更全面、实用,从而提高用户体验和便利性。 学生在课程设计过程中展现了积极的学习态度和纪律,没有缺勤情况,演示过程流畅且作品具有很强的使用价值。设计报告完整详细,展现了对问题的深入思考和解决能力。在答辩环节中,学生能够自信地回答问题,展示出扎实的专业知识和逻辑思维能力。教师对学生的表现予以肯定,认为学生在课程设计中表现出色,值得称赞。 整个课程设计过程包括平时成绩、报告成绩和演示与答辩成绩三个部分,其中平时表现占比20%,报告成绩占比40%,演示与答辩成绩占比40%。通过这三个部分的综合评定,最终为学生总成绩提供参考。总评分以百分制计算,全面评估学生在课程设计中的各项表现,最终为学生提供综合评价和反馈意见。 通过校园超市商品信息管理系统课程设计,学生不仅提升了对程序设计基础知识的理解与应用能力,同时也增强了团队协作和沟通能力。这一过程旨在培养学生综合运用技术解决问题的能力,为其未来的专业发展打下坚实基础。学生在进行校园超市商品信息管理系统课程设计过程中,不仅获得了理论知识的提升,同时也锻炼了实践能力和创新思维,为其未来的职业发展奠定了坚实基础。 校园超市商品信息管理系统课程设计的目的在于促进学生对程序设计基础知识的深入理解与掌握,同时培养学生解决实际问题的能力。通过对系统功能和用户需求的全面考量,学生设计了一个实用、高效的校园超市商品信息管理系统,为用户提供了更便捷、更高效的管理和使用体验。 综上所述,校园超市商品信息管理系统课程设计是一项旨在提升学生综合能力和实践技能的重要教学活动。通过此次设计,学生不仅深化了对程序设计基础知识的理解,还培养了解决实际问题的能力和团队合作精神。这一过程将为学生未来的专业发展提供坚实基础,使其在实际工作中能够胜任更多挑战。
recommend-type

"互动学习:行动中的多样性与论文攻读经历"

多样性她- 事实上SCI NCES你的时间表ECOLEDO C Tora SC和NCESPOUR l’Ingén学习互动,互动学习以行动为中心的强化学习学会互动,互动学习,以行动为中心的强化学习计算机科学博士论文于2021年9月28日在Villeneuve d'Asq公开支持马修·瑟林评审团主席法布里斯·勒菲弗尔阿维尼翁大学教授论文指导奥利维尔·皮耶昆谷歌研究教授:智囊团论文联合主任菲利普·普雷教授,大学。里尔/CRISTAL/因里亚报告员奥利维耶·西格德索邦大学报告员卢多维奇·德诺耶教授,Facebook /索邦大学审查员越南圣迈IMT Atlantic高级讲师邀请弗洛里安·斯特鲁布博士,Deepmind对于那些及时看到自己错误的人...3谢谢你首先,我要感谢我的两位博士生导师Olivier和Philippe。奥利维尔,"站在巨人的肩膀上"这句话对你来说完全有意义了。从科学上讲,你知道在这篇论文的(许多)错误中,你是我可以依
recommend-type

:YOLO目标检测算法的挑战与机遇:数据质量、计算资源与算法优化,探索未来发展方向

![:YOLO目标检测算法的挑战与机遇:数据质量、计算资源与算法优化,探索未来发展方向](https://img-blog.csdnimg.cn/7e3d12895feb4651b9748135c91e0f1a.png?x-oss-process=image/watermark,type_ZHJvaWRzYW5zZmFsbGJhY2s,shadow_50,text_Q1NETiBA5rKJ6YaJ77yM5LqO6aOO5Lit,size_20,color_FFFFFF,t_70,g_se,x_16) # 1. YOLO目标检测算法简介 YOLO(You Only Look Once)是一种