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

本文介绍了Spring Security Oauth2.0 实现短信验证码登录示例,分享给大家,具体如下:

定义手机号登录令牌

/**
 * @author lengleng
 * @date 2018/1/9
 * 手机号登录令牌
 */
public class MobileAuthenticationToken extends AbstractAuthenticationToken {

  private static final long serialVersionUID = SpringSecurityCoreVersion.SERIAL_VERSION_UID;

  private final Object principal;

  public MobileAuthenticationToken(String mobile) {
    super(null);
    this.principal = mobile;
    setAuthenticated(false);
  }

  public MobileAuthenticationToken(Object principal,
                   Collection<? extends GrantedAuthority> authorities) {
    super(authorities);
    this.principal = principal;
    super.setAuthenticated(true);
  }

  public Object getPrincipal() {
    return this.principal;
  }

  @Override
  public Object getCredentials() {
    return null;
  }

  public void setAuthenticated(boolean isAuthenticated) throws IllegalArgumentException {
    if (isAuthenticated) {
      throw new IllegalArgumentException(
          "Cannot set this token to trusted - use constructor which takes a GrantedAuthority list instead");
    }

    super.setAuthenticated(false);
  }

  @Override
  public void eraseCredentials() {
    super.eraseCredentials();
  }
}

手机号登录校验逻辑

/**
 * @author lengleng
 * @date 2018/1/9
 * 手机号登录校验逻辑
 */
public class MobileAuthenticationProvider implements AuthenticationProvider {
  private UserService userService;

  @Override
  public Authentication authenticate(Authentication authentication) throws AuthenticationException {
    MobileAuthenticationToken mobileAuthenticationToken = (MobileAuthenticationToken) authentication;
    UserVo userVo = userService.findUserByMobile((String) mobileAuthenticationToken.getPrincipal());

    UserDetailsImpl userDetails = buildUserDeatils(userVo);
    if (userDetails == null) {
      throw new InternalAuthenticationServiceException("手机号不存在:" + mobileAuthenticationToken.getPrincipal());
    }

    MobileAuthenticationToken authenticationToken = new MobileAuthenticationToken(userDetails, userDetails.getAuthorities());
    authenticationToken.setDetails(mobileAuthenticationToken.getDetails());
    return authenticationToken;
  }

  private UserDetailsImpl buildUserDeatils(UserVo userVo) {
    return new UserDetailsImpl(userVo);
  }

  @Override
  public boolean supports(Class<?> authentication) {
    return MobileAuthenticationToken.class.isAssignableFrom(authentication);
  }

  public UserService getUserService() {
    return userService;
  }

  public void setUserService(UserService userService) {
    this.userService = userService;
  }
}

登录过程filter处理

/**
 * @author lengleng
 * @date 2018/1/9
 * 手机号登录验证filter
 */
public class MobileAuthenticationFilter extends AbstractAuthenticationProcessingFilter {
  public static final String SPRING_SECURITY_FORM_MOBILE_KEY = "mobile";

  private String mobileParameter = SPRING_SECURITY_FORM_MOBILE_KEY;
  private boolean postOnly = true;

  public MobileAuthenticationFilter() {
    super(new AntPathRequestMatcher(SecurityConstants.MOBILE_TOKEN_URL, "POST"));
  }

  public Authentication attemptAuthentication(HttpServletRequest request,
                        HttpServletResponse response) throws AuthenticationException {
    if (postOnly && !request.getMethod().equals(HttpMethod.POST.name())) {
      throw new AuthenticationServiceException(
          "Authentication method not supported: " + request.getMethod());
    }

    String mobile = obtainMobile(request);

    if (mobile == null) {
      mobile = "";
    }

    mobile = mobile.trim();

    MobileAuthenticationToken mobileAuthenticationToken = new MobileAuthenticationToken(mobile);

    setDetails(request, mobileAuthenticationToken);

    return this.getAuthenticationManager().authenticate(mobileAuthenticationToken);
  }

  protected String obtainMobile(HttpServletRequest request) {
    return request.getParameter(mobileParameter);
  }

  protected void setDetails(HttpServletRequest request,
               MobileAuthenticationToken authRequest) {
    authRequest.setDetails(authenticationDetailsSource.buildDetails(request));
  }

  public void setPostOnly(boolean postOnly) {
    this.postOnly = postOnly;
  }

  public String getMobileParameter() {
    return mobileParameter;
  }

  public void setMobileParameter(String mobileParameter) {
    this.mobileParameter = mobileParameter;
  }

  public boolean isPostOnly() {
    return postOnly;
  }
}

生产token 位置

/**
 * @author lengleng
 * @date 2018/1/8
 * 手机号登录成功,返回oauth token
 */
@Component
public class MobileLoginSuccessHandler implements org.springframework.security.web.authentication.AuthenticationSuccessHandler {
  private Logger logger = LoggerFactory.getLogger(getClass());
  @Autowired
  private ObjectMapper objectMapper;
  @Autowired
  private ClientDetailsService clientDetailsService;
  @Autowired
  private AuthorizationServerTokenServices authorizationServerTokenServices;

  @Override
  public void onAuthenticationSuccess(HttpServletRequest request, HttpServletResponse response, Authentication authentication) {
    String header = request.getHeader("Authorization");

    if (header == null || !header.startsWith("Basic ")) {
      throw new UnapprovedClientAuthenticationException("请求头中client信息为空");
    }

    try {
      String[] tokens = extractAndDecodeHeader(header);
      assert tokens.length == 2;
      String clientId = tokens[0];
      String clientSecret = tokens[1];

      JSONObject params = new JSONObject();
      params.put("clientId", clientId);
      params.put("clientSecret", clientSecret);
      params.put("authentication", authentication);

      ClientDetails clientDetails = clientDetailsService.loadClientByClientId(clientId);
      TokenRequest tokenRequest = new TokenRequest(MapUtil.newHashMap(), clientId, clientDetails.getScope(), "mobile");
      OAuth2Request oAuth2Request = tokenRequest.createOAuth2Request(clientDetails);

      OAuth2Authentication oAuth2Authentication = new OAuth2Authentication(oAuth2Request, authentication);
      OAuth2AccessToken oAuth2AccessToken = authorizationServerTokenServices.createAccessToken(oAuth2Authentication);
      logger.info("获取token 成功:{}", oAuth2AccessToken.getValue());

      response.setCharacterEncoding(CommonConstant.UTF8);
      response.setContentType(CommonConstant.CONTENT_TYPE);
      PrintWriter printWriter = response.getWriter();
      printWriter.append(objectMapper.writeValueAsString(oAuth2AccessToken));
    } catch (IOException e) {
      throw new BadCredentialsException(
          "Failed to decode basic authentication token");
    }
  }

  /**
   * Decodes the header into a username and password.
   *
   * @throws BadCredentialsException if the Basic header is not present or is not valid
   *                 Base64
   */
  private String[] extractAndDecodeHeader(String header)
      throws IOException {

    byte[] base64Token = header.substring(6).getBytes("UTF-8");
    byte[] decoded;
    try {
      decoded = Base64.decode(base64Token);
    } catch (IllegalArgumentException e) {
      throw new BadCredentialsException(
          "Failed to decode basic authentication token");
    }

    String token = new String(decoded, CommonConstant.UTF8);

    int delim = token.indexOf(":");

    if (delim == -1) {
      throw new BadCredentialsException("Invalid basic authentication token");
    }
    return new String[]{token.substring(0, delim), token.substring(delim + 1)};
  }
}

配置以上自定义

//**
 * @author lengleng
 * @date 2018/1/9
 * 手机号登录配置入口
 */
@Component
public class MobileSecurityConfigurer extends SecurityConfigurerAdapter<DefaultSecurityFilterChain, HttpSecurity> {
  @Autowired
  private MobileLoginSuccessHandler mobileLoginSuccessHandler;
  @Autowired
  private UserService userService;

  @Override
  public void configure(HttpSecurity http) throws Exception {
    MobileAuthenticationFilter mobileAuthenticationFilter = new MobileAuthenticationFilter();
    mobileAuthenticationFilter.setAuthenticationManager(http.getSharedObject(AuthenticationManager.class));
    mobileAuthenticationFilter.setAuthenticationSuccessHandler(mobileLoginSuccessHandler);

    MobileAuthenticationProvider mobileAuthenticationProvider = new MobileAuthenticationProvider();
    mobileAuthenticationProvider.setUserService(userService);
    http.authenticationProvider(mobileAuthenticationProvider)
        .addFilterAfter(mobileAuthenticationFilter, UsernamePasswordAuthenticationFilter.class);
  }
}

在spring security 配置 上边定一个的那个聚合配置

/**
 * @author lengleng
 * @date 2018年01月09日14:01:25
 * 认证服务器开放接口配置
 */
@Configuration
@EnableResourceServer
public class ResourceServerConfiguration extends ResourceServerConfigurerAdapter {
  @Autowired
  private FilterUrlsPropertiesConifg filterUrlsPropertiesConifg;
  @Autowired
  private MobileSecurityConfigurer mobileSecurityConfigurer;

  @Override
  public void configure(HttpSecurity http) throws Exception {
    registry
        .antMatchers("/mobile/token").permissionAll()
        .anyRequest().authenticated()
        .and()
        .csrf().disable();
    http.apply(mobileSecurityConfigurer);
  }
}

使用

代码如下:

curl -H "Authorization:Basic cGlnOnBpZw==" -d "grant_type=mobile&scope=server&mobile=17034642119&code=" http://localhost:9999/auth/mobile/token

源码

请参考gitee.com/log4j/

基于Spring Cloud、Spring Security Oauth2.0开发企业级认证与授权,提供常见服务监控、链路追踪、日志分析、缓存管理、任务调度等实现

整个逻辑是参考spring security 自身的 usernamepassword 登录模式实现,可以参考其源码。

验证码的发放、校验逻辑比较简单,方法后通过全局fiter 判断请求中code 是否和 手机号匹配集合,重点逻辑是令牌的参数

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持我们。

您可能感兴趣的文章:

  • spring security4 添加验证码的示例代码
(0)

相关推荐

  • spring security4 添加验证码的示例代码

    spring security是一个很大的模块,本文中只涉及到了自定义参数的认证.spring security默认的验证参数只有username和password,一般来说都是不够用的.由于时间过太久,有些忘,可能有少许遗漏.好了,不废话. spring以及spring security配置采用javaConfig,版本依次为4.2.5,4.0.4 总体思路:自定义EntryPoint,添加自定义参数扩展AuthenticationToken以及AuthenticationProvider进行

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

    本文介绍了Spring Security Oauth2.0 实现短信验证码登录示例,分享给大家,具体如下: 定义手机号登录令牌 /** * @author lengleng * @date 2018/1/9 * 手机号登录令牌 */ public class MobileAuthenticationToken extends AbstractAuthenticationToken { private static final long serialVersionUID = SpringSecur

  • Spring Security OAuth2集成短信验证码登录以及第三方登录

    前言 基于SpringCloud做微服务架构分布式系统时,OAuth2.0作为认证的业内标准,Spring Security OAuth2也提供了全套的解决方案来支持在Spring Cloud/Spring Boot环境下使用OAuth2.0,提供了开箱即用的组件.但是在开发过程中我们会发现由于Spring Security OAuth2的组件特别全面,这样就导致了扩展很不方便或者说是不太容易直指定扩展的方案,例如: 图片验证码登录 短信验证码登录 微信小程序登录 第三方系统登录 CAS单点登录

  • Spring Security 实现短信验证码登录功能

    之前文章都是基于用户名密码登录,第六章图形验证码登录其实还是用户名密码登录,只不过多了一层图形验证码校验而已:Spring Security默认提供的认证流程就是用户名密码登录,整个流程都已经固定了,虽然提供了一些接口扩展,但是有些时候我们就需要有自己特殊的身份认证逻辑,比如用短信验证码登录,它和用户名密码登录的逻辑是不一样的,这时候就需要重新写一套身份认证逻辑. 开发短信验证码接口 获取验证码 短信验证码的发送获取逻辑和图片验证码类似,这里直接贴出代码. @GetMapping("/code/

  • swift 3.0 实现短信验证码倒计时功能

    下面一段代码给大家分享swift 3.0 实现短信验证码倒计时功能,具体实例代码如下所示: class TCCountDown { private var countdownTimer: Timer? var codeBtn = UIButton() private var remainingSeconds: Int = 0 { willSet { codeBtn.setTitle("重新获取\(newValue)秒", for: .normal) if newValue <=

  • C#代码实现短信验证码接口示例

    本文实例为大家分享了C#实现短信验证码接口示例,供大家参考,具体内容如下 using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Net.Security; using System.Security.Cryptography.X509Certificates; using System.Net; using System.IO; using System

  • SpringBoot + SpringSecurity 短信验证码登录功能实现

    实现原理 在之前的文章中,我们介绍了普通的帐号密码登录的方式: SpringBoot + Spring Security 基本使用及个性化登录配置. 但是现在还有一种常见的方式,就是直接通过手机短信验证码登录,这里就需要自己来做一些额外的工作了. 对SpringSecurity认证流程详解有一定了解的都知道,在帐号密码认证的过程中,涉及到了以下几个类:UsernamePasswordAuthenticationFilter(用于请求参数获取),UsernamePasswordAuthentica

  • 基于 antd pro 的短信验证码登录功能(流程分析)

    概要 最近使用 antd pro 开发项目时遇到个新的需求, 就是在登录界面通过短信验证码来登录, 不使用之前的用户名密码之类登录方式. 这种方式虽然增加了额外的短信费用, 但是对于安全性确实提高了不少. antd 中并没有自带能够倒计时的按钮, 但是 antd pro 的 ProForm components 中倒是提供了针对短信验证码相关的组件. 组件说明可参见: https://procomponents.ant.design/components/form 整体流程 通过短信验证码登录的

  • Java实现短信验证码的示例代码

    目录 项目需求 需求来由 代码实现 发送验证码方法 注册方法 忘记密码 前端代码 编码中遇到的问题 如何改进 短信验证码相信大家都不陌生吗,但是短信验证码怎么生成的你真的了解吗,本文揭示本人项目中对短信验证码的. 项目需求 用户注册/忘记密码添加短信验证码 需求来由 登录注册页面需要确保用户同一个手机号只关联一个账号确保非人为操作,避免系统用户信息紊乱增加系统安全性 代码实现 同事提供了WebService接口,很好,之前没调过,又增加了困难. 这边用的阿里云的短信服务,废话少说上图,呸,上代码

  • Redis实现短信验证码登录的示例代码

    目录 效果图 pom.xml applicatoin.yml Redis配置类 controller serviceImpl mapper 效果图 发送验证码 输入手机号.密码以及验证码完成登录操作 pom.xml 核心依赖 <dependencies> <dependency> <groupId>cn.hutool</groupId> <artifactId>hutool-all</artifactId> <version&g

  • Android开发中通过手机号+短信验证码登录的实例代码

    首先,需要一个电话号码,目前很多账户都是将账户名设置成手机号,然后点击按钮获取手机验证码. 其次,你需要后台给你手机短信的验证接口,各个公司用的不一样,这个身为前端,不需要你来考虑,你只要让你后台给你写好接口,你直接调用就好了. activity_login.xml <?xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns:android="http://schemas.andr

随机推荐