溫馨提示×

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

密碼登錄×
登錄注冊(cè)×
其他方式登錄
點(diǎn)擊 登錄注冊(cè) 即表示同意《億速云用戶(hù)服務(wù)條款》

SpringBoot下如何實(shí)現(xiàn)token短信驗(yàn)證登入登出權(quán)限操作

發(fā)布時(shí)間:2021-09-06 09:25:03 來(lái)源:億速云 閱讀:138 作者:小新 欄目:編程語(yǔ)言

這篇文章給大家分享的是有關(guān)SpringBoot下如何實(shí)現(xiàn)token短信驗(yàn)證登入登出權(quán)限操作的內(nèi)容。小編覺(jué)得挺實(shí)用的,因此分享給大家做個(gè)參考,一起跟隨小編過(guò)來(lái)看看吧。

SpringBoot下token短信驗(yàn)證登入登出(token存放redis)

不對(duì)SpringBoot進(jìn)行介紹,具體的可以參考官方文檔

思路:獲取短信(驗(yàn)證并限制發(fā)送次數(shù),將code存放redis)-->登入(驗(yàn)證并限制錯(cuò)誤次數(shù),將用戶(hù)信息及權(quán)限放token,token放redis)-->查詢(xún)操作(略),主要將前兩點(diǎn),不足的希望指出,謝謝

步驟:

1.整合Redis需要的依賴(lài),yml自行配置,ali短信接口依賴(lài)(使用引入外部包的方式)

<dependency>
  <groupId>org.springframework.boot</groupId>
  <artifactId>spring-boot-starter-data-redis</artifactId>
</dependency>
<dependency>
  <groupId>ali</groupId>
  <artifactId>taobao-sdk-java-auto</artifactId>
  <scope>system</scope>
  <!--將jar包放在項(xiàng)目/libs/xxx.jar-->
  <systemPath>${project.basedir}/libs/taobao-sdk-java-auto.jar</systemPath>
</dependency>
.......
<build>
    <plugins>
      <plugin>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-maven-plugin</artifactId>
      </plugin>
      <plugin>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-maven-plugin</artifactId>
        <configuration>
          <!--打包的時(shí)候引用該屬性的包-->
          <includeSystemScope>true</includeSystemScope>
        </configuration>
      </plugin>
    </plugins>
  </build>

2.ali短信接口工具類(lèi),發(fā)送驗(yàn)證碼

@Autowired
  private StringRedisTemplate redisTemplate;
....略....
//查詢(xún)是否有此用戶(hù),記錄單位時(shí)間內(nèi)發(fā)送短信次數(shù),并限制發(fā)送次數(shù)
Account account = accountService.findByUserName(phone);
if (account==null){
 return ResultVOUtil.erro(0,"未注冊(cè)用戶(hù)");
 }
ValueOperations<String, String> ops = redisTemplate.opsForValue();
String getTimes = ops.get(account + "code");
Integer gts=getTimes==null?0:Integer.valueOf(getTimes);
if (gts>5){
 return ResultVOUtil.erro(0,"獲取短信次數(shù)過(guò)多,請(qǐng)稍后再試");
}
ops.set(account+"code",String.valueOf(gts+1),5,TimeUnit.MINUTES);
NoteUtils noteUtils=new NoteUtils();
String validCode = UidUtil.getValidCode(); //生成隨機(jī)數(shù)
try {
 String yzmcode = noteUtils.yzmcode(validCode, phone);
  //redis設(shè)置驗(yàn)證碼有效時(shí)間5分組
 ops.set(phone,validCode,5,TimeUnit.MINUTES);
 }catch (Exception e){
   throw new YunExceptions(0,"獲取驗(yàn)證碼服務(wù)器bug");
 }
 
//短信接口工具類(lèi)
public class NoteUtils {
  //僅當(dāng)示例:具體參考官方文檔
  public String url="***************";
  public String appkey="****************";
  public String secret="*********************";
  public String yzmcode(String code,String telnum) throws ApiException, JSONException {
    TaobaoClient client = new DefaultTaobaoClient(url, appkey, secret);
    AlibabaAliqinFcSmsNumSendRequest req = new AlibabaAliqinFcSmsNumSendRequest();
    req.setExtend( "extend" );
    req.setSmsType( "normal" );
    req.setSmsFreeSignName( "*************" );
    req.setSmsParamString( "{code:'"+code+"'}" );
    req.setRecNum(telnum);
    req.setSmsTemplateCode( "******************" );
    AlibabaAliqinFcSmsNumSendResponse rsp = client.execute(req);
    return "true";
 
  }
}

3.登入驗(yàn)證,并將權(quán)限保存在token,以下有token工具類(lèi),可直接copy使用

public ResultVo login(String phone, String code, HttpServletResponse response, HttpServletRequest request){
    ValueOperations<String, String> ops = redisTemplate.opsForValue(); 
    String validcode = ops.get(phone);
    String outtimes=ops.get(phone+"wrong");
    Integer ots=outtimes==null?0:Integer.valueOf(outtimes);
    if (ots>5){
      return ResultVOUtil.erro(0,"錯(cuò)誤次數(shù)過(guò)多,請(qǐng)稍后再試");
    }
    if (validcode!=null){
      String vcode=validcode.toString();
      if (code.equalsIgnoreCase(vcode)){
        Account account = accountService.findByUserName(phone);
        if (account!=null){
          //記錄登入信息,獲取權(quán)限,字符串類(lèi)型a,b,c,d
          String token = TokenUtils.tokenGet(phone, account.getDbids());
          Loglogin loglogin=new Loglogin();
          loglogin.setActionid(200);
          loglogin.setUserip(request.getRemoteAddr());
          loglogin.setUsername(phone);
          loglogin.setLogtime(Timestamp.valueOf(TimeUtil.getCurDate()));
          loglogin.setUserid(account.getUserId());
          logloginService.save(loglogin);
          設(shè)置token時(shí)效
          ops.set(phone+"token",token,60,TimeUnit.MINUTES);
          return ResultVOUtil.success(token);
        }else {
          return ResultVOUtil.erro(0,"沒(méi)有此賬戶(hù)");
        }
      }else {
        ops.set(phone+"wrong",String.valueOf(ots+1),5,TimeUnit.MINUTES);
        return ResultVOUtil.erro(0,"驗(yàn)證碼錯(cuò)誤");
      }
    }else {
      return ResultVOUtil.erro(0,"請(qǐng)先獲取驗(yàn)證碼");
    }
  }
//token工具類(lèi)
public class TokenUtils {
  public static String tokenGet(String username,String limits){
    Map<String,Object> map=new HashMap<>();
    map.put("alg","HS256");
    map.put("typ","JWT");
    try {
      Algorithm algorithm=Algorithm.HMAC256("*******");
      String token = JWT.create()
          .withHeader(map)
          /*設(shè)置 載荷 Payload*/
          .withClaim("loginName", username)
          .withClaim("limits",limits)
          //設(shè)置過(guò)期時(shí)間-->間隔一定時(shí)間驗(yàn)證是否本人登入
          .withExpiresAt(new Date(System.currentTimeMillis()+3600000*5))
          .withIssuer("****")//簽名是有誰(shuí)生成 例如 服務(wù)器
          .withSubject("*****")//簽名的主題
          .withAudience("*****")//簽名的觀眾 也可以理解誰(shuí)接受簽名的
          /*簽名 Signature */
          .sign(algorithm);
      return token;
    }catch (Exception e){
      e.printStackTrace();
    }
    return null;
  }
 
  public static String validToken(String token, String dbid){
    try {
      Algorithm algorithm = Algorithm.HMAC256("*******");
      JWTVerifier verifier = JWT.require(algorithm)
          .withIssuer("SERVICE")
          .build();
      DecodedJWT jwt = verifier.verify(token);
      String subject = jwt.getSubject();
      List<String> audience = jwt.getAudience();
      Map<String, Claim> claims = jwt.getClaims();
      Claim limits = claims.get("limits");
      //驗(yàn)證操作權(quán)限,set長(zhǎng)度改變說(shuō)明權(quán)限不一致
      String ss = limits.asString();
      String[] split = ss.split(",");
      Set<String> set=new HashSet<>(Arrays.asList(split));
      int size = set.size();
      set.add(dbid);
      if (set.size()!=size){
        return null;
      }else {
        Claim name = claims.get("loginName");
        return name.asString();
      }
    }catch (Exception e){
      e.printStackTrace();
    }
    return null;
  }

4.接下來(lái)都比較簡(jiǎn)單

4.1獲取數(shù)據(jù)-->前端傳參數(shù),后臺(tái)驗(yàn)證即可,

4.2退出的時(shí)候,清除redis里的token數(shù)據(jù)即可,

感謝各位的閱讀!關(guān)于“SpringBoot下如何實(shí)現(xiàn)token短信驗(yàn)證登入登出權(quán)限操作”這篇文章就分享到這里了,希望以上內(nèi)容可以對(duì)大家有一定的幫助,讓大家可以學(xué)到更多知識(shí),如果覺(jué)得文章不錯(cuò),可以把它分享出去讓更多的人看到吧!

向AI問(wèn)一下細(xì)節(jié)

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

AI