In addition to Weibo, there is also WeChat
Please pay attention
WeChat public account
Shulou
2025-01-31 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >
Share
Shulou(Shulou.com)06/03 Report--
This article is to share with you about how to implement token SMS verification login and logout permissions under SpringBoot. The editor thinks it is very practical, so share it with you as a reference and follow the editor to have a look.
Token SMS verification login and logout under SpringBoot (token stores redis)
There is no introduction to SpringBoot. Please refer to the official documentation for details.
Idea: get SMS messages (verify and limit the number of sending times, store code in redis)-> log in (verify and limit the number of errors, put user information and permissions on token,token and redis)-> query operation (abbreviated), mainly point out the first two points, thank you
Steps:
1. Integration of Redis needs dependencies, yml self-configuration, ali SMS interface dependence (using the introduction of external packages)
Org.springframework.boot spring-boot-starter-data-redis ali taobao-sdk-java-auto system ${project.basedir} / libs/taobao-sdk-java-auto.jar. Org.springframework.boot spring-boot-maven-plugin org.springframework.boot spring-boot-maven-plugin true
2.ali SMS interface tool class, sending CAPTCHA
@ Autowired private StringRedisTemplate redisTemplate;.... Query whether there is such a user, record the number of SMS messages sent per unit time, and limit the number of messages sent Account account= accountService.findByUserName (phone); if (account==null) {return ResultVOUtil.erro (0, "unregistered user");} ValueOperations ops = redisTemplate.opsForValue (); String getTimes= ops.get (account + "code"); Integer gts=getTimes==null?0:Integer.valueOf (getTimes) If (gts > 5) {return ResultVOUtil.erro (0, "get too many SMS messages, please try again later");} ops.set (account+ "code", String.valueOf (gts+1), 5PowerTimeUnit. Minutes); NoteUtils noteUtils=new NoteUtils (); String validCode = UidUtil.getValidCode (); / / generate random number try {String yzmcode = noteUtils.yzmcode (validCode, phone); / / redis sets valid time of CAPTCHA 5 grouping ops.set (phone,validCode,5,TimeUnit.MINUTES) } catch (Exception e) {throw new YunExceptions (0, "get CAPTCHA server bug");} / / SMS interface tool class public class NoteUtils {/ / only if example: refer to the official document 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. Log in to verify and save the permissions in token. There are token utility classes below, which can be directly used by copy.
Public ResultVo login (String phone, String code, HttpServletResponse response, HttpServletRequest request) {ValueOperations 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, "too many errors, please try again later");} if (validcodewords null) {String vcode=validcode.toString () If (code.equalsIgnoreCase (vcode)) {Account account = accountService.findByUserName (phone); if (roomtrecording null) {/ / record login information to obtain permission, string type arecine breco 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); set token ops.set (phone+ "token", token,60,TimeUnit.MINUTES); return ResultVOUtil.success (token) } else {return ResultVOUtil.erro (0, "no account");}} else {ops.set (phone+ "wrong", String.valueOf (ots+1), 5PowerTime. MINUTES); return ResultVOUtil.erro (0, "CAPTCHA error");} else {return ResultVOUtil.erro (0, "Please get CAPTCHA first") }} / / token utility class public class TokenUtils {public static String tokenGet (String username,String limits) {Map map=new HashMap (); map.put ("alg", "HS256"); map.put ("typ", "JWT"); try {Algorithm algorithm=Algorithm.HMAC256 ("*") String token = JWT.create () .withHeader (map) / * set load Payload*/ .withClaim ("loginName", username) .withClaim ("limits") Limits) / / set expiration time-- > verify whether you are logged in .withExpiresAt (new Date (System.currentTimeMillis () + 3600000Secret5)) .withIssuer ("*") / / the signature is generated by someone such as the server .withSubject ("*") / / signature subject .withaudience ("*) * ") / / signature viewers can also understand who accepts the signature / * signature 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 audience = jwt.getAudience (); Map claims = jwt.getClaims (); Claim limits = claims.get ("limits"); / / verify operation permissions. Changes in set length indicate inconsistent permissions String ss = limits.asString (); String [] split = ss.split (","); Set 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. The next step is relatively simple.
4.1 obtain data-- > parameters passed at the front end, and can be verified at the background.
4.2 when you exit, you can clear the token data in redis.
Thank you for reading! On "how to achieve token SMS verification login and logout operation under SpringBoot" this article is shared here, I hope the above content can be of some help to you, so that you can learn more knowledge, if you think the article is good, you can share it out for more people to see it!
Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.
Views: 0
*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.
Continue with the installation of the previous hadoop.First, install zookooper1. Decompress zookoope
"Every 5-10 years, there's a rare product, a really special, very unusual product that's the most un
© 2024 shulou.com SLNews company. All rights reserved.