微信企业号OAuth2验证接口实例(使用SpringMVC)

微信企业号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 {

	/**
	 * 在DispatcherServlet完全处理完请求后被调用
	 * 当有拦截器抛出异常时,会从当前拦截器往回执行所有的拦截器的afterCompletion()
	 */
	@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**");

	}

	/**
	 * 在业务处理器处理请求之前被调用 如果返回false 从当前的拦截器往回执行所有拦截器的afterCompletion(),再退出拦截器链
	 * 如果返回true 执行下一个拦截器,直到所有的拦截器都执行完毕 再执行被拦截的Controller 然后进入拦截器链,
	 * 从最后一个拦截器往回执行所有的postHandle() 接着再从最后一个拦截器往回执行所有的afterCompletion()
	 */
	@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();
				}
				//请求的路径
		        String contextPath=request.getContextPath();
				response.sendRedirect(contextPath + "/oauth2.do?resultUrl=" + resultUrl);
				return false;
			}

		}
		return true;
	}

}

验证OAuth2注解OAuthRequired
package org.oms.qiye.interceptor;

import java.lang.annotation.*;
/**
 * 验证OAuth2注解
 * @author Sunlight
 *
 */
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.METHOD)
public @interface OAuthRequired {
	
}

常量类,此处可以替换为持久化数据读取;
package org.oms.qiye.util;

public class Constants {
	/**
	 * 常量说明:
	 * 此处定义的常量需要持久化,可以保存在数据库中,在需要的地方读取。
	 * 在多企业号中,最好以每个应用来定义。
	 */
	public static final int AGENTID = 1;
	public static final String TOKEN = "sunlight";
	public static final String CORPID = "你的企业号ID";
	public static final String Secret = "你的企业号_ACCESS_TOKEN";
	public static final String encodingAESKey = "s8vFF4f6AWay3uAdJh79WD6imaam4BV6Kl4eL4UzgfM";
}

OAuth2 处理控制器OAuth2Controller
package org.oms.qiye.web;

import java.io.UnsupportedEncodingException;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

import org.oms.qiye.pojo.AccessToken;
import org.oms.qiye.util.Constants;
import org.oms.qiye.util.QiYeUtil;
import org.oms.qiye.util.Result;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
/**
 * OAuth2 处理控制器
 * @author Sunlight
 *
 */
@Controller
public class OAuth2Controller {
	/**
	 * 构造参数并将请求重定向到微信API获取登录信息
	 * 
	 * @param index
	 * @return
	 */
	@RequestMapping(value = { "/oauth2.do", "/oauth2" })
	public String Oauth2API(HttpServletRequest request, @RequestParam String resultUrl) {
		// 此处可以添加获取持久化的数据,如企业号id等相关信息
		String CropId = Constants.CORPID;
		String redirectUrl = "";
		if (resultUrl != null) {
			String reqUrl =request.getLocalAddr();
			String backUrl ="http://" + reqUrl + "/oauth2url.do?oauth2url=" + resultUrl;
			System.out.println("backUrl="+backUrl);
			redirectUrl = oAuth2Url(CropId, backUrl);
		}
		return "redirect:" + redirectUrl;
	}

	/**
	 * 根据code获取Userid后跳转到需要带用户信息的最终页面
	 * 
	 * @param request
	 * @param code
	 *            获取微信重定向到自己设置的URL中code参数
	 * @param oauth2url
	 *            跳转到最终页面的地址
	 * @return
	 */
	@RequestMapping(value = { "/oauth2url.do" })
	public String Oauth2MeUrl(HttpServletRequest request, @RequestParam String code, @RequestParam String oauth2url) {
		AccessToken accessToken = QiYeUtil.getAccessToken(Constants.CORPID, Constants.Secret);
		HttpSession session = request.getSession();
		if (accessToken != null && accessToken.getToken() != null) {
			String Userid = getMemberGuidByCode(accessToken.getToken(), code, Constants.AGENTID);
			if (Userid != null) {
				session.setAttribute("UserId", Userid);
			}
		}
		// 这里简单处理,存储到session中
		return "redirect:" + oauth2url;
	}

	/**
	 * 构造带员工身份信息的URL
	 * 
	 * @param corpid
	 *            企业id
	 * @param redirect_uri
	 *            授权后重定向的回调链接地址,请使用urlencode对链接进行处理
	 * @param state
	 *            重定向后会带上state参数,企业可以填写a-zA-Z0-9的参数值
	 * @return
	 */
	private String oAuth2Url(String corpid, String redirect_uri) {
		try {
			redirect_uri = java.net.URLEncoder.encode(redirect_uri, "utf-8");
		} catch (UnsupportedEncodingException e) {
			e.printStackTrace();
		}
		String oauth2Url = "https://open.weixin.qq.com/connect/oauth2/authorize?appid=" + corpid + "&redirect_uri=" + redirect_uri
				+ "&response_type=code&scope=snsapi_base&state=sunlight#wechat_redirect";
		System.out.println("oauth2Url=" + oauth2Url);
		return oauth2Url;
	}

	/**
	 * 调用接口获取用户信息
	 * 
	 * @param token
	 * @param code
	 * @param agentId
	 * @return
	 * @throws SQLException
	 * @throws RemoteException
	 */
	public String getMemberGuidByCode(String token, String code, int agentId) {
		System.out.println("code==" + code + "\ntoken=" + token + "\nagentid=" + agentId);
		Result<String> result = QiYeUtil.oAuth2GetUserByCode(token, code, agentId);
		System.out.println("result=" + result);
		if (result.getErrcode() == "0") {
			if (result.getObj() != null) {
				// 此处可以通过微信授权用code还钱的Userid查询自己本地服务器中的数据
				return result.getObj();
			}
		}
		return "";
	}

}

需要验证OAuth2控制器UserController
package org.oms.qiye.web;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import org.oms.qiye.interceptor.OAuthRequired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
/**
 * 需要验证OAuth2控制器
 * @author Sunlight
 *
 */
@Controller
public class UserController {
	/**
	 * 加载个人信息,此处添加了@OAuthRequired注解
	 * @param model
	 * @return
	 */
	@RequestMapping(value={"/userInfo.do"})
	@OAuthRequired
	public String load(HttpServletRequest request,Model model){
		System.out.println("Load a User!");
		HttpSession session = request.getSession();
		model.addAttribute("Userid", session.getAttribute("Userid"));
		return "user";
	}
}

发起https请求并获取结果HttpRequestUtil.class

微信企业号调用类 {"errcode":0,"errmsg":"ok"} 此结果表示调用方法成功返回QiYeUtil.class

返回结果处理类Result.class

枚举EnumMethod.class

以上类不在列出,在其他文章已存在!

处理页面user.jsp:

<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Model And List</title>
</head>
<body>
	<h1>Welcome To SpringMVC! This is OAuth2 UserInfo</h1>
	<h3>获取到的Userid是:${UserId}</h3>
</body>
</html>

SpringMVC配置文件:mvc-servlet.xml
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
	xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:tx="http://www.springframework.org/schema/tx"
	xmlns:context="http://www.springframework.org/schema/context"
	xmlns:mvc="http://www.springframework.org/schema/mvc"
	xsi:schemaLocation="http://www.springframework.org/schema/beans 
	http://www.springframework.org/schema/beans/spring-beans-3.2.xsd 
	http://www.springframework.org/schema/tx 
	http://www.springframework.org/schema/tx/spring-tx-3.2.xsd
	http://www.springframework.org/schema/context
    http://www.springframework.org/schema/context/spring-context-3.2.xsd
	http://www.springframework.org/schema/mvc
    http://www.springframework.org/schema/mvc/spring-mvc-3.2.xsd">

	<context:component-scan base-package="org.oms.qiye.web"></context:component-scan>
	<mvc:annotation-driven />

	<bean
		class="org.springframework.web.servlet.view.InternalResourceViewResolver">
		<property name="prefix" value="/WEB-INF/jsp/"></property>
		<property name="suffix" value=".jsp"></property>
	</bean>

	<!-- 静态文件处理 -->
	<mvc:resources mapping="/images/**" location="/images/" />
	<mvc:resources mapping="/js/**" location="/js/" />
	<mvc:resources mapping="/css/**" location="/css/" />

	<!-- OAuth2拦截器 -->
	<mvc:interceptors>
		<mvc:interceptor>
			<!-- 对所有的请求拦截使用/** ,对某个模块下的请求拦截使用:/myPath/* -->
			<mvc:mapping path="/**" />
			<ref bean="oauth2Interceptor" />
		</mvc:interceptor>
	</mvc:interceptors>
	<bean id="oauth2Interceptor" class="org.oms.qiye.interceptor.OAuth2Interceptor">
	</bean>
</beans>

服务器测试结果图:


手机微信客户端测试结果图:


转载请注明出处,以免惨不忍睹!

技术交流请加入QQ群:点击链接加入群【微信企业号开发交流】:http://jq.qq.com/?_wv=1027&k=RgbtOX

QQ群:89714226


<think>好的,我现在需要帮助用户将OAuth2授权服务器1.4与企业微信扫码登录集成。首先,我需要回忆一下OAuth2授权服务器的基本配置步骤,以及企业微信OAuth2流程。根据用户提供的引用内容,特别是引用[3]提到的整合Spring Boot 3.1.3和OAuth2.1规范,可能需要注意版本兼容性。用户提到的是1.4版本,但引用中的版本是0.2.22.5.6,可能需要确认是否有差异。 首先,企业微信的扫码登录通常使用OAuth2的授权码流程。需要注册企业微信应用,获取CorpID、AgentID和Secret。然后,在授权服务器中配置这些信息作为客户端属性。接着,可能需要自定义Grant类型或扩展OAuth2的Provider,以支持企业微信的特定参数,比如企业微信的redirect_uri和scope。 接下来,用户需要配置授权服务器的客户端信息,设置重定向URI到企业微信的回调地址。然后,处理授权码回调,这里可能需要实现一个自定义的TokenResponseController,用于处理企业微信返回的授权码,并交换访问令牌。同时,需要确保用户信息能够正确映射到授权服务器的用户体系,可能需要实现UserDetailsService来加载用户信息。 还需要考虑安全配置,确保端点正确保护,比如/oauth2/authorization和/oauth2/token。同时,处理企业微信返回的用户信息,可能需要自定义OAuth2UserService来解析企业微信的用户数据,并转换为系统的用户对象。 在过程中,可能会遇到版本兼容问题,比如oauth2-authorization-server 1.4与Spring Boot版本是否匹配,需要参考官方文档确认依赖关系。另外,企业微信的API可能有特定的请求参数,比如需要使用企业微信的特定URL来发起授权请求,以及处理返回的userid如何映射到本地用户。 最后,测试整个流程,确保用户可以通过企业微信扫码登录,并正确获取访问令牌和用户信息。同时,需要处理异常情况,比如授权码无效或过期的情况,返回合适的错误信息。</think>### OAuth2授权服务器1.4集成企业微信扫码登录步骤 #### 1. **企业微信应用配置** - 登录企业微信后台,创建应用并获取以下参数: - `CorpID`(企业ID) - `AgentID`(应用ID) - `Secret`(应用密钥) - 设置**授权回调域**为授权服务器的域名,例如:`https://your-domain.com/login/oauth2/code/wecom` #### 2. **添加依赖** ```xml <dependency> <groupId>org.springframework.security</groupId> <artifactId>spring-security-oauth2-authorization-server</artifactId> <version>1.4.0</version> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-web</artifactId> </dependency> ``` #### 3. **配置授权服务器** ```java @Bean public RegisteredClientRepository registeredClientRepository() { RegisteredClient wecomClient = RegisteredClient.withId("wecom") .clientId("CorpID@AgentID") // 企业微信格式要求 .clientSecret("{noop}Secret") // 企业微信应用Secret .clientAuthenticationMethod(ClientAuthenticationMethod.CLIENT_SECRET_BASIC) .authorizationGrantType(AuthorizationGrantType.AUTHORIZATION_CODE) .redirectUri("https://your-domain.com/login/oauth2/code/wecom") .scope("userid") // 企业微信默认scope .build(); return new InMemoryRegisteredClientRepository(wecomClient); } ``` #### 4. **自定义企业微信OAuth2登录配置** ```java @Configuration public class WecomOAuth2Config { @Bean public ClientRegistration wecomClientRegistration() { return ClientRegistration.withRegistrationId("wecom") .clientId("CorpID@AgentID") .clientSecret("Secret") .clientAuthenticationMethod(ClientAuthenticationMethod.CLIENT_SECRET_BASIC) .authorizationGrantType(AuthorizationGrantType.AUTHORIZATION_CODE) .redirectUri("{baseUrl}/login/oauth2/code/{registrationId}") .scope("userid") .authorizationUri("https://open.work.weixin.qq.com/wwopen/sso/qrConnect") .tokenUri("https://qyapi.weixin.qq.com/cgi-bin/gettoken") .userInfoUri("https://qyapi.weixin.qq.com/cgi-bin/user/getuserinfo") .userNameAttributeName("userid") .build(); } @Bean public OAuth2UserService<OAuth2UserRequest, OAuth2User> wecomOAuth2UserService() { return request -> { // 解析企业微信返回的userid String userId = request.getAdditionalParameters().get("userid").toString(); return new DefaultOAuth2User( Collections.singleton(new SimpleGrantedAuthority("ROLE_USER")), Collections.singletonMap("userid", userId), "userid"); }; } } ``` #### 5. **配置安全规则** ```java @EnableWebSecurity public class SecurityConfig { @Bean public SecurityFilterChain filterChain(HttpSecurity http) throws Exception { http .authorizeHttpRequests(auth -> auth .anyRequest().authenticated()) .oauth2Login(oauth2 -> oauth2 .userInfoEndpoint(userInfo -> userInfo .userService(wecomOAuth2UserService()))); return http.build(); } } ``` #### 6. **处理用户映射** 需实现`UserDetailsService`接口,将企业微信返回的`userid`与本地用户体系关联: ```java @Service public class WecomUserService implements UserDetailsService { @Override public UserDetails loadUserByUsername(String userid) throws UsernameNotFoundException { // 根据userid查询本地用户信息 return new User(userid, "", Collections.singletonList(new SimpleGrantedAuthority("USER"))); } } ``` ### 关键问题说明 1. **企业微信特殊参数**:需在`authorizationUri`中添加`appid=CorpID&agentid=AgentID`参数[^3] 2. **Token端点兼容性**:企业微信的Token端点返回格式为JSON,但字段名与标准OAuth2不同,需自定义解析逻辑 3. **会话管理**:建议启用`Spring Session`保证分布式环境下的会话一致性
评论 11
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值