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

Spring?Security短信驗(yàn)證碼實(shí)現(xiàn)詳解

 更新時(shí)間:2021年11月23日 11:52:36   作者:大忽悠愛忽悠  
本文主要介紹了Spring?Security短信驗(yàn)證碼的實(shí)現(xiàn)詳解,文中通過示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧

需求

  • 輸入手機(jī)號(hào)碼,點(diǎn)擊獲取按鈕,服務(wù)端接受請(qǐng)求發(fā)送短信
  • 用戶輸入驗(yàn)證碼點(diǎn)擊登錄
  • 手機(jī)號(hào)碼必須屬于系統(tǒng)的注冊(cè)用戶,并且唯一
  • 手機(jī)號(hào)與驗(yàn)證碼正確性及其關(guān)系必須經(jīng)過校驗(yàn)
  • 登錄后用戶具有手機(jī)號(hào)對(duì)應(yīng)的用戶的角色及權(quán)限

實(shí)現(xiàn)步驟

  • 獲取短信驗(yàn)證碼
  • 短信驗(yàn)證碼校驗(yàn)過濾器
  • 短信驗(yàn)證碼登錄認(rèn)證過濾器
  • 綜合配置

獲取短信驗(yàn)證碼

在這一步我們需要寫一個(gè)controller接收用戶的獲取驗(yàn)證碼請(qǐng)求。注意:一定要為“/smscode”訪問路徑配置為permitAll訪問權(quán)限,因?yàn)閟pring security默認(rèn)攔截所有路徑,除了默認(rèn)配置的/login請(qǐng)求,只有經(jīng)過登錄認(rèn)證過后的請(qǐng)求才會(huì)默認(rèn)可以訪問。

@Slf4j
@RestController
public class SmsController {

    @Autowired
    private UserDetailsService userDetailsService;

    //獲取短信驗(yàn)證碼
    @RequestMapping(value="/smscode",method = RequestMethod.GET)
    public String sms(@RequestParam String mobile, HttpSession session) throws IOException {
         //先從數(shù)據(jù)庫中查找,判斷對(duì)應(yīng)的手機(jī)號(hào)是否存在
        UserDetails userDetails = userDetailsService.loadUserByUsername(mobile);
        //這個(gè)地方userDetailsService如果使用spring security提供的話,找不到用戶名會(huì)直接拋出異常,走不到這里來
        //即直接去了登錄失敗的處理器
        if(userDetails == null){
            return "您輸入的手機(jī)號(hào)不是系統(tǒng)注冊(cè)用戶";
        }
        //commons-lang3包下的工具類,生成指定長度為4的隨機(jī)數(shù)字字符串
        String randomNumeric = RandomStringUtils.randomNumeric(4);
        //驗(yàn)證碼,過期時(shí)間,手機(jī)號(hào)
        SmsCode smsCode = new SmsCode(randomNumeric,60,mobile);
        //TODO 此處調(diào)用驗(yàn)證碼發(fā)送服務(wù)接口
        //這里只是模擬調(diào)用
        log.info(smsCode.getCode() + "=》" + mobile);

        //將驗(yàn)證碼存放到session中
        session.setAttribute("sms_key",smsCode);

        return "短信息已經(jīng)發(fā)送到您的手機(jī)";
    }
}

上文中我們只做了短信驗(yàn)證碼接口調(diào)用的模擬,沒有真正的向手機(jī)發(fā)送驗(yàn)證碼。此部分接口請(qǐng)結(jié)合短信發(fā)送服務(wù)提供商接口實(shí)現(xiàn)。

短信驗(yàn)證碼發(fā)送之后,將驗(yàn)證碼“謎底”保存在session中。

使用SmsCode封裝短信驗(yàn)證碼的謎底,用于后續(xù)登錄過程中進(jìn)行校驗(yàn)。

public class SmsCode {
    private String code;  //短信驗(yàn)證碼
    private LocalDateTime expireTime; //驗(yàn)證碼的過期時(shí)間
    private String mobile; //發(fā)送手機(jī)號(hào)

    public SmsCode(String code,int expireAfterSeconds,String mobile){
        this.code = code;
        this.expireTime = LocalDateTime.now().plusSeconds(expireAfterSeconds);
        this.mobile = mobile;
    }

    public boolean isExpired(){
        return  LocalDateTime.now().isAfter(expireTime);
    }

    public String getCode() {
        return code;
    }

    public String getMobile() {
       return mobile;
    }

}

前端初始化短信登錄界面

<h1>短信登陸</h1>
<form action="/smslogin" method="post">
    <span>手機(jī)號(hào)碼:</span><input type="text" name="mobile" id="mobile"> <br>
    <span>短信驗(yàn)證碼:</span><input type="text" name="smsCode" id="smsCode" >
    <input type="button" onclick="getSmsCode()" value="獲取"><br>
    <input type="button" onclick="smslogin()" value="登陸">
</form>

<script>

   function getSmsCode()
   {
     $.ajax({
       type: "GET",
       url: "/smscode",
        data:{"mobile":$("#mobile").val()},
       success: function (res) {
         console.log(res)
       },
       error: function (e) {
         console.log(e.responseText);
       }
     });
   }

    function smslogin() {
      var mobile = $("#mobile").val();
      var smsCode = $("#smsCode").val();
      if (mobile === "" || smsCode === "") {
        alert('手機(jī)號(hào)和短信驗(yàn)證碼均不能為空');
        return;
      }
      $.ajax({
        type: "POST",
        url: "/smslogin",
        data: {
          "mobile": mobile,
          "smsCode": smsCode
        },
        success: function (res) {
          console.log(res)
        },
        error: function (e) {
          console.log(e.responseText);
        }
      });
    }
</script>

spring security配置類

@Configuration
public class SecurityConfig extends WebSecurityConfigurerAdapter {

   private ObjectMapper objectMapper=new ObjectMapper();

   @Resource
   private CaptchaCodeFilter captchaCodeFilter;

   @Bean
   PasswordEncoder passwordEncoder() {
      return NoOpPasswordEncoder.getInstance();
   }

   @Override
   public void configure(WebSecurity web) throws Exception {
      web.ignoring().antMatchers("/js/**", "/css/**","/images/**");
   }

   //數(shù)據(jù)源注入
   @Autowired
   DataSource dataSource;

   //持久化令牌配置
   @Bean
   JdbcTokenRepositoryImpl jdbcTokenRepository() {
      JdbcTokenRepositoryImpl jdbcTokenRepository = new JdbcTokenRepositoryImpl();
      jdbcTokenRepository.setDataSource(dataSource);
      return jdbcTokenRepository;
   }


   //用戶配置
   @Override
   @Bean
   protected UserDetailsService userDetailsService() {
      JdbcUserDetailsManager manager = new JdbcUserDetailsManager();
      manager.setDataSource(dataSource);
      if (!manager.userExists("dhy")) {
         manager.createUser(User.withUsername("dhy").password("123").roles("admin").build());
      }
      if (!manager.userExists("大忽悠")) {
         manager.createUser(User.withUsername("大忽悠").password("123").roles("user").build());
      }
      //模擬電話號(hào)碼
      if (!manager.userExists("123456789")) {
         manager.createUser(User.withUsername("123456789").password("").roles("user").build());
      }
      return manager;
   }

   @Override
   protected void configure(HttpSecurity http) throws Exception {
      http.//處理需要認(rèn)證的請(qǐng)求
              authorizeRequests()
              //放行請(qǐng)求,前提:是對(duì)應(yīng)的角色才行
              .antMatchers("/admin/**").hasRole("admin")
              .antMatchers("/user/**").hasRole("user")
              //無需登錄憑證,即可放行
              .antMatchers("/kaptcha","/smscode").permitAll()//放行驗(yàn)證碼的顯示請(qǐng)求
              //剩余的請(qǐng)求都需要認(rèn)證才可以放行
              .anyRequest().authenticated()
              .and()
              //表單形式登錄的個(gè)性化配置
              .formLogin()
              .loginPage("/login.html").permitAll()
              .loginProcessingUrl("/login").permitAll()
              .defaultSuccessUrl("/main.html")//可以記住上一次的請(qǐng)求路徑
              //登錄失敗的處理器
              .failureHandler(new MyFailHandler())
              .and()
              //退出登錄相關(guān)設(shè)置
              .logout()
              //退出登錄的請(qǐng)求,是再?zèng)]退出前發(fā)出的,因此此時(shí)還有登錄憑證
              //可以訪問
              .logoutUrl("/logout")
              //此時(shí)已經(jīng)退出了登錄,登錄憑證沒了
              //那么想要訪問非登錄頁面的請(qǐng)求,就必須保證這個(gè)請(qǐng)求無需憑證即可訪問
              .logoutSuccessUrl("/logout.html").permitAll()
              //退出登錄的時(shí)候,刪除對(duì)應(yīng)的cookie
              .deleteCookies("JSESSIONID")
              .and()
              //記住我相關(guān)設(shè)置
              .rememberMe()
              //預(yù)定義key相關(guān)設(shè)置,默認(rèn)是一串uuid
              .key("dhy")
              //令牌的持久化
              .tokenRepository(jdbcTokenRepository())
              .and()
              .addFilterBefore(captchaCodeFilter, UsernamePasswordAuthenticationFilter.class)
              //csrf關(guān)閉
              .csrf().disable();

   }

   //角色繼承
   @Bean
   RoleHierarchy roleHierarchy() {
      RoleHierarchyImpl hierarchy = new RoleHierarchyImpl();
      hierarchy.setHierarchy("ROLE_admin > ROLE_user");
      return hierarchy;
   }

}

短信驗(yàn)證碼校驗(yàn)過濾器

短信驗(yàn)證碼的校驗(yàn)過濾器,和圖片驗(yàn)證碼的驗(yàn)證實(shí)現(xiàn)原理是一致的。都是通過繼承OncePerRequestFilter實(shí)現(xiàn)一個(gè)Spring環(huán)境下的過濾器。其核心校驗(yàn)規(guī)則如下:

  • 用戶登錄時(shí)手機(jī)號(hào)不能為空
  • 用戶登錄時(shí)短信驗(yàn)證碼不能為空
  • 用戶登陸時(shí)在session中必須存在對(duì)應(yīng)的校驗(yàn)謎底(獲取驗(yàn)證碼時(shí)存放的)
  • 用戶登錄時(shí)輸入的短信驗(yàn)證碼必須和“謎底”中的驗(yàn)證碼一致
  • 用戶登錄時(shí)輸入的手機(jī)號(hào)必須和“謎底”中保存的手機(jī)號(hào)一致
  • 用戶登錄時(shí)輸入的手機(jī)號(hào)必須是系統(tǒng)注冊(cè)用戶的手機(jī)號(hào),并且唯一
@Component
public class SmsCodeValidateFilter extends OncePerRequestFilter {

    @Resource
    UserDetailsService userDetailsService;

    @Resource
    MyFailHandler myAuthenticationFailureHandler;

    @Override
    protected void doFilterInternal(HttpServletRequest request,
                                    HttpServletResponse response,
                                    FilterChain filterChain)
            throws ServletException, IOException {
       //該過濾器只負(fù)責(zé)攔截驗(yàn)證碼登錄的請(qǐng)求
       //并且請(qǐng)求必須是post
        if (request.getRequestURI().equals("/smslogin")
                && request.getMethod().equalsIgnoreCase("post")) {
            try {
                validate(new ServletWebRequest(request));

            }catch (AuthenticationException e){
                myAuthenticationFailureHandler.onAuthenticationFailure(
                        request,response,e);
                return;
            }
        }
        filterChain.doFilter(request,response);
    }

    private void validate(ServletWebRequest request) throws ServletRequestBindingException {
        HttpSession session = request.getRequest().getSession();
        //從session取出獲取驗(yàn)證碼時(shí),在session中存放驗(yàn)證碼相關(guān)信息的類
        SmsCode codeInSession = (SmsCode) session.getAttribute("sms_key");
        //取出用戶輸入的驗(yàn)證碼
        String codeInRequest = request.getParameter("smsCode");
        //取出用戶輸入的電話號(hào)碼
        String mobileInRequest = request.getParameter("mobile");
        
        //common-lang3包下的工具類
        if(StringUtils.isEmpty(mobileInRequest)){
            throw new SessionAuthenticationException("手機(jī)號(hào)碼不能為空!");
        }
        if(StringUtils.isEmpty(codeInRequest)){
            throw new SessionAuthenticationException("短信驗(yàn)證碼不能為空!");
        }
        if(Objects.isNull(codeInSession)){
            throw new SessionAuthenticationException("短信驗(yàn)證碼不存在!");
        }
        if(codeInSession.isExpired())
        {
            //從session中移除保存的驗(yàn)證碼相關(guān)信息
            session.removeAttribute("sms_key");
            throw new SessionAuthenticationException("短信驗(yàn)證碼已過期!");
        }
        if(!codeInSession.getCode().equals(codeInRequest)){
            throw new SessionAuthenticationException("短信驗(yàn)證碼不正確!");
        }

        if(!codeInSession.getMobile().equals(mobileInRequest)){
            throw new SessionAuthenticationException("短信發(fā)送目標(biāo)與該手機(jī)號(hào)不一致!");
        }
        //數(shù)據(jù)庫查詢當(dāng)前手機(jī)號(hào)是否注冊(cè)過
        UserDetails myUserDetails = userDetailsService.loadUserByUsername(mobileInRequest);
        if(Objects.isNull(myUserDetails)){
            throw new SessionAuthenticationException("您輸入的手機(jī)號(hào)不是系統(tǒng)的注冊(cè)用戶");
        }
        //校驗(yàn)完畢并且沒有拋出異常的情況下,移除session中保存的驗(yàn)證碼信息
        session.removeAttribute("sms_key");
    }
}

注意:一定要為"/smslogin"訪問路徑配置為permitAll訪問權(quán)限

到這里,我們可以講一下整體的短信驗(yàn)證登錄流程,如上面的時(shí)序圖。

  • 首先用戶發(fā)起“獲取短信驗(yàn)證碼”請(qǐng)求,SmsCodeController中調(diào)用短信服務(wù)商接口發(fā)送短信,并將短信發(fā)送的“謎底”保存在session中。
  • 當(dāng)用戶發(fā)起登錄請(qǐng)求,首先要經(jīng)過SmsCodeValidateFilter對(duì)謎底和用戶輸入進(jìn)行比對(duì),比對(duì)失敗則返回短信驗(yàn)證碼校驗(yàn)失敗
  • 當(dāng)短信驗(yàn)證碼校驗(yàn)成功,繼續(xù)執(zhí)行過濾器鏈中的SmsCodeAuthenticationFilter對(duì)用戶進(jìn)行認(rèn)證授權(quán)。

短信驗(yàn)證碼登錄認(rèn)證

我們可以仿照用戶密碼登錄的流程,完成相關(guān)類的動(dòng)態(tài)替換

由上圖可以看出,短信驗(yàn)證碼的登錄認(rèn)證邏輯和用戶密碼的登錄認(rèn)證流程是一樣的。所以:

SmsCodeAuthenticationFilter仿造UsernamePasswordAuthenticationFilter進(jìn)行開發(fā)

SmsCodeAuthenticationProvider仿造DaoAuthenticationProvider進(jìn)行開發(fā)。

模擬實(shí)現(xiàn):只不過將用戶名、密碼換成手機(jī)號(hào)進(jìn)行認(rèn)證,短信驗(yàn)證碼在此部分已經(jīng)沒有用了,因?yàn)槲覀冊(cè)赟msCodeValidateFilter已經(jīng)驗(yàn)證過了。

/**
 * 仿造UsernamePasswordAuthenticationFilter開發(fā)
 */
public class SmsCodeAuthenticationFilter extends AbstractAuthenticationProcessingFilter {

    public static final String SPRING_SECURITY_FORM_MOBILE_KEY = "mobile";
    private String mobileParameter = SPRING_SECURITY_FORM_MOBILE_KEY ;    //請(qǐng)求中攜帶手機(jī)號(hào)的參數(shù)名稱
    private boolean postOnly = true;    //指定當(dāng)前過濾器是否只處理POST請(qǐng)求
    //默認(rèn)處理的請(qǐng)求
    private static final AntPathRequestMatcher DEFAULT_ANT_PATH_REQUEST_MATCHER = new AntPathRequestMatcher("/smslogin", "POST");

    public SmsCodeAuthenticationFilter() {
        //指定當(dāng)前過濾器處理的請(qǐng)求
        super(DEFAULT_ANT_PATH_REQUEST_MATCHER);
    }

    //嘗試進(jìn)行認(rèn)證
    public Authentication attemptAuthentication(
            HttpServletRequest request,
            HttpServletResponse response)
            throws AuthenticationException {
        if (this.postOnly && !request.getMethod().equals("POST")) {
            throw new AuthenticationServiceException("Authentication method not supported: " + request.getMethod());
        } else {
            String mobile = this.obtainMobile(request);
            if (mobile == null) {
                mobile = "";
            }
            mobile = mobile.trim();
            //認(rèn)證前---手機(jī)號(hào)碼是認(rèn)證主體
            SmsCodeAuthenticationToken authRequest = new SmsCodeAuthenticationToken(mobile);
            //設(shè)置details---默認(rèn)是sessionid和remoteaddr
            this.setDetails(request, authRequest);
            return this.getAuthenticationManager().authenticate(authRequest);
        }
    }


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


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

    public void setMobileParameter(String mobileParameter) {
        Assert.hasText(mobileParameter, "Username parameter must not be empty or null");
        this.mobileParameter = mobileParameter;
    }


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

    public final String getMobileParameter() {
        return this.mobileParameter;
    }

}

認(rèn)證令牌也需要替換:

public class SmsCodeAuthenticationToken extends AbstractAuthenticationToken {
    private static final long serialVersionUID = SpringSecurityCoreVersion.SERIAL_VERSION_UID;

    //存放認(rèn)證信息,認(rèn)證之前存放手機(jī)號(hào),認(rèn)證之后存放登錄的用戶
    private final Object principal;

//認(rèn)證前
    public SmsCodeAuthenticationToken(String mobile) {
        super((Collection)null);
        this.principal = mobile;
        this.setAuthenticated(false);
    }

//認(rèn)證后,會(huì)設(shè)置相關(guān)的權(quán)限
    public SmsCodeAuthenticationToken(Object principal, Collection<? extends GrantedAuthority> authorities) {
        super(authorities);
        this.principal = principal;
        super.setAuthenticated(true);
    }

    public Object getCredentials() {
        return null;
    }

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

    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");
        } else {
            super.setAuthenticated(false);
        }
    }

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

當(dāng)前還需要提供能夠?qū)ξ覀儺?dāng)前自定義令牌對(duì)象起到認(rèn)證作用的provider,仿照DaoAuthenticationProvider

public class SmsCodeAuthenticationProvider implements AuthenticationProvider{


    private UserDetailsService userDetailsService;

    public UserDetailsService getUserDetailsService() {
        return userDetailsService;
    }

    public void setUserDetailsService(UserDetailsService userDetailsService) {
        this.userDetailsService = userDetailsService;
    }

    /**
     * 進(jìn)行身份認(rèn)證的邏輯
     * @param authentication    就是我們傳入的Token
     * @return
     * @throws AuthenticationException
     */
    @Override
    public Authentication authenticate(Authentication authentication) throws AuthenticationException {

        //利用UserDetailsService獲取用戶信息,拿到用戶信息后重新組裝一個(gè)已認(rèn)證的Authentication
        SmsCodeAuthenticationToken authenticationToken = (SmsCodeAuthenticationToken)authentication;
        UserDetails user = userDetailsService.loadUserByUsername((String) authenticationToken.getPrincipal());  //根據(jù)手機(jī)號(hào)碼拿到用戶信息
        if(user == null){
            throw new InternalAuthenticationServiceException("無法獲取用戶信息");
        }
        //設(shè)置新的認(rèn)證主體
        SmsCodeAuthenticationToken authenticationResult = new SmsCodeAuthenticationToken(user,user.getAuthorities());
        //copy details
        authenticationResult.setDetails(authenticationToken.getDetails());
        //返回新的令牌對(duì)象
        return authenticationResult;
    }

    /**
     * AuthenticationManager挑選一個(gè)AuthenticationProvider
     * 來處理傳入進(jìn)來的Token就是根據(jù)supports方法來判斷的
     * @param aClass
     * @return
     */
    @Override
    public boolean supports(Class<?> aClass) {
        //isAssignableFrom: 判斷當(dāng)前的Class對(duì)象所表示的類,
        // 是不是參數(shù)中傳遞的Class對(duì)象所表示的類的父類,超接口,或者是相同的類型。
        // 是則返回true,否則返回false。
        return SmsCodeAuthenticationToken.class.isAssignableFrom(aClass);
    }
}

配置類進(jìn)行綜合組裝

最后我們將以上實(shí)現(xiàn)進(jìn)行組裝,并將以上接口實(shí)現(xiàn)以配置的方式告知Spring Security。因?yàn)榕渲么a比較多,所以我們單獨(dú)抽取一個(gè)關(guān)于短信驗(yàn)證碼的配置類SmsCodeSecurityConfig,繼承自SecurityConfigurerAdapter。

@Component
public class SmsCodeSecurityConfig extends SecurityConfigurerAdapter<DefaultSecurityFilterChain, HttpSecurity> {

    @Resource
    private MyFailHandler myAuthenticationFailureHandler;

      //這里不能直接注入,否則會(huì)造成依賴注入的問題發(fā)生
    private UserDetailsService myUserDetailsService;

    @Resource
    private SmsCodeValidateFilter smsCodeValidateFilter;

    @Override
    public void configure(HttpSecurity http) throws Exception {

        SmsCodeAuthenticationFilter smsCodeAuthenticationFilter = new SmsCodeAuthenticationFilter();
        smsCodeAuthenticationFilter.setAuthenticationManager(http.getSharedObject(AuthenticationManager.class));
        //有則配置,無則不配置
        //smsCodeAuthenticationFilter.setAuthenticationSuccessHandler(myAuthenticationSuccessHandler);
        smsCodeAuthenticationFilter.setAuthenticationFailureHandler(myAuthenticationFailureHandler);

        // 獲取驗(yàn)證碼登錄令牌校驗(yàn)的提供者
        SmsCodeAuthenticationProvider smsCodeAuthenticationProvider = new SmsCodeAuthenticationProvider();
        smsCodeAuthenticationProvider.setUserDetailsService(myUserDetailsService);

        //在用戶密碼過濾器前面加入短信驗(yàn)證碼校驗(yàn)過濾器
        http.addFilterBefore(smsCodeValidateFilter, UsernamePasswordAuthenticationFilter.class);
        //在用戶密碼過濾器后面加入短信驗(yàn)證碼認(rèn)證授權(quán)過濾器        
        http.authenticationProvider(smsCodeAuthenticationProvider)
            .addFilterAfter(smsCodeAuthenticationFilter, UsernamePasswordAuthenticationFilter.class);

    }
}

該配置類可以用以下代碼,集成到SecurityConfig中。

完整配置

@Configuration
public class SecurityConfig extends WebSecurityConfigurerAdapter {

   private ObjectMapper objectMapper=new ObjectMapper();

   @Resource
   private CaptchaCodeFilter captchaCodeFilter;

   @Resource
   private SmsCodeSecurityConfig smsCodeSecurityConfig;

   @Bean
   PasswordEncoder passwordEncoder() {
      return NoOpPasswordEncoder.getInstance();
   }

   @Override
   public void configure(WebSecurity web) throws Exception {
      web.ignoring().antMatchers("/js/**", "/css/**","/images/**");
   }

   //數(shù)據(jù)源注入
   @Autowired
   DataSource dataSource;

   //持久化令牌配置
   @Bean
   JdbcTokenRepositoryImpl jdbcTokenRepository() {
      JdbcTokenRepositoryImpl jdbcTokenRepository = new JdbcTokenRepositoryImpl();
      jdbcTokenRepository.setDataSource(dataSource);
      return jdbcTokenRepository;
   }


   //用戶配置
   @Override
   @Bean
   protected UserDetailsService userDetailsService() {
      JdbcUserDetailsManager manager = new JdbcUserDetailsManager();
      manager.setDataSource(dataSource);
      if (!manager.userExists("dhy")) {
         manager.createUser(User.withUsername("dhy").password("123").roles("admin").build());
      }
      if (!manager.userExists("大忽悠")) {
         manager.createUser(User.withUsername("大忽悠").password("123").roles("user").build());
      }
      //模擬電話號(hào)碼
      if (!manager.userExists("123456789")) {
         manager.createUser(User.withUsername("123456789").password("").roles("user").build());
      }
      return manager;
   }

   @Override
   protected void configure(HttpSecurity http) throws Exception {

 //設(shè)置一下userDetailService
      smsCodeSecurityConfig.setMyUserDetailsService(userDetailsService());

      http.//處理需要認(rèn)證的請(qǐng)求
              authorizeRequests()
              //放行請(qǐng)求,前提:是對(duì)應(yīng)的角色才行
              .antMatchers("/admin/**").hasRole("admin")
              .antMatchers("/user/**").hasRole("user")
              //無需登錄憑證,即可放行
              .antMatchers("/kaptcha","/smscode","/smslogin").permitAll()//放行驗(yàn)證碼的顯示請(qǐng)求
              //剩余的請(qǐng)求都需要認(rèn)證才可以放行
              .anyRequest().authenticated()
              .and()
              //表單形式登錄的個(gè)性化配置
              .formLogin()
              .loginPage("/login.html").permitAll()
              .loginProcessingUrl("/login").permitAll()
              .defaultSuccessUrl("/main.html")//可以記住上一次的請(qǐng)求路徑
              //登錄失敗的處理器
              .failureHandler(new MyFailHandler())
              .and()
              //退出登錄相關(guān)設(shè)置
              .logout()
              //退出登錄的請(qǐng)求,是再?zèng)]退出前發(fā)出的,因此此時(shí)還有登錄憑證
              //可以訪問
              .logoutUrl("/logout")
              //此時(shí)已經(jīng)退出了登錄,登錄憑證沒了
              //那么想要訪問非登錄頁面的請(qǐng)求,就必須保證這個(gè)請(qǐng)求無需憑證即可訪問
              .logoutSuccessUrl("/logout.html").permitAll()
              //退出登錄的時(shí)候,刪除對(duì)應(yīng)的cookie
              .deleteCookies("JSESSIONID")
              .and()
              //記住我相關(guān)設(shè)置
              .rememberMe()
              //預(yù)定義key相關(guān)設(shè)置,默認(rèn)是一串uuid
              .key("dhy")
              //令牌的持久化
              .tokenRepository(jdbcTokenRepository())
              .and()
              //應(yīng)用手機(jī)驗(yàn)證碼的配置
              .apply(smsCodeSecurityConfig)
              .and()
              //圖形驗(yàn)證碼
              .addFilterBefore(captchaCodeFilter, UsernamePasswordAuthenticationFilter.class)
              //csrf關(guān)閉
              .csrf().disable();

   }

   //角色繼承
   @Bean
   RoleHierarchy roleHierarchy() {
      RoleHierarchyImpl hierarchy = new RoleHierarchyImpl();
      hierarchy.setHierarchy("ROLE_admin > ROLE_user");
      return hierarchy;
   }

} 

以上就是Spring Security短信驗(yàn)證碼實(shí)現(xiàn)詳解的詳細(xì)內(nèi)容,更多關(guān)于Spring Security短信驗(yàn)證碼的資料請(qǐng)關(guān)注腳本之家其它相關(guān)文章!

相關(guān)文章

  • java實(shí)現(xiàn)zip,gzip,7z,zlib格式的壓縮打包

    java實(shí)現(xiàn)zip,gzip,7z,zlib格式的壓縮打包

    本文是利用Java原生類和apache的commons實(shí)現(xiàn)zip,gzip,7z,zlib的壓縮打包,如果你要是感興趣可以進(jìn)來了解一下。
    2016-10-10
  • Java?導(dǎo)出Excel增加下拉框選項(xiàng)

    Java?導(dǎo)出Excel增加下拉框選項(xiàng)

    這篇文章主要介紹了Java?導(dǎo)出Excel增加下拉框選項(xiàng),excel對(duì)于下拉框較多選項(xiàng)的,需要使用隱藏工作簿來解決,使用函數(shù)取值來做選項(xiàng),下文具體的操作詳情,需要的小伙伴可以參考一下
    2022-04-04
  • 開發(fā)工具EesyCode使用方法解析

    開發(fā)工具EesyCode使用方法解析

    這篇文章主要介紹了開發(fā)工具EesyCode使用方法解析,文中通過示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友可以參考下
    2020-04-04
  • 使用Jackson進(jìn)行JSON生成與解析的新手指南

    使用Jackson進(jìn)行JSON生成與解析的新手指南

    這篇文章主要為大家詳細(xì)介紹了如何使用Jackson進(jìn)行JSON生成與解析處理,文中的示例代碼講解詳細(xì),感興趣的小伙伴可以跟隨小編一起學(xué)習(xí)一下
    2025-04-04
  • Java的方法重載與變量作用域簡介

    Java的方法重載與變量作用域簡介

    這篇文章主要介紹了Java的方法重載與變量作用域,是Java入門學(xué)習(xí)中的基礎(chǔ)知識(shí),需要的朋友可以參考下
    2015-10-10
  • IDEA插件之快速刪除Java代碼中的注釋

    IDEA插件之快速刪除Java代碼中的注釋

    這篇文章主要介紹了IDEA插件之快速刪除Java代碼中的注釋,本文給大家介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或工作具有一定的參考借鑒價(jià)值,需要的朋友可以參考下
    2021-02-02
  • IDEA編寫JavaWeb出現(xiàn)亂碼問題解決方案

    IDEA編寫JavaWeb出現(xiàn)亂碼問題解決方案

    這篇文章主要介紹了IDEA編寫JavaWeb出現(xiàn)亂碼問題解決方案,文中通過示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友可以參考下
    2020-09-09
  • SpringBoot中的Logging詳解

    SpringBoot中的Logging詳解

    這篇文章主要介紹了SpringBoot中的Logging詳解,log配置可能是被忽視的一個(gè)環(huán)節(jié),一般的項(xiàng)目中日志配置好了基本上很少去改動(dòng),我們常規(guī)操作是log.info來記錄日志內(nèi)容,很少會(huì)有人注意到springBoot中日志的配置,需要的朋友可以參考下
    2023-09-09
  • Spring、SpringMVC和SpringBoot的區(qū)別及說明

    Spring、SpringMVC和SpringBoot的區(qū)別及說明

    這篇文章主要介紹了Spring、SpringMVC和SpringBoot的區(qū)別及說明,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。
    2022-10-10
  • java FileOutputStream輸出流的使用解讀

    java FileOutputStream輸出流的使用解讀

    這篇文章主要介紹了java FileOutputStream輸出流的使用解讀,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。如有錯(cuò)誤或未考慮完全的地方,望不吝賜教
    2022-12-12

最新評(píng)論

宝丰县| 长泰县| 九龙坡区| 固安县| 长垣县| 浙江省| 淅川县| 宜宾市| 许昌县| 齐齐哈尔市| 洪泽县| 河北省| 巴中市| 井冈山市| 黄浦区| 本溪| 普兰店市| 盖州市| 安宁市| 琼海市| 建瓯市| 敦煌市| 开封县| 泾川县| 泰来县| 天气| 肇庆市| 深州市| 宿松县| 巴塘县| 汾阳市| 沂源县| 祥云县| 五河县| 中方县| 雅江县| 黄浦区| 苍梧县| 元朗区| 临汾市| 含山县|