资讯专栏INFORMATION COLUMN

oauth 实现手机号码登录

hyuan / 3309人阅读

摘要:现在有一个需求就是改造实现手机号码可以登录需要重几个类第一个类手机验证码登陆第二个类验证码验证,调用公共服务查询为的,并判断其与验证码是否匹配第三个类第四个类第五个类不存在不匹配最后在配置一下设置禁止隐藏用户未找到异常使用进行密码

现在有一个需求就是改造 oauth2.0 实现手机号码可以登录 需要重几个类

第一个类

public class PhoneLoginAuthenticationFilter extends AbstractAuthenticationProcessingFilter {

</>复制代码

  1. private static final String SPRING_SECURITY_RESTFUL_PHONE_KEY = "phone";
  2. private static final String SPRING_SECURITY_RESTFUL_VERIFY_CODE_KEY = "verifyCode";
  3. private static final String SPRING_SECURITY_RESTFUL_LOGIN_URL = "/oauth/phoneLogin";
  4. private boolean postOnly = true;
  5. public PhoneLoginAuthenticationFilter() {
  6. super(new AntPathRequestMatcher(SPRING_SECURITY_RESTFUL_LOGIN_URL, "POST"));
  7. }
  8. @Override
  9. public Authentication attemptAuthentication(HttpServletRequest request, HttpServletResponse response) throws AuthenticationException {
  10. if (postOnly && !request.getMethod().equals("POST")) {
  11. throw new AuthenticationServiceException(
  12. "Authentication method not supported: " + request.getMethod());
  13. }
  14. AbstractAuthenticationToken authRequest;
  15. String principal;
  16. String credentials;
  17. // 手机验证码登陆
  18. principal = obtainParameter(request, SPRING_SECURITY_RESTFUL_PHONE_KEY);
  19. credentials = obtainParameter(request, SPRING_SECURITY_RESTFUL_VERIFY_CODE_KEY);
  20. principal = principal.trim();
  21. authRequest = new PhoneAuthenticationToken(principal, credentials);
  22. // Allow subclasses to set the "details" property
  23. setDetails(request, authRequest);
  24. return this.getAuthenticationManager().authenticate(authRequest);
  25. }
  26. private void setDetails(HttpServletRequest request,
  27. AbstractAuthenticationToken authRequest) {
  28. authRequest.setDetails(authenticationDetailsSource.buildDetails(request));
  29. }
  30. private String obtainParameter(HttpServletRequest request, String parameter) {
  31. String result = request.getParameter(parameter);
  32. return result == null ? "" : result;
  33. }

第二个类

public class PhoneAuthenticationProvider extends MyAbstractUserDetailsAuthenticationProvider {

</>复制代码

  1. private UserDetailsService userDetailsService;
  2. @Override
  3. protected void additionalAuthenticationChecks(UserDetails var1, Authentication authentication) throws AuthenticationException {
  4. if(authentication.getCredentials() == null) {
  5. this.logger.debug("Authentication failed: no credentials provided");
  6. throw new BadCredentialsException(this.messages.getMessage("PhoneAuthenticationProvider.badCredentials", "Bad credentials"));
  7. } else {
  8. String presentedPassword = authentication.getCredentials().toString();
  9. // 验证码验证,调用公共服务查询 key 为authentication.getPrincipal()的value, 并判断其与验证码是否匹配
  10. if(!"1000".equals(presentedPassword)){
  11. this.logger.debug("Authentication failed: verifyCode does not match stored value");
  12. throw new BadCredentialsException(this.messages.getMessage("PhoneAuthenticationProvider.badCredentials", "Bad verifyCode"));
  13. }
  14. }
  15. }
  16. @Override
  17. protected Authentication createSuccessAuthentication(Object principal, Authentication authentication, UserDetails user) {
  18. PhoneAuthenticationToken result = new PhoneAuthenticationToken(principal, authentication.getCredentials(), user.getAuthorities());
  19. result.setDetails(authentication.getDetails());
  20. return result;
  21. }
  22. @Override
  23. protected UserDetails retrieveUser(String phone, Authentication authentication) throws AuthenticationException {
  24. UserDetails loadedUser;
  25. try {
  26. loadedUser = this.getUserDetailsService().loadUserByUsername(phone);
  27. } catch (UsernameNotFoundException var6) {
  28. throw var6;
  29. } catch (Exception var7) {
  30. throw new InternalAuthenticationServiceException(var7.getMessage(), var7);
  31. }
  32. if(loadedUser == null) {
  33. throw new InternalAuthenticationServiceException("UserDetailsService returned null, which is an interface contract violation");
  34. } else {
  35. return loadedUser;
  36. }
  37. }
  38. @Override
  39. public boolean supports(Class authentication) {
  40. return PhoneAuthenticationToken.class.isAssignableFrom(authentication);
  41. }
  42. public UserDetailsService getUserDetailsService() {
  43. return userDetailsService;
  44. }
  45. public void setUserDetailsService(UserDetailsService userDetailsService) {
  46. this.userDetailsService = userDetailsService;
  47. }

}
第三个类

@Service
public class PhoneUserDetailService implements UserDetailsService {

</>复制代码

  1. private Logger logger = LoggerFactory.getLogger(this.getClass());
  2. @Override
  3. public UserDetails loadUserByUsername(String s) throws UsernameNotFoundException {
  4. System.out.println("PhoneUserDetailService");
  5. return new User("admin", "1000", AuthorityUtils.commaSeparatedStringToAuthorityList("ROLE_USER"));
  6. }

}
第四个类

public class PhoneAuthenticationToken extends MyAuthenticationToken {

</>复制代码

  1. public PhoneAuthenticationToken(Object principal, Object credentials) {
  2. super(principal, credentials);
  3. }
  4. public PhoneAuthenticationToken(Object principal, Object credentials, Collection authorities) {
  5. super(principal, credentials, authorities);
  6. }

}
第五个类

@Component("MyLoginAuthSuccessHandler")
public class MyLoginAuthSuccessHandler extends SavedRequestAwareAuthenticationSuccessHandler {

</>复制代码

  1. @Autowired
  2. private ClientDetailsService clientDetailsService;
  3. @Autowired
  4. private AuthorizationServerTokenServices authorizationServerTokenServices;
  5. @Override
  6. public void onAuthenticationSuccess(HttpServletRequest request, HttpServletResponse response, Authentication authentication) throws IOException, ServletException {

// String clientId = obtainParameter(request, "client_id");
// String client_secret = obtainParameter(request, "client_secret");

</>复制代码

  1. String header = request.getHeader("Authorization");
  2. header.toLowerCase().startsWith("basic ");
  3. String[] strings = extractAndDecodeHeader(header, request);
  4. String clientId = strings[0];
  5. String client_secret = strings[1];
  6. String clientSecret = new BCryptPasswordEncoder().encode(client_secret);
  7. System.out.println(clientSecret);
  8. ClientDetails clientDetails = clientDetailsService.loadClientByClientId(clientId);
  9. if (null == clientDetails) {
  10. throw new UnapprovedClientAuthenticationException("clientId不存在" + clientId);
  11. } else if (!new BCryptPasswordEncoder().matches(client_secret, clientDetails.getClientSecret())) {
  12. throw new UnapprovedClientAuthenticationException("clientSecret不匹配" + clientId);
  13. }
  14. TokenRequest tokenRequest = new TokenRequest(MapUtils.EMPTY_MAP, clientId, clientDetails.getScope(), "phone");
  15. OAuth2Request oAuth2Request = tokenRequest.createOAuth2Request(clientDetails);
  16. OAuth2Authentication oAuth2Authentication = new OAuth2Authentication(oAuth2Request, authentication);
  17. OAuth2AccessToken token = authorizationServerTokenServices.createAccessToken(oAuth2Authentication);
  18. Set scope = token.getScope();
  19. StringBuffer stringBuffer = new StringBuffer();
  20. stringBuffer.append(scope.stream().findFirst());
  21. scope.stream().forEach(s -> {
  22. stringBuffer.append("," + s);
  23. });
  24. Map map = new HashMap<>();
  25. map.put("access_token", token.getValue());
  26. map.put("token_type", token.getTokenType());
  27. map.put("refresh_token", token.getRefreshToken().getValue());
  28. map.put("expires_in", token.getExpiresIn());
  29. map.put("scope", scope.stream().findFirst());
  30. response.setContentType("application/json;charset=UTF-8");
  31. response.getWriter().write(JsonUtil.toJsonString(map));
  32. }
  33. private String obtainParameter(HttpServletRequest request, String parameter) {
  34. String result = request.getParameter(parameter);
  35. return result == null ? "" : result;
  36. }
  37. private String[] extractAndDecodeHeader(String header, HttpServletRequest request)
  38. throws IOException {
  39. byte[] base64Token = header.substring(6).getBytes("UTF-8");
  40. byte[] decoded;
  41. try {
  42. decoded = Base64.getDecoder().decode(base64Token);
  43. }
  44. catch (IllegalArgumentException e) {
  45. throw new BadCredentialsException(
  46. "Failed to decode basic authentication token");
  47. }
  48. String token = new String(decoded, "UTF-8");
  49. int delim = token.indexOf(":");
  50. if (delim == -1) {
  51. throw new BadCredentialsException("Invalid basic authentication token");
  52. }
  53. return new String[] { token.substring(0, delim), token.substring(delim + 1) };
  54. }

}
最后在 SecurityConfig 配置一下

@Configuration
public class SecurityConfig extends WebSecurityConfigurerAdapter {

</>复制代码

  1. @Autowired
  2. private SsoUserDetailsService ssoUserDetailsService;
  3. @Autowired
  4. private PhoneUserDetailService phoneUserDetailService;
  5. @Autowired
  6. private QrUserDetailService qrUserDetailService;
  7. @Autowired
  8. private MyLoginAuthSuccessHandler myLoginAuthSuccessHandler;
  9. @Bean
  10. public PasswordEncoder passwordEncoder() {
  11. return new BCryptPasswordEncoder();
  12. }
  13. @Override
  14. public void configure(WebSecurity web) {
  15. web.ignoring().antMatchers("/authentication/require", "/**/*.js",
  16. "/**/*.css",
  17. "/**/*.jpg",
  18. "/**/*.png",
  19. "/**/*.woff2",
  20. "/oauth/exit",
  21. "/oauth/logout"
  22. );
  23. }
  24. @Override
  25. protected void configure(HttpSecurity http) throws Exception {
  26. http
  27. .addFilterBefore(getPhoneLoginAuthenticationFilter(), UsernamePasswordAuthenticationFilter.class)
  28. .addFilterBefore(getQrLoginAuthenticationFilter(), UsernamePasswordAuthenticationFilter.class)
  29. .formLogin().loginPage("/authentication/require")
  30. .loginProcessingUrl("/authentication/form")
  31. .successHandler(myLoginAuthSuccessHandler).and()
  32. .authorizeRequests().antMatchers("/authentication/require",
  33. "/authentication/form",
  34. "/**/*.js",
  35. "/**/*.css",
  36. "/**/*.jpg",
  37. "/**/*.png",
  38. "/**/*.woff2",
  39. "/auth/*",
  40. "/oauth/*",
  41. )
  42. .permitAll()
  43. .anyRequest().authenticated().and().anonymous().disable().exceptionHandling().authenticationEntryPoint(new LoginUrlAuthenticationEntryPoint("/login?error")).and()
  44. .csrf().disable();
  45. http.addFilterBefore(myFilterSecurityInterceptor, FilterSecurityInterceptor.class);
  46. }
  47. @Override
  48. protected void configure(AuthenticationManagerBuilder auth) throws Exception {
  49. auth.authenticationProvider(phoneAuthenticationProvider());
  50. auth.authenticationProvider(daoAuthenticationProvider());
  51. }
  52. @Bean
  53. public DaoAuthenticationProvider daoAuthenticationProvider(){
  54. DaoAuthenticationProvider provider1 = new DaoAuthenticationProvider();
  55. // 设置userDetailsService
  56. provider1.setUserDetailsService(ssoUserDetailsService);
  57. // 禁止隐藏用户未找到异常
  58. provider1.setHideUserNotFoundExceptions(false);
  59. // 使用BCrypt进行密码的hash
  60. provider1.setPasswordEncoder(passwordEncode());
  61. return provider1;
  62. }
  63. @Bean
  64. public PhoneAuthenticationProvider phoneAuthenticationProvider(){
  65. PhoneAuthenticationProvider provider = new PhoneAuthenticationProvider();
  66. // 设置userDetailsService
  67. provider.setUserDetailsService(phoneUserDetailService);
  68. // 禁止隐藏用户未找到异常
  69. provider.setHideUserNotFoundExceptions(false);
  70. return provider;
  71. }
  72. @Override
  73. @Bean
  74. public AuthenticationManager authenticationManager() throws Exception {
  75. return super.authenticationManager();
  76. }
  77. /**
  78. * 手机验证码登陆过滤器
  79. * @return
  80. */
  81. @Bean
  82. public PhoneLoginAuthenticationFilter getPhoneLoginAuthenticationFilter() {
  83. PhoneLoginAuthenticationFilter filter = new PhoneLoginAuthenticationFilter();
  84. try {
  85. filter.setAuthenticationManager(this.authenticationManagerBean());
  86. } catch (Exception e) {
  87. e.printStackTrace();
  88. }
  89. filter.setAuthenticationSuccessHandler(myLoginAuthSuccessHandler);
  90. filter.setAuthenticationFailureHandler(new SimpleUrlAuthenticationFailureHandler("/login?error"));
  91. return filter;
  92. }

}
配置好了

本文代码参考 https://github.com/fp2952/spr... 来实现 本人已经验证

文章版权归作者所有,未经允许请勿转载,若此文章存在违规行为,您可以联系管理员删除。

转载请注明本文地址:https://www.ucloud.cn/yun/73061.html

相关文章

  • Spring Security Oauth2.0 实现短信验证码登录

    摘要:验证码的发放校验逻辑比较简单,方法后通过全局判断请求中是否和手机号匹配集合,重点逻辑是令牌的参数 spring security oauth2 登录过程详解 ​ showImg(https://segmentfault.com/img/remote/1460000012811024); ​ 定义手机号登录令牌 /** * @author lengleng * @date 2018/...

    陆斌 评论0 收藏0
  • Spring Security OAuth2 优雅的集成短信验证码登录以及第三方登录

    摘要:前言基于做微服务架构分布式系统时,作为认证的业内标准,也提供了全套的解决方案来支持在环境下使用,提供了开箱即用的组件。 前言 基于SpringCloud做微服务架构分布式系统时,OAuth2.0作为认证的业内标准,Spring Security OAuth2也提供了全套的解决方案来支持在Spring Cloud/Spring Boot环境下使用OAuth2.0,提供了开箱即用的组件。但...

    yck 评论0 收藏0
  • 前后端分离项目 — 基于SpringSecurity OAuth2.0用户认证

    摘要:前言现在的好多项目都是基于移动端以及前后端分离的项目,之前基于的前后端放到一起的项目已经慢慢失宠并淡出我们视线,尤其是当基于的微服务架构以及单页面应用流行起来后,情况更甚。使用生成是什么请自行百度。 1、前言 现在的好多项目都是基于APP移动端以及前后端分离的项目,之前基于Session的前后端放到一起的项目已经慢慢失宠并淡出我们视线,尤其是当基于SpringCloud的微服务架构以及...

    QLQ 评论0 收藏0
  • 聊聊二维码登录

    摘要:场景主要的场景有如下几个扫二维码登录版系统比如微信版,在手机端微信登录的前提下,扫二维码确认,自动登录网页版。小结二维码扫描登录是个挺潮流的功能,这要求既有系统增加改造,也要求针对这种形式的登录带来潜在的攻击进行安全防范。 序 本文主要来研究一下二维码登录的相关场景和原理。 场景 主要的场景有如下几个: app扫二维码登录pc版系统 比如微信web版,在手机端微信登录的前提下,扫二维码...

    Tikitoo 评论0 收藏0
  • 说一说几种登录认证方式,你用的哪一种

    摘要:登录认证几乎是任何一个系统的标配,系统客户端等,好多都需要注册登录授权认证。假设我们开发了一个电商平台,并集成了微信登录,以这个场景为例,说一下的工作原理。微信网页授权是授权码模式的授权模式。 登录认证几乎是任何一个系统的标配,web 系统、APP、PC 客户端等,好多都需要注册、登录、授权认证。 场景说明 以一个电商系统,假设淘宝为例,如果我们想要下单,首先需要注册一个账号。拥有了账...

    idealcn 评论0 收藏0

发表评论

0条评论

最新活动
阅读需要支付1元查看
<