Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

How to realize Code scan Login by SpringBoot Framework in java

2025-02-22 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >

Share

Shulou(Shulou.com)06/03 Report--

This article mainly introduces the java SpringBoot framework how to achieve code scan login, the article is very detailed, has a certain reference value, interested friends must read it!

Project profile

Backend: SpringBoot,Redis.

Front end: Vue,Vue Router, VueX, Axios, vue-qr, ElemntUI.

Android: ZXing, XUI, YHttp.

Realization idea

The verification logic of the overall code-scan login is similar to that of OAuth3.0, as follows:

Users who choose to scan the code to log in can be seen as A: the front end sends an authorization request and waits for app to scan the code.

Users use app to scan the code can be regarded as B: scan the code for authorization and return a temporary Token for secondary authentication.

Users confirm login in app can be regarded as C: login confirmation, authorizing users to log in on the Web side.

The backend returns an official Token after the user confirms the login, which can be regarded as step D.

The subsequent front end accesses the background interface according to the formal Token, and the formal operation on the web side can be regarded as E and F.

The reasons for the second certification

The reason why the user needs to confirm the login again after scanning the code, rather than logging in directly, is for the sake of user security to prevent users from scanning the QR code that other people need to log in and log in directly without confirmation. as a result, others may access our information without our knowledge.

To implement the steps, users visit the web side and choose to scan the code to log in.

When the user chooses to scan the code to log in, the user will send a request for the generation of the QR code to the backend. The backend generates a UUID and saves it to Redis (fixed valid time). The status is set to UNUSED (unused), and if the Redis cache expires, it is EXPIRE (expired). The front end generates a QR code according to the content returned by the backend, and sets a timer to send the request to the backend at regular intervals according to the UUID in the content of the QR code. Get the status of the QR code and update the content displayed on the interface.

Generate the QR code backend interface:

/ * generate QR code content * * @ return result * / @ GetMapping ("/ generate") public BaseResult generate () {String code = IdUtil.simpleUUID (); redisCache.setCacheObject (code, CodeUtils.getUnusedCodeInfo (), DEFAULT_QR_EXPIRE_SECONDS, TimeUnit.SECONDS); return BaseResult.success (GENERATE_SUCCESS, code);}

The front end acquires the content and generates the QR code:

GetToken () {this.codeStatus = 'EMPTY' this.tip =' is getting the login code Please wait for 60 seconds this.effectiveSeconds = 60 clearInterval (this.timer) request ({method: 'get', url:' / code/generate'}). Then ((response) = > {/ / request succeeded. Set the content of the QR code. And update the relevant information this.code = `$ {HOST} / code/scan?code=$ {response.data} `this.codeStatus = 'UNUSED' this.tip =' Please use the mobile phone to scan the code to log in 'this.timer = setInterval (this.getTokenInfo, 2000)}. Catch (() = > {this.getToken ()})}

The API that the backend returns the status information of the QR code:

/ * get QR code status information * * @ param code QR code * @ return result * / @ GetMapping ("/ info") public BaseResult info (String code) {CodeVO codeVO = redisCache.getCacheObject (code); if (codeVO = = null) {return BaseResult.success (INVALID_CODE, StringUtils.EMPTY);} return BaseResult.success (GET_SUCCESS, codeVO);}

Front-end polling to obtain the status of the QR code:

GetTokenInfo () {this.effectiveSeconds-- / / QR code expiration if (this.effectiveSeconds {const codeVO = response.data / / QR code expiration if (! codeVO | |! codeVO.codeStatus) {this.codeStatus = 'EXPIRE' this.tip =' QR code has expired Please refresh the 'return} / / QR code status to log in to if (codeVO.codeStatus =' CONFIRMING') {this.username = codeVO.username this.avatar = codeVO.avatar this.codeStatus = 'CONFIRMING' this.tip =' scan successfully Please confirm the status of the 'return} / / QR code on the phone is to confirm login to if (codeVO.codeStatus = =' CONFIRMED') {clearInterval (this.timer) const token = codeVO.token store.commit ('setToken') Token) this.$router.push ('/ home') Message.success ('login successful') return}})} use mobile phone to scan code State change of QR code

When the user uses the mobile phone to scan the code (logged in and is the correct app, otherwise the scan code will jump to the custom propaganda page), the status of the QR code will be updated to the status of CONFIRMING (to be confirmed), and the user name and avatar information will be added in the Redis cache for the front end to display. In addition, the user's login information (login address, browser, operating system) will be returned to show to the app. At the same time, a temporary Token is generated to app (fixed valid time).

Background processing when the user scans the code:

/ * deal with unused QR code * * @ param code QR code * @ param token token * @ return result * / private BaseResult handleUnusedQr (String code, String token) {/ / verify that the app side accesses the passed token boolean isLegal = JwtUtils.verify (token); if (! isLegal) {return BaseResult.error (AUTHENTICATION_FAILED) } / / Save user name and profile picture information for the front end to display String username = JwtUtils.getUsername (token); CodeVO codeVO = CodeUtils.getConfirmingCodeInfo (username, DEFAULT_AVATAR_URL); redisCache.setCacheObject (code, codeVO, DEFAULT_QR_EXPIRE_SECONDS, TimeUnit.SECONDS); / / return login address, browser, operating system and a temporary token to app String address = HttpUtils.getRealAddressByIp (); String browser = HttpUtils.getBrowserName () String os = HttpUtils.getOsName (); String tmpToken = JwtUtils.sign (username); / / use temporary token as the key, and the user name is stored in redis redisCache.setCacheObject (tmpToken, username, DEFAULT_TEMP_TOKEN_EXPIRE_MINUTES, TimeUnit.MINUTES); LoginInfoVO loginInfoVO = new LoginInfoVO (address, browser, os, tmpToken); return BaseResult.success (SCAN_SUCCESS, loginInfoVO);} confirm login on phone

When a user clicks to confirm login in app, the generated temporary Token will send a request to update the status, and the status of the QR code will be updated to the status of CONFIRMED (confirmed login). At the same time, the backend will generate a formal Token and save it in the Redis. The frontend will obtain the Token when polling for the update status, and then log in with this Token.

The backend processes the code to confirm the login:

/ * deal with the unconfirmed QR code * * @ param code QR code * @ param token token * @ return result * / private BaseResult handleConfirmingQr (String code, String token) {/ / use temporary token to obtain the user name and delete temporary token String username = redisCache.getCacheObject (token) from redis; if (StringUtils.isBlank (username)) {return BaseResult.error (AUTHENTICATION_FAILED) } redisCache.deleteObject (token); / / generate a formal token based on the user name and save it in redis for front-end use String formalToken = JwtUtils.sign (username); CodeVO codeVO = CodeUtils.getConfirmedCodeInfo (username, DEFAULT_AVATAR_URL, formalToken); redisCache.setCacheObject (code, codeVO, DEFAULT_QR_EXPIRE_SECONDS, TimeUnit.SECONDS); return BaseResult.success (CONFIRM_SUCCESS);} effect demonstration

The above is all the contents of the article "how to scan Code login in SpringBoot Framework in java". Thank you for reading! Hope to share the content to help you, more related knowledge, welcome to follow the industry information channel!

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.

Share To

Development

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report