编程知识 cdmana.com

Website realizes wechat code scanning login + java + Shiro framework

                    Website to achieve wechat scan code login +Java+Shiro frame

 

One 、 preparation

1、 Sign up for wechat open platform :https://open.weixin.qq.com/

2、 Create web apps , Set authorization callback domain .

3、 Developer Certification ( Need enterprise qualification , cost 300 element )

 

 

 

Two 、 Specific implementation steps

1、 Web page generated QR code ---- Use the second way

 step 1: First introduce the following in the page JS file ( Support https):
http://res.wx.qq.com/connect/zh_CN/htmledition/js/wxLogin.js

 step 2: The following are examples of places where wechat login is required JS object :
 var obj = new WxLogin({
     self_redirect:true,
     id:"login_container", 
     appid: "", 
     scope: "", 
     redirect_uri: "",
     state: "",
     style: "",
     href: ""
 });

2、 adopt code obtain access_token( Server implementation )

https://api.weixin.qq.com/sns/oauth2/access_token?appid=APPID&secret=SECRET&code=CODE&grant_type=authorization_code

3、 The third step : Get user's personal information (UnionID Mechanism ) ( Server implementation )

https://api.weixin.qq.com/sns/userinfo?access_token=ACCESS_TOKEN&openid=OPENID

4、 Get unionID , To sys_user User table to find whether the user exists

5、 Users exist , Direct login

6、 The user doesn't exist , Go to the prompt registration page

7、 Use steps 1 When generating a QR code , You can return the corresponding parameters from the server first

@RequestMapping(value = "/pre")
	@ResponseBody
	public Map<String,String> pre(HttpServletRequest request){
		Map<String,String> map = new HashMap<String, String>();
		map.put("AppId", Global.getConfig("weixin.open.AppId"));
		map.put("redirect_url", Global.getConfig("weixin.open.redirect_url"));
		map.put("state", IdGen.uuid().toUpperCase());
		String key =map.get("state");
		WechatCacheUtils.put(key, key);
		return map;
	}

8、 The pseudo code logic is as follows :

@SuppressWarnings("unchecked")
	@RequestMapping(value = "/login")
	public Object login(String code ,String state , Model model , HttpServletRequest request) throws IOException {
		if(StringUtils.isBlank(code) || StringUtils.isBlank(state)) {
			model.addAttribute("message","state or code  Parameter error !");
			return "error/invalid";
		}
		logger.debug("code , {}" , code);
		logger.debug("state , {}" , state);
		String key =state;
		Object attribute = WechatCacheUtils.get(key);
		// 1、state  Parameter checking 
		if(null == attribute || !state.equals(attribute.toString())) {
			model.addAttribute("message"," Illegal request !");
			return "error/invalid";
		}
		WechatCacheUtils.remove(key);
		
		// 2、 obtain AccessToken
		String openAccessToken = WechatCacheUtils.getOpenAccessToken(code);
		logger.debug("openAccessToken , {}" , openAccessToken);
		Map<String,String> resMap = (Map<String,String>)JsonMapper.fromJsonString(openAccessToken, Map.class);
		// 3、 Get user's personal information  
		String url = WechatConstant.WEIXIN_OPEN_USERINFO.concat("access_token=").concat(resMap.get("access_token"))
														.concat("&openid=").concat(resMap.get("openid"));
		logger.debug(" Get user's personal information url, {}" , url);
		Map<String,String> res = new HashMap<String, String>();
		String doGet = null ;
		try {
			doGet = HttpClientUtils.doGet(url);
			logger.debug(" Get user's personal information , as follows : {}" , doGet);
			res = (Map<String,String>)JsonMapper.fromJsonString(doGet, Map.class);
		} catch (IOException e) {
			e.printStackTrace();
		}
		if(StringUtils.isBlank(res.get("unionid"))) {
			//  Interface call failed , Can't get  unionid
			logger.error(" Failed to get user information ,  The user information interface returns the following data : {}" , doGet);
			model.addAttribute("message"," Wechat interface error , Please try again !");
			return "error/invalid";
		}
		User temp = new User();
		temp.setWechatUid(res.get("unionid"));
		temp.setNumber(1);
		// 4、 According to the unique ID of the user , Judge whether it exists  wechatUid
		List<User> findList = systemService.existsUserByCondition(temp);
		if(CollectionUtils.isEmpty(findList)) {
			//  non-existent , Jump to the prompt to the applet registration page 
			return "modules/sys/guideWechat";
		}
		//  There is , call shiro  Log in  
	    Subject subject = SecurityUtils.getSubject();
	    UsernamePasswordToken passwordToken = new UsernamePasswordToken();
	    passwordToken.setUsername(findList.get(0).getLoginName());
	    passwordToken.setPassword(findList.get(0).getPassword().toCharArray());
	    passwordToken.setUnpass(true); //  Password free login verification 
	    subject.login(passwordToken);
	    //  Login successful , Jump to the login management page 
	    return "redirect:"+adminPath+"/login";
	}

 

3、 ... and 、 summary

1、 Create website application steps --- Authorization callback domain , It can be modified at will , And effective in time .

 

2、 Local debugging method , Using intranet penetration , Just map a local address . Reference resources : Java Wechat payment informs local debugging solution

3、 Scan the code and log in , If the website uses shiro As login management , Suggestions for reference : Shiro Realize password free login .

4、 When debugging , You can use the first method to generate the QR code , There is no need to verify state

https://open.weixin.qq.com/connect/qrconnect?appid=APPID&redirect_uri=REDIRECT_URI&response_type=code&scope=SCOPE&state=STATE#wechat_redirect 

 

 

If you don't understand , Welcome to leave a message , thank you ~

 

 

Reference material : Java The back end calls other service interfaces

            Shiro Implementation of password free login policy

 

 

版权声明
本文为[HaHa_ Sir]所创,转载请带上原文链接,感谢
https://cdmana.com/2020/12/20201224214805159T.html

Scroll to Top