In today’s life, logging in to a website has become so simple. When you have logged in to WeChat, when you want to log in to another website, you only need to scan the QR code. But everyone knows how to use Java to scan the QR code. Authorized? This article is about how to use Java to implement code scanning authorization login. Let’s learn about it together.
Assume that there are two devices now. Device A needs to scan the QR code to authorize login, and device B is the device that has already been logged in. Then the implementation is as shown below,
1: Device A generates a QR code:
Device A requests the getLoginCode interface from the server. This interface is performed based on the requested sessionId. Encrypt with base64 or other encryption methods, then use this as the value of the QR code, write this loginCode to redis, and set an expiration of 5 minutes. Then this loginCode is returned to device A, and device A uses this value to generate a login QR code.
2: Device B scans QR code for authorization
When device B scans the QR code of device A, it carries the value of the QR code and requests the interface scanConfirmLogin for authorization login. In this interface, first Verify whether the QR code has expired. If it has not expired, perform subsequent business logic processing and write the user's basic information and token into redis.
3: Device A polls to obtain authorization status
Device B refreshes the user authorization status interface once per second. If the status is authorized, it will obtain the user information and do the following logical processing.
/** * 获取扫描登陆的二维码 * @param noncestr随机字符串 * @throws Exception */ @RequestMapping(value = "user/getLoginCode.json") public void getLoginCode(String noncestr,HttpServletRequest request,HttpServletResponse response) throws Exception { if(StringUtil.isBlank(noncestr)){ apiData(request, response,ReqJson.error(CommonError.PARAMS_IMPERFECT)); return; } //参数的有效性校验在拦截器里实现 int expirationTime=300; //时效5分钟 final String sessionId=request.getSession().getId(); String loginCode=ToolUtils.getBase64(sessionId); JedisUtil.set(loginCode, loginCode, expirationTime); Map<String,Object> map=new HashMap<>(); map.put("loginCode", loginCode); map.put("expirationTime", expirationTime); apiData(request, response, ReqJson.ok(map)); } /** * 扫码确认登陆 * @param loginCode * @param request * @param response * @throws Exception */ @RequestMapping(value = "user/scanConfirmLogin.json") @AuthorizationApi public void scanConfirmLogin(@CurrentToken final Token token,String loginCode,HttpServletRequest request,HttpServletResponse response) throws Exception { if(StringUtil.isBlank(loginCode)){ apiData(request, response,ReqJson.error(CommonError.PARAMS_IMPERFECT)); return; } String userId=token.getUserId(); Map<String,String> map=new HashMap<>(); String loginTicket=JedisUtil.get(loginCode); if(StringUtil.isBlank(loginTicket)){ //二维码过期 apiData(request, response,ReqJson.error(CommonError.TWO_DIMENSIONAL_CODE_HAS_EXPIRED)); return; } UserInfo userInfo = userInfoBiz.getUser(new UserInfo(userId)); if(userInfo==null){ apiData(request, response,ReqJson.error(UserError.USER_NOT_FOUND)); return; } //将用户信息放在缓存中 map.put(BaseConfig.ACCESS_TOKEN, token.getAccessToken()); map.put("userId", userInfo.getUserId()); map.put("rongCloudToken", userInfo.getRongCloudToken()); map.put("identity", userInfo.getIdentity()); JedisUtil.setMap(loginCode+"scanConfirmLogin", map, 300); apiData(request, response, ReqJson.ok(new Object())); } /** * 获取登陆状态 * @param loginCode * @param request * @param response * @throws Exception */ @RequestMapping(value = "user/getScanConfirmLoginStatus.json") public void getLoginStatus(final String loginCode,HttpServletRequest request,HttpServletResponse response) throws Exception { if(StringUtil.isBlank(loginCode)){ apiData(request, response,ReqJson.error(CommonError.PARAMS_IMPERFECT)); return; } Map<String,String> map= JedisUtil.getMap(loginCode+"scanConfirmLogin"); if(map==null){ apiData(request, response,ReqJson.error(CommonError.AUTHORIZATION_HAS_EXPIRED)); return; } apiData(request, response, ReqJson.ok(map)); }
【Recommended course: Java video course】
The above is the detailed content of Java implements QR code scanning authorization login. For more information, please follow other related articles on the PHP Chinese website!

JavaachievesplatformindependencethroughtheJavaVirtualMachine(JVM),allowingcodetorunondifferentoperatingsystemswithoutmodification.TheJVMcompilesJavacodeintoplatform-independentbytecode,whichittheninterpretsandexecutesonthespecificOS,abstractingawayOS

Javaispowerfulduetoitsplatformindependence,object-orientednature,richstandardlibrary,performancecapabilities,andstrongsecurityfeatures.1)PlatformindependenceallowsapplicationstorunonanydevicesupportingJava.2)Object-orientedprogrammingpromotesmodulara

The top Java functions include: 1) object-oriented programming, supporting polymorphism, improving code flexibility and maintainability; 2) exception handling mechanism, improving code robustness through try-catch-finally blocks; 3) garbage collection, simplifying memory management; 4) generics, enhancing type safety; 5) ambda expressions and functional programming to make the code more concise and expressive; 6) rich standard libraries, providing optimized data structures and algorithms.

JavaisnotentirelyplatformindependentduetoJVMvariationsandnativecodeintegration,butitlargelyupholdsitsWORApromise.1)JavacompilestobytecoderunbytheJVM,allowingcross-platformexecution.2)However,eachplatformrequiresaspecificJVM,anddifferencesinJVMimpleme

TheJavaVirtualMachine(JVM)isanabstractcomputingmachinecrucialforJavaexecutionasitrunsJavabytecode,enablingthe"writeonce,runanywhere"capability.TheJVM'skeycomponentsinclude:1)ClassLoader,whichloads,links,andinitializesclasses;2)RuntimeDataAr

Javaremainsagoodlanguageduetoitscontinuousevolutionandrobustecosystem.1)Lambdaexpressionsenhancecodereadabilityandenablefunctionalprogramming.2)Streamsallowforefficientdataprocessing,particularlywithlargedatasets.3)ThemodularsystemintroducedinJava9im

Javaisgreatduetoitsplatformindependence,robustOOPsupport,extensivelibraries,andstrongcommunity.1)PlatformindependenceviaJVMallowscodetorunonvariousplatforms.2)OOPfeatureslikeencapsulation,inheritance,andpolymorphismenablemodularandscalablecode.3)Rich

The five major features of Java are polymorphism, Lambda expressions, StreamsAPI, generics and exception handling. 1. Polymorphism allows objects of different classes to be used as objects of common base classes. 2. Lambda expressions make the code more concise, especially suitable for handling collections and streams. 3.StreamsAPI efficiently processes large data sets and supports declarative operations. 4. Generics provide type safety and reusability, and type errors are caught during compilation. 5. Exception handling helps handle errors elegantly and write reliable software.


Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

VSCode Windows 64-bit Download
A free and powerful IDE editor launched by Microsoft

Notepad++7.3.1
Easy-to-use and free code editor

WebStorm Mac version
Useful JavaScript development tools

SublimeText3 Chinese version
Chinese version, very easy to use

SAP NetWeaver Server Adapter for Eclipse
Integrate Eclipse with SAP NetWeaver application server.
