亚洲乱码中文字幕综合,中国熟女仑乱hd,亚洲精品乱拍国产一区二区三区,一本大道卡一卡二卡三乱码全集资源,又粗又黄又硬又爽的免费视频

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à)值,需要的朋友們下面隨著小編來(lái)一起學(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ù)庫(kù)中查找,判斷對(duì)應(yīng)的手機(jī)號(hào)是否存在
        UserDetails userDetails = userDetailsService.loadUserByUsername(mobile);
        //這個(gè)地方userDetailsService如果使用spring security提供的話,找不到用戶名會(huì)直接拋出異常,走不到這里來(lái)
        //即直接去了登錄失敗的處理器
        if(userDetails == null){
            return "您輸入的手機(jī)號(hào)不是系統(tǒng)注冊(cè)用戶";
        }
        //commons-lang3包下的工具類,生成指定長(zhǎng)度為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")
              //無(wú)需登錄憑證,即可放行
              .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)退出了登錄,登錄憑證沒了
              //那么想要訪問非登錄頁(yè)面的請(qǐng)求,就必須保證這個(gè)請(qǐng)求無(wú)需憑證即可訪問
              .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ù)庫(kù)查詢當(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("無(wú)法獲取用戶信息");
        }
        //設(shè)置新的認(rèn)證主體
        SmsCodeAuthenticationToken authenticationResult = new SmsCodeAuthenticationToken(user,user.getAuthorities());
        //copy details
        authenticationResult.setDetails(authenticationToken.getDetails());
        //返回新的令牌對(duì)象
        return authenticationResult;
    }

    /**
     * AuthenticationManager挑選一個(gè)AuthenticationProvider
     * 來(lái)處理傳入進(jìn)來(lái)的Token就是根據(jù)supports方法來(lái)判斷的
     * @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));
        //有則配置,無(wú)則不配置
        //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")
              //無(wú)需登錄憑證,即可放行
              .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)退出了登錄,登錄憑證沒了
              //那么想要訪問非登錄頁(yè)面的請(qǐng)求,就必須保證這個(gè)請(qǐng)求無(wú)需憑證即可訪問
              .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執(zhí)行SQL語(yǔ)句實(shí)現(xiàn)查詢的通用方法詳解

    java執(zhí)行SQL語(yǔ)句實(shí)現(xiàn)查詢的通用方法詳解

    這篇文章主要介紹了java執(zhí)行SQL語(yǔ)句實(shí)現(xiàn)查詢的通用方法詳解,具有一定借鑒價(jià)值,需要的朋友可以參考下。
    2017-12-12
  • 解決springboot中配置過濾器以及可能出現(xiàn)的問題

    解決springboot中配置過濾器以及可能出現(xiàn)的問題

    這篇文章主要介紹了解決springboot中配置過濾器以及可能出現(xiàn)的問題,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。一起跟隨小編過來(lái)看看吧
    2020-09-09
  • SpringBoot的10個(gè)參數(shù)驗(yàn)證技巧分享

    SpringBoot的10個(gè)參數(shù)驗(yàn)證技巧分享

    參數(shù)驗(yàn)證很重要,是平時(shí)開發(fā)環(huán)節(jié)中不可少的一部分,但是我想很多后端同事會(huì)偷懶,干脆不錯(cuò),這樣很可能給系統(tǒng)的穩(wěn)定性和安全性帶來(lái)嚴(yán)重的危害,那么在Spring Boot應(yīng)用中如何做好參數(shù)校驗(yàn)工作呢,本文提供了10個(gè)小技巧,需要的朋友可以參考下
    2023-09-09
  • Java使用Socket判斷某服務(wù)能否連通代碼實(shí)例

    Java使用Socket判斷某服務(wù)能否連通代碼實(shí)例

    這篇文章主要介紹了Java使用Socket判斷某服務(wù)能否連通代碼實(shí)例,文中通過示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友可以參考下
    2019-11-11
  • @valid 無(wú)法觸發(fā)BindingResult的解決

    @valid 無(wú)法觸發(fā)BindingResult的解決

    這篇文章主要介紹了@valid 無(wú)法觸發(fā)BindingResult的解決方案,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。如有錯(cuò)誤或未考慮完全的地方,望不吝賜教
    2021-12-12
  • SpringBoot下使用MyBatis-Puls代碼生成器的方法

    SpringBoot下使用MyBatis-Puls代碼生成器的方法

    這篇文章主要介紹了SpringBoot下使用MyBatis-Puls代碼生成器的方法,本文給大家介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或工作具有一定的參考借鑒價(jià)值,需要的朋友可以參考下
    2020-10-10
  • 一文徹底了解Java的組合模式

    一文徹底了解Java的組合模式

    組合模式(Composite?Pattern)指將對(duì)象組合成樹形結(jié)構(gòu)以表示“部分-整體”的層次結(jié)構(gòu),?使得用戶對(duì)單個(gè)對(duì)象和組合對(duì)象的使用具有一致性。本文就來(lái)帶大家深入了解一下Java的組合模式吧
    2023-02-02
  • 注解@CrossOrigin解決跨域的問題

    注解@CrossOrigin解決跨域的問題

    這篇文章主要介紹了注解@CrossOrigin解決跨域的問題,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。一起跟隨小編過來(lái)看看吧
    2020-09-09
  • Java中實(shí)現(xiàn)在一個(gè)方法中調(diào)用另一個(gè)方法

    Java中實(shí)現(xiàn)在一個(gè)方法中調(diào)用另一個(gè)方法

    下面小編就為大家分享一篇Java中實(shí)現(xiàn)在一個(gè)方法中調(diào)用另一個(gè)方法,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。一起跟隨小編過來(lái)看看吧
    2018-02-02
  • Spring中存取Bean的相關(guān)注解舉例詳解

    Spring中存取Bean的相關(guān)注解舉例詳解

    這篇文章主要給大家介紹了關(guān)于Spring中存取Bean的相關(guān)注解,在沒有使用注解獲取對(duì)象之前,我們需要在配置文件中通過添加bean來(lái)將對(duì)象存儲(chǔ)到Spring容器中,這對(duì)于我們來(lái)說(shuō)是比較麻煩的,需要的朋友可以參考下
    2023-10-10

最新評(píng)論