微信企业号OAuth2验证接口(使用SpringMVC)
企业应用中的URL链接(包括自定义菜单或者消息中的链接),可以通过OAuth2.0来获取员工的身份信息。
注意,此URL的域名,必须完全匹配企业应用设置项中的'可信域名',否则获取用户信息时会返回50001错误码。
可信域名设置不包含"http://",只需域名或IP即可。
OAuth2验证可以使用多种方式,此处使用注解方式。设计思路是在需要获取用户信息的GET请求上添加注解,然后在调用的时候判断是否包含此注解,然后做处理流程。
每次请求包含2种情况:
1.不需要获取用户信息,直接跳转到指定视图;
2.需要获取用户信息,此处分2种情况:
a.session中存储了之前获取的用户信息,则直接跳转到指定视图;
b.session中不包含用户信息,则需要构造带回调参数的URL去微信API服务器获取code参数,然后通过code参数调用API换取Userid并保存到session,然后再次跳转到初始请求的视图页面。
具体处理流程如下图:
此处源码包括:微信企业号的接入及消息的简单处理,在此基础上添加OAuth2的验证实例。
源码下载地址:http://download.csdn.NET/detail/rzg813/8015527
具体实现代码:
创建拦截器:OAuth2Interceptor
- package org.oms.qiye.interceptor;
-
- import java.io.UnsupportedEncodingException;
- import java.lang.reflect.Method;
-
- import javax.servlet.http.HttpServletRequest;
- import javax.servlet.http.HttpServletResponse;
- import javax.servlet.http.HttpSession;
-
- import org.springframework.web.method.HandlerMethod;
- import org.springframework.web.servlet.HandlerInterceptor;
- import org.springframework.web.servlet.ModelAndView;
-
- public class OAuth2Interceptor implements HandlerInterceptor {
-
-
-
-
-
- @Override
- public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
- System.out.println("**执行顺序: 3、afterCompletion**");
-
- }
-
-
-
-
- @Override
- public void postHandle(HttpServletRequest request, HttpServletResponse response, Object arg2, ModelAndView modelAndView) throws Exception {
- System.out.println("**执行顺序: 2、postHandle**");
-
- }
-
-
-
-
-
-
- @Override
- public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
- System.out.println("**执行顺序: 1、preHandle**");
- String url = request.getRequestURL().toString();
-
- HttpSession session = request.getSession();
-
-
- HandlerMethod handlerMethod = (HandlerMethod) handler;
- Method method = handlerMethod.getMethod();
- OAuthRequired annotation = method.getAnnotation(OAuthRequired.class);
- if (annotation != null) {
- System.out.println("OAuthRequired:你的访问需要获取登录信息!");
- Object objUid = session.getAttribute("UserId");
- if (objUid == null) {
- String resultUrl = request.getRequestURL().toString();
- String param=request.getQueryString();
- if(param!=null){
- resultUrl+= "?" + param;
- }
- System.out.println("resultUrl="+resultUrl);
- try {
- resultUrl = java.net.URLEncoder.encode(resultUrl, "utf-8");
- } catch (UnsupportedEncodingException e) {
- e.printStackTrace();
- }
-