1.什么是OAuth2.0:
OAuth是一个开放协议,允许用户让第三方应用以安全且标准的方式获取该用户在某一网站、应用上存储的私密的资源(如用户个人信息、照片、视频、联系人列表),而无需将用户名和密码提供给第三方应用。(一般是对接比较大的公司)
OAuth允许用户提供一个令牌,openId 而不是用户名和密码来访问他们存放在特定服务提供者的数据
2.微信公众平台OAuth2.0授权详细步骤:
1.用户点击授权页面,向服务器发出请求
2.第三方服务器询问用户是否同意授权给微信公众号
3.用户同意
4.微信服务器重定向至第三方,返回code,第三方服务器通过code获取accessTokenUrl链接
5.第三方服务器请求accessTokenUrl链接,获取到accessToken
6.根据accessToken,openId获取userInfoUrl
7.第三方服务器请求userInfoUrl链接,获取用户信息
请求:127.0.0.1:8080/authorizedUrl
用户同意:
登录成功获取到用户信息
3.修改微信公众平台配置流程:
1.微信公众平台接口测试帐号申请链接
https://mp.weixin.qq.com/debug/cgi-bin/sandbox?t=sandbox/login
2.将appID,appsecret写到配置文件中
3.关注测试公众号
4.修改回调地址 不能带有http:// 还有/ 等
4.代码部分:
构造页面授权链接
https://mp.weixin.qq.com/wiki?t=resource/res_main&id=mp1421140842
application.yml
appid: 此处为以上页面的appID
secret: 此处为以上页面的appsecret
redirectUri: http://127.0.0.1:8080/callback
### 生成微信授权
authorizedUrl: https://open.weixin.qq.com/connect/oauth2/authorize?appid=APPID&redirect_uri=REDIRECT_URI&response_type=code&scope=snsapi_userinfo&state=STATE#wechat_redirect
###获取code后,请求以下链接获取access_token
access_token: https://api.weixin.qq.com/sns/oauth2/access_token?appid=APPID&secret=SECRET&code=CODE&grant_type=authorization_code
###拉取用户信息(需scope为 snsapi_userinfo)
userinfo: https://api.weixin.qq.com/sns/userinfo?access_token=ACCESS_TOKEN&openid=OPENID&lang=zh_CN
BaseApiService
@Component
public class BaseApiService {
public ResponseBase setResultError(Integer code, String msg) {
return setResult(code, msg, null);
}
// 返回错误,可以传msg
public ResponseBase setResultError(String msg) {
return setResult(Constants.HTTP_RES_CODE_500, msg, null);
}
// 返回成功,可以传data值
public ResponseBase setResultSuccessData(Object data) {
return setResult(Constants.HTTP_RES_CODE_200, Constants.HTTP_RES_CODE_200_VALUE, data);
}
public ResponseBase setResultSuccessData(Integer code, Object data) {
return setResult(code, Constants.HTTP_RES_CODE_200_VALUE, data);
}
// 返回成功,沒有data值
public ResponseBase setResultSuccess() {
return setResult(Constants.HTTP_RES_CODE_200, Constants.HTTP_RES_CODE_200_VALUE, null);
}
// 返回成功,沒有data值
public ResponseBase setResultSuccess(String msg) {
return setResult(Constants.HTTP_RES_CODE_200, msg, null);
}
// 通用封装
public ResponseBase setResult(Integer code, String msg, Object data) {
return new ResponseBase(code, msg, data);
}
}
ResponseBase
@Getter
@Setter
@Slf4j
public class ResponseBase {
private Integer rtnCode;
private String msg;
private Object data;
public ResponseBase() {
}
public ResponseBase(Integer rtnCode, String msg, Object data) {
super();
this.rtnCode = rtnCode;
this.msg = msg;
this.data = data;
}
public static void main(String[] args) {
ResponseBase responseBase = new ResponseBase();
responseBase.setData("123456");
responseBase.setMsg("success");
responseBase.setRtnCode(200);
System.out.println(responseBase.toString());
log.info("itmayiedu...");
}
@Override
public String toString() {
return "ResponseBase [rtnCode=" + rtnCode + ", msg=" + msg + ", data=" + data + "]";
}
}
WeiXinUtils
@Component
public class WeiXinUtils {
@Value("${appid}")
private String appId;
@Value("${secret}")
private String secret;
@Value("${redirecturi}")
private String redirectUri;
@Value("${authorizedUrl}")
private String authorizedUrl;
@Value("${access_token}")
private String accessToken;
@Value("${userinfo}")
private String userinfo;
public String getAuthorizedUrl() {
return authorizedUrl.replace("APPID", appId).replace("REDIRECT_URI", URLEncoder.encode(redirectUri));
}
public String getAccessTokenUrl(String code) {
return accessToken.replace("APPID", appId).replace("SECRET", secret).replace("CODE", code);
}
public String getUserInfo(String accessToken, String openId) {
return userinfo.replace("ACCESS_TOKEN", accessToken).replace("OPENID", openId);
}
}
HttpClientUtils
public class HttpClientUtils {
private static Logger logger = LoggerFactory.getLogger(HttpClientUtils.class); // 日志记录
private static RequestConfig requestConfig = null;
static {
// 设置请求和传输超时时间
requestConfig = RequestConfig.custom().setSocketTimeout(2000).setConnectTimeout(2000).build();
}
/**
* post请求传输json参数
*
* @param url
* url地址
* @param json
* 参数
* @return
*/
public static JSONObject httpPost(String url, JSONObject jsonParam) {
// post请求返回结果
CloseableHttpClient httpClient = HttpClients.createDefault();
JSONObject jsonResult = null;
HttpPost httpPost = new HttpPost(url);
// 设置请求和传输超时时间
httpPost.setConfig(requestConfig);
try {
if (null != jsonParam) {
// 解决中文乱码问题
StringEntity entity = new StringEntity(jsonParam.toString(), "utf-8");
entity.setContentEncoding("UTF-8");
entity.setContentType("application/json");
httpPost.setEntity(entity);
}
CloseableHttpResponse result = httpClient.execute(httpPost);
// 请求发送成功,并得到响应
if (result.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
String str = "";
try {
// 读取服务器返回过来的json字符串数据
str = EntityUtils.toString(result.getEntity(), "utf-8");
// 把json字符串转换成json对象
jsonResult = JSONObject.parseObject(str);
} catch (Exception e) {
logger.error("post请求提交失败:" + url, e);
}
}
} catch (IOException e) {
logger.error("post请求提交失败:" + url, e);
} finally {
httpPost.releaseConnection();
}
return jsonResult;
}
/**
* post请求传输String参数 例如:name=Jack&sex=1&type=2
* Content-type:application/x-www-form-urlencoded
*
* @param url
* url地址
* @param strParam
* 参数
* @return
*/
public static JSONObject httpPost(String url, String strParam) {
// post请求返回结果
CloseableHttpClient httpClient = HttpClients.createDefault();
JSONObject jsonResult = null;
HttpPost httpPost = new HttpPost(url);
httpPost.setConfig(requestConfig);
try {
if (null != strParam) {
// 解决中文乱码问题
StringEntity entity = new StringEntity(strParam, "utf-8");
entity.setContentEncoding("UTF-8");
entity.setContentType("application/x-www-form-urlencoded");
httpPost.setEntity(entity);
}
CloseableHttpResponse result = httpClient.execute(httpPost);
// 请求发送成功,并得到响应
if (result.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
String str = "";
try {
// 读取服务器返回过来的json字符串数据
str = EntityUtils.toString(result.getEntity(), "utf-8");
// 把json字符串转换成json对象
jsonResult = JSONObject.parseObject(str);
} catch (Exception e) {
logger.error("post请求提交失败:" + url, e);
}
}
} catch (IOException e) {
logger.error("post请求提交失败:" + url, e);
} finally {
httpPost.releaseConnection();
}
return jsonResult;
}
/**
* 发送get请求
*
* @param url
* 路径
* @return
*/
public static JSONObject httpGet(String url) {
// get请求返回结果
JSONObject jsonResult = null;
CloseableHttpClient client = HttpClients.createDefault();
// 发送get请求
HttpGet request = new HttpGet(url);
request.setConfig(requestConfig);
try {
CloseableHttpResponse response = client.execute(request);
// 请求发送成功,并得到响应
if (response.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
// 读取服务器返回过来的json字符串数据
HttpEntity entity = response.getEntity();
String strResult = EntityUtils.toString(entity, "utf-8");
// 把json字符串转换成json对象
jsonResult = JSONObject.parseObject(strResult);
} else {
logger.error("get请求提交失败:" + url);
}
} catch (IOException e) {
logger.error("get请求提交失败:" + url, e);
} finally {
request.releaseConnection();
}
return jsonResult;
}
}
OauthController
@Controller
public class OauthController extends BaseApiService {
@Autowired
private WeiXinUtils weiXinUtils;
private String errorPage = "errorPage";
// 生成授权链接
@RequestMapping("/authorizedUrl")
public String authorizedUrl() {
return "redirect:" + weiXinUtils.getAuthorizedUrl();
}
// 微信授权回调地址
@RequestMapping("/callback")
public String callback(String code, HttpServletRequest request) {
// 1.使用Code 获取 access_token
String accessTokenUrl = weiXinUtils.getAccessTokenUrl(code);
//通过请求获取的accessTokenUrl链接 获取到accessToken
JSONObject resultAccessToken = HttpClientUtils.httpGet(accessTokenUrl);
boolean containsKey = resultAccessToken.containsKey("errcode");
if (containsKey) {
request.setAttribute("errorMsg", "系统错误!");
return errorPage;
}
// 2.使用access_token获取用户信息
String accessToken = resultAccessToken.getString("access_token");
String openid = resultAccessToken.getString("openid");
// 3.拉取用户信息(需scope为 snsapi_userinfo)
String userInfoUrl = weiXinUtils.getUserInfo(accessToken, openid);
JSONObject userInfoResult = HttpClientUtils.httpGet(userInfoUrl);
System.out.println("userInfoResult:" + userInfoResult);
request.setAttribute("nickname", userInfoResult.getString("nickname"));
request.setAttribute("city", userInfoResult.getString("city"));
request.setAttribute("headimgurl", userInfoResult.getString("headimgurl"));
return "info";
}
}