search
HomeJavajavaTutorialJava implements QR code scanning authorization login

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!

Statement
This article is reproduced at:CSDN. If there is any infringement, please contact admin@php.cn delete
Java Platform Independence: Compatibility with different OSJava Platform Independence: Compatibility with different OSMay 13, 2025 am 12:11 AM

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

What features make java still powerfulWhat features make java still powerfulMay 13, 2025 am 12:05 AM

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

Top Java Features: A Comprehensive Guide for DevelopersTop Java Features: A Comprehensive Guide for DevelopersMay 13, 2025 am 12:04 AM

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.

Is Java Truly Platform Independent? How 'Write Once, Run Anywhere' WorksIs Java Truly Platform Independent? How 'Write Once, Run Anywhere' WorksMay 13, 2025 am 12:03 AM

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

Demystifying the JVM: Your Key to Understanding Java ExecutionDemystifying the JVM: Your Key to Understanding Java ExecutionMay 13, 2025 am 12:02 AM

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

Is java still a good language based on new features?Is java still a good language based on new features?May 12, 2025 am 12:12 AM

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

What Makes Java Great? Key Features and BenefitsWhat Makes Java Great? Key Features and BenefitsMay 12, 2025 am 12:11 AM

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

Top 5 Java Features: Examples and ExplanationsTop 5 Java Features: Examples and ExplanationsMay 12, 2025 am 12:09 AM

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.

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

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

VSCode Windows 64-bit Download

A free and powerful IDE editor launched by Microsoft

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

WebStorm Mac version

WebStorm Mac version

Useful JavaScript development tools

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

SAP NetWeaver Server Adapter for Eclipse

SAP NetWeaver Server Adapter for Eclipse

Integrate Eclipse with SAP NetWeaver application server.