解决微信网页授权多个域名(大于两个)
问题
微信进行网页授权时,需要填写授权域名,授权域名只有两个, 但是实际上可能有多个。不利于开发调试,每次都要修改,并且要发布到那个域名底下,相当麻烦
思路
- 准备中间代理域名agent.example
- 微信公众号网页授权上填这个代理域名 agent.example
- 所有 需要微信网页授权的客户端页面都向 agent.example 请求
- 然后由 agent.example 统一向 微信服务器进行发起网页授权请求
- 微信服务器带着code 重定向 agent.example
- agent.example 将code 拼接真实客户端需要授权页面的地址 为 url
- agent.example 重定向 url 到客户端
- 客户端可以通过 url 拿到 微信授权过的 code
流程图
使用程序实现
@Slf4j
@RestController
public class WechatAgentController {
/**
* 微信网页授权地址, 需要人工点击确认的那种
*/
private static final String AUTH_URL = "https://open.weixin.qq.com/connect/oauth2/authorize"
+"?appid={0}&redirect_uri={1}&response_type=code&scope=snsapi_userinfo&state=STATE#wechat_redirect";
/**
* 代理授权域名,换成你自己真实的公网域名!!
*/
private static final String DEFAULT_AUTH_HOST = "http://wx.open.vaiwan.com";
private static final String CODE_URL = "wx/code?returnUrl={0}";
/**
* 授权
*
* @param appId
* @param redirectUrl 目标地址
* @param authHost 中间代理域名,可直接访问到 /wx/oauth2, 可以不填
* @param response
* @throws IOException
*/
@GetMapping("/wx/oauth2")
public void openAuth(@RequestParam String appId, @RequestParam String redirectUrl,
@RequestParam(required = false) String agentHost,
HttpServletResponse response) throws IOException {
String middleUrl = StringUtils.hasText(agentHost) ? agentHost : DEFAULT_AUTH_HOST;
if (middleUrl.lastIndexOf("/") != -1) {
middleUrl = middleUrl.concat("/");
}
middleUrl = middleUrl.concat(CODE_URL);
String tmpUrl = MessageFormat.format(middleUrl, redirectUrl);
String realRedirectUrl = MessageFormat.format(AUTH_URL, appId, tmpUrl);
//重定向到 /wx/code 请求
response.sendRedirect(realRedirectUrl);
}
/**
* 获取 code
*
* @param code
* @param returnUrl
* @param response
* @throws IOException
*/
@GetMapping("/wx/code")
public void code(@RequestParam String code, @RequestParam String returnUrl,
HttpServletResponse response) throws IOException {
log.info("code: {}, returnUrl: {}", code, returnUrl);
String redirectUrl = returnUrl.concat("?").concat(code);
response.sendRedirect(redirectUrl);
}
}
客户端发起网页授权请求
http://wx.open.vaiwan.com/wx/oauth2?appId=appId&redirectUrl=https://www.baidu.com
这样客户端想在哪个页面进行微信网页授权,就只要修改redirectUrl
啦
其他方式
也可以通过写一个中间agent.html, 做一层代理转发,然后重定向回去,原理差不多
good luck !