最新国产好看的视频,伊人天堂AV在线,国产Aaaaaa视频,蜜臀视频在线观看一区,人妻av色图,密臀久久久精品影片,青青视频免费观看毛片,久草在线观看视,国产三级精品色情在线

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

 更新時(shí)間:2018年01月12日 10:54:35   作者:冷冷gg  
本篇文章主要介紹了Spring Security Oauth2.0 實(shí)現(xiàn)短信驗(yàn)證碼登錄示例,具有一定的參考價(jià)值,感興趣的小伙伴們可以參考一下

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

定義手機(jī)號(hào)登錄令牌

/**
 * @author lengleng
 * @date 2018/1/9
 * 手機(jī)號(hào)登錄令牌
 */
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();
  }
}

手機(jī)號(hào)登錄校驗(yàn)邏輯

/**
 * @author lengleng
 * @date 2018/1/9
 * 手機(jī)號(hào)登錄校驗(yàn)邏輯
 */
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("手機(jī)號(hào)不存在:" + 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;
  }
}

登錄過(guò)程filter處理

/**
 * @author lengleng
 * @date 2018/1/9
 * 手機(jī)號(hào)登錄驗(yàn)證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
 * 手機(jī)號(hào)登錄成功,返回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("請(qǐng)求頭中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
 * 手機(jī)號(hào)登錄配置入口
 */
@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 配置 上邊定一個(gè)的那個(gè)聚合配置

/**
 * @author lengleng
 * @date 2018年01月09日14:01:25
 * 認(rèn)證服務(wù)器開(kāi)放接口配置
 */
@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);
  }
}

使用

復(fù)制代碼 代碼如下:

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

源碼

請(qǐng)參考gitee.com/log4j/

基于Spring Cloud、Spring Security Oauth2.0開(kāi)發(fā)企業(yè)級(jí)認(rèn)證與授權(quán),提供常見(jiàn)服務(wù)監(jiān)控、鏈路追蹤、日志分析、緩存管理、任務(wù)調(diào)度等實(shí)現(xiàn)

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

驗(yàn)證碼的發(fā)放、校驗(yàn)邏輯比較簡(jiǎn)單,方法后通過(guò)全局fiter 判斷請(qǐng)求中code 是否和 手機(jī)號(hào)匹配集合,重點(diǎn)邏輯是令牌的參數(shù)

以上就是本文的全部?jī)?nèi)容,希望對(duì)大家的學(xué)習(xí)有所幫助,也希望大家多多支持腳本之家。

相關(guān)文章

  • Spring?Security權(quán)限管理實(shí)現(xiàn)接口動(dòng)態(tài)權(quán)限控制

    Spring?Security權(quán)限管理實(shí)現(xiàn)接口動(dòng)態(tài)權(quán)限控制

    這篇文章主要為大家介紹了Spring?Security權(quán)限管理實(shí)現(xiàn)接口動(dòng)態(tài)權(quán)限控制,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進(jìn)步,早日升職加薪
    2022-06-06
  • Intellij IDEA 2017新特性之Spring Boot相關(guān)特征介紹

    Intellij IDEA 2017新特性之Spring Boot相關(guān)特征介紹

    Intellij IDEA 2017.2.2版本針對(duì)Springboot設(shè)置了一些特性,本篇文章給大家簡(jiǎn)單介紹一下如何使用這些特性,需要的朋友參考下吧
    2018-01-01
  • java構(gòu)造http請(qǐng)求的幾種方式(附源碼)

    java構(gòu)造http請(qǐng)求的幾種方式(附源碼)

    本文主要介紹了java構(gòu)造http請(qǐng)求的幾種方式,文中通過(guò)示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來(lái)一起學(xué)習(xí)學(xué)習(xí)吧
    2023-02-02
  • Linux下java環(huán)境配置圖文方法

    Linux下java環(huán)境配置圖文方法

    這篇文章主要介紹了Linux下java環(huán)境配置圖文方法,需要的朋友可以參考下
    2023-06-06
  • Java lastIndexOf類使用方法原理解析

    Java lastIndexOf類使用方法原理解析

    這篇文章主要介紹了Java lastIndexOf類使用方法解析,文中通過(guò)示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友可以參考下
    2020-07-07
  • 詳解Spring MVC的異步模式(高性能的關(guān)鍵)

    詳解Spring MVC的異步模式(高性能的關(guān)鍵)

    本篇文章主要介紹了詳解Spring MVC的異步模式(高性能的關(guān)鍵),小編覺(jué)得挺不錯(cuò)的,現(xiàn)在分享給大家,也給大家做個(gè)參考。一起跟隨小編過(guò)來(lái)看看吧
    2017-02-02
  • 關(guān)于webLucene 安裝方法

    關(guān)于webLucene 安裝方法

    webLucene是一個(gè)基于開(kāi)源項(xiàng)目lucene實(shí)現(xiàn)站內(nèi)搜索的工具,關(guān)于它的安裝,百度得到的大多是一樣的,按照步驟也能正確安裝并運(yùn)行,需要注意的問(wèn)題是
    2009-06-06
  • TransmittableThreadLocal解決線程間上下文傳遞煩惱

    TransmittableThreadLocal解決線程間上下文傳遞煩惱

    這篇文章主要為大家介紹了TransmittableThreadLocal解決線程間上下文傳遞煩惱詳解,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進(jìn)步,早日升職加薪
    2022-11-11
  • SpringBoot中Redisson延遲隊(duì)列的示例

    SpringBoot中Redisson延遲隊(duì)列的示例

    延時(shí)隊(duì)列是一種常見(jiàn)的需求,延時(shí)隊(duì)列允許我們延遲處理某些任務(wù),本文主要介紹了Redisson延遲隊(duì)列的示例,具有一定的參考價(jià)值,感興趣的可以了解一下
    2024-06-06
  • springboot+thymeleaf+layui的實(shí)現(xiàn)示例

    springboot+thymeleaf+layui的實(shí)現(xiàn)示例

    本文主要介紹了springboot+thymeleaf+layui的實(shí)現(xiàn)示例,文中通過(guò)示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來(lái)一起學(xué)習(xí)學(xué)習(xí)吧
    2023-12-12

最新評(píng)論

北京市| 南涧| 博爱县| 淮南市| 施秉县| 卢湾区| 樟树市| 阳朔县| 隆安县| 巴塘县| 黑水县| 开平市| 蕉岭县| 黎平县| 梧州市| 安乡县| 宿迁市| 沁水县| 奈曼旗| 榆林市| 共和县| 务川| 黄平县| 株洲市| 云阳县| 姚安县| 蓬安县| 大丰市| 沿河| 合川市| 吉林省| 永胜县| 朔州市| 宜州市| 丰原市| 黄山市| 祁阳县| 莎车县| 交口县| 淅川县| 屯昌县|