溫馨提示×

溫馨提示×

您好,登錄后才能下訂單哦!

密碼登錄×
登錄注冊×
其他方式登錄
點擊 登錄注冊 即表示同意《億速云用戶服務條款》

Spring Security Oauth2.0 實現(xiàn)短信驗證碼登錄示例

發(fā)布時間:2020-10-09 21:07:13 來源:腳本之家 閱讀:200 作者:冷冷gg 欄目:編程語言

本文介紹了Spring Security Oauth3.0 實現(xiàn)短信驗證碼登錄示例,分享給大家,具體如下:

Spring Security Oauth2.0 實現(xiàn)短信驗證碼登錄示例

定義手機號登錄令牌

/**
 * @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;
  }
}

生產(chǎn)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");
      OAuth3Request oAuth3Request = tokenRequest.createOAuth3Request(clientDetails);

      OAuth3Authentication oAuth3Authentication = new OAuth3Authentication(oAuth3Request, authentication);
      OAuth3AccessToken oAuth3AccessToken = authorizationServerTokenServices.createAccessToken(oAuth3Authentication);
      logger.info("獲取token 成功:{}", oAuth3AccessToken.getValue());

      response.setCharacterEncoding(CommonConstant.UTF8);
      response.setContentType(CommonConstant.CONTENT_TYPE);
      PrintWriter printWriter = response.getWriter();
      printWriter.append(objectMapper.writeValueAsString(oAuth3AccessToken));
    } 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 Oauth3.0開發(fā)企業(yè)級認證與授權,提供常見服務監(jiān)控、鏈路追蹤、日志分析、緩存管理、任務調度等實現(xiàn)

整個邏輯是參考spring security 自身的 usernamepassword 登錄模式實現(xiàn),可以參考其源碼。

驗證碼的發(fā)放、校驗邏輯比較簡單,方法后通過全局fiter 判斷請求中code 是否和 手機號匹配集合,重點邏輯是令牌的參數(shù)

以上就是本文的全部內容,希望對大家的學習有所幫助,也希望大家多多支持億速云。

向AI問一下細節(jié)

免責聲明:本站發(fā)布的內容(圖片、視頻和文字)以原創(chuàng)、轉載和分享為主,文章觀點不代表本網(wǎng)站立場,如果涉及侵權請聯(lián)系站長郵箱:is@yisu.com進行舉報,并提供相關證據(jù),一經(jīng)查實,將立刻刪除涉嫌侵權內容。

AI