android - 在android中实现手机号登录并在spring boot中验证
问题描述
在 Android 手机号码登录过程中,我需要大家的帮助。我有一个应用程序,用户应该使用手机号码启动登录,然后我需要在 Spring Boot 中使用基于 OTP 的身份验证来验证该号码。验证成功后,Spring Boot 应用程序将生成 JWT 身份验证令牌,用户将使用该令牌访问其他 API。
期待您的回复。
谢谢
解决方案
您需要一个额外的身份验证提供程序:
@Slf4j
@Configuration
@EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter {
@Bean
public BCryptPasswordEncoder passwordEncoder() {
return new BCryptPasswordEncoder();
}
@Override
@Bean
public AuthenticationManager authenticationManagerBean() throws Exception {
return super.authenticationManagerBean();
}
@Autowired
private OtpAuthenticationProvider otpAuthenticationProvider;
@Autowired
private JwtConfig jwtConfig;
@Autowired
private PasswordAuthenticationProvider passwordAuthenticationProvider;
@Override
protected void configure(AuthenticationManagerBuilder auth) {
auth
.authenticationProvider(otpAuthenticationProvider)
.authenticationProvider(passwordAuthenticationProvider);
}
@Override
protected void configure(HttpSecurity http) throws Exception {
http
.csrf().disable()
// make sure we use stateless session; session won't be used to store user's state.
.sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS)
.and()
// handle an authorized attempts
.exceptionHandling().authenticationEntryPoint((req, rsp, e) -> rsp.sendError(HttpServletResponse.SC_UNAUTHORIZED))
.and()
// Add a filter to validate the tokens with every request
.addFilterAfter(new JwtTokenAuthenticationFilter(jwtConfig), UsernamePasswordAuthenticationFilter.class)
// authorization requests config
.authorizeRequests()
// allow all who are accessing "auth" service
// allow /msg
.antMatchers("/oauth/token", "/v1/auth/**").permitAll()
// must be an admin if trying to access admin area (authentication is also required here)
// Any other request must be authenticated
.anyRequest().authenticated();
}
@Override
public void configure(WebSecurity web) throws Exception {
web.ignoring().antMatchers("/webjars/**", "/swagger-ui.html**", "/favicon.ico",
"/swagger-resources**", "/swagger-resources/**", "/csrf**", "/v2/api-docs**");
}
@Bean
public JwtConfig jwtConfig() {
return new JwtConfig();
}
}
这是 otpAuthenticationProvider --
/**
* @author dv singh
*/
@Component
public class OtpAuthenticationProvider implements AuthenticationProvider {
private final AccountOtpService otpService;
private final AccountService accountService;
@Autowired
public OtpAuthenticationProvider(@Lazy AccountOtpService otpService, @Lazy AccountService accountService) {
this.otpService = otpService;
this.accountService = accountService;
}
@Override
public Authentication authenticate(Authentication authentication) throws AuthenticationException {
final OtpAuthenticationRequestToken request = (OtpAuthenticationRequestToken) authentication;
AccountOtp otpPrincipal = null;
// todo remove condition for prod, it for testing and development
if(!request.getToken().equals("123456")) {
try {
otpPrincipal = otpService.findByMobile(request.getMobile());
} catch (NoSuchElementException e) {
throw new BadCredentialsException("Invalid OTP");
}
if (!otpPrincipal.getOtp().equals(request.getToken()) || !otpPrincipal.getCreatedOn().isAfter(LocalDateTime.now()))
throw new BadCredentialsException("Invalid OTP");
}
Account account;
try {
account = accountService.findByMobile(request.getMobile());
} catch (NoSuchElementException e){
account = accountService.createJobSeeker(request.getMobile(), request.getDeviceToken());
}
// todo remove condition for prod
if(!request.getToken().equals("123456"))
otpService.clearOtp(otpPrincipal);
return new OtpAuthenticationToken(CustomAccountDetail.create(account));
}
@Override
public boolean supports(Class<?> authentication) {
return OtpAuthenticationRequestToken.class.isAssignableFrom(authentication);
}
}
推荐阅读
- python - 将 dask 数据帧转换为 avro
- java - SQL条件的Json表示
- javascript - 将 js 对象推送到数组
- asp.net - GraphQL.NET:如何将根查询分成多个部分
- angular - Ngx-bootstrap 下拉菜单在角度 6 中不起作用
- asp.net-mvc - ASP.NET Core 中间件和 URL 解析
- c# - 使用 LINQ 查询从数据库中返回项目列表
- java - 我可以访问为线程池线程提交任务(并且正在运行)的线程吗?
- javascript - 未捕获的 ConfigError:使用 Jquery 查询构建器时未定义目标
- node.js - 如何在可视代码中调试 Angular 7 库