Commit ff340509 authored by hezhen's avatar hezhen Committed by libin

123

parent 5d97c572
package com.github.wxiaoqi.security.common.util;
import javax.servlet.http.HttpServletRequest;
public class UserAgentUtil {
/**
* 关键字: 微信浏览器
*/
public static final String KEY_WEIXIN_BROWSER = "micromessenger";
/**
* 判断是否微信浏览器
*
* @param user_agent
* @return
*/
public static boolean isWexinBrowser(HttpServletRequest request) {
// 可能会出现npe
String user_agent = "";
user_agent = request.getHeader("user-agent");
// 修改如下
return user_agent != null && user_agent.toLowerCase().indexOf(KEY_WEIXIN_BROWSER) > 0;
}
}
package com.github.wxiaoqi.security.admin.rest;
import com.github.wxiaoqi.security.admin.biz.*;
import com.github.wxiaoqi.security.admin.entity.*;
import com.github.wxiaoqi.security.admin.feign.dto.AppUserDTO;
import com.github.wxiaoqi.security.admin.vo.AppUserGroups;
import com.github.wxiaoqi.security.admin.vo.AppUserInfoVo;
import com.github.wxiaoqi.security.admin.vo.AppUserVo;
import com.github.wxiaoqi.security.admin.vo.UserMemberVo;
import com.github.wxiaoqi.security.auth.client.annotation.IgnoreClientToken;
import com.github.wxiaoqi.security.auth.client.annotation.IgnoreUserToken;
import com.github.wxiaoqi.security.auth.client.config.UserAuthConfig;
import com.github.wxiaoqi.security.auth.client.jwt.UserAuthUtil;
import com.github.wxiaoqi.security.auth.common.util.jwt.IJWTInfo;
import com.github.wxiaoqi.security.common.exception.BaseException;
import com.github.wxiaoqi.security.common.msg.ObjectRestResponse;
import com.github.wxiaoqi.security.common.msg.TableResultResponse;
import com.github.wxiaoqi.security.common.rest.CommonBaseController;
import com.github.wxiaoqi.security.common.util.Query;
import com.github.wxiaoqi.security.common.util.process.ResultCode;
import com.xxfc.platform.order.feign.OrderFeign;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.beanutils.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
import javax.servlet.http.HttpServletRequest;
import java.util.List;
import java.util.Map;
import static com.github.wxiaoqi.security.common.constant.CommonConstants.SYS_TRUE;
/**
* @author keliii
*/
@Controller
@RequestMapping("demo")
@Slf4j
public class DemoController extends CommonBaseController{
@GetMapping("/app/unauth/test")
@IgnoreUserToken
@IgnoreClientToken
public String test() {
return String.format("redirect:https://xxtest.upyuns.com/h5/appHtml/view/travelDetails.html?id=96&shareType=app");
}
}
......@@ -11,5 +11,13 @@
<groupId>com.xxfc.platform</groupId>
<artifactId>xx-summit-api</artifactId>
<dependencies>
<dependency>
<groupId>com.xxfc.platform</groupId>
<artifactId>xx-universal-api</artifactId>
<version>2.0-SNAPSHOT</version>
</dependency>
</dependencies>
</project>
\ No newline at end of file
package com.xxfc.platform.summit.util;
import lombok.extern.slf4j.Slf4j;
import org.apache.http.HttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.util.EntityUtils;
import java.io.IOException;
import java.net.URLDecoder;
@Slf4j
public class HttpRequestUtil {
/**
* post请求
* @param url url地址
* @return
*/
public static String httpPost(String url){
//post请求返回结果
DefaultHttpClient httpClient = new DefaultHttpClient();
HttpPost method = new HttpPost(url);
String str = "";
try {
HttpResponse result = httpClient.execute(method);
url = URLDecoder.decode(url, "UTF-8");
/**请求发送成功,并得到响应**/
if (result.getStatusLine().getStatusCode() == 200) {
try {
/**读取服务器返回过来的json字符串数据**/
str = EntityUtils.toString(result.getEntity(),"UTF-8");
} catch (Exception e) {
log.error("post请求提交失败:" + url, e);
}
}
} catch (IOException e) {
log.error("post请求提交失败:" + url, e);
}
return str;
}
/**
* 发送get请求
* @param url 路径
* @return
*/
public static String httpGet(String url){
//get请求返回结果
String strResult = null;
try {
DefaultHttpClient client = new DefaultHttpClient();
//发送get请求
HttpGet request = new HttpGet(url);
HttpResponse response = client.execute(request);
/**请求发送成功,并得到响应**/
if (response.getStatusLine().getStatusCode() == org.apache.http.HttpStatus.SC_OK) {
/**读取服务器返回过来的json字符串数据**/
strResult = EntityUtils.toString(response.getEntity(),"UTF-8");
} else {
log.error("get请求提交失败:" + url);
}
} catch (IOException e) {
log.error("get请求提交失败:" + url, e);
}
return strResult;
}
}
package com.xxfc.platform.summit.vo;
import lombok.Data;
@Data
public class UserInfo {
private String openId;
}
package com.xxfc.platform.summit.config;
import com.github.wxiaoqi.security.auth.client.interceptor.ServiceAuthRestInterceptor;
import com.github.wxiaoqi.security.auth.client.interceptor.UserAuthRestInterceptor;
import com.github.wxiaoqi.security.common.handler.GlobalExceptionHandler;
import com.xxfc.platform.summit.interceptor.WeChatH5LoginInterceoptor;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Primary;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
import java.util.ArrayList;
import java.util.Collections;
@Configuration("tourWebConfig")
@Configuration("summitWebConfig")
@Primary
public class WebConfiguration implements WebMvcConfigurer {
......@@ -23,20 +22,13 @@ public class WebConfiguration implements WebMvcConfigurer {
@Override
public void addInterceptors(InterceptorRegistry registry) {
registry.addInterceptor(getServiceAuthRestInterceptor()).
addPathPatterns(getIncludePathPatterns());
registry.addInterceptor(getUserAuthRestInterceptor()).
registry.addInterceptor(getWeChatH5LoginRestInterceptor()).
addPathPatterns(getIncludePathPatterns());
}
@Bean
ServiceAuthRestInterceptor getServiceAuthRestInterceptor() {
return new ServiceAuthRestInterceptor();
}
@Bean
UserAuthRestInterceptor getUserAuthRestInterceptor() {
return new UserAuthRestInterceptor();
WeChatH5LoginInterceoptor getWeChatH5LoginRestInterceptor() {
return new WeChatH5LoginInterceoptor();
}
/**
......@@ -46,7 +38,7 @@ public class WebConfiguration implements WebMvcConfigurer {
private ArrayList<String> getIncludePathPatterns() {
ArrayList<String> list = new ArrayList<>();
String[] urls = {
"/summit/**"
"/summit/activity/**"
};
Collections.addAll(list, urls);
return list;
......
package com.xxfc.platform.summit.controller;
import com.github.wxiaoqi.security.auth.client.annotation.IgnoreClientToken;
import com.github.wxiaoqi.security.auth.client.annotation.IgnoreUserToken;
import com.github.wxiaoqi.security.common.msg.ObjectRestResponse;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;
@RestController
@RequestMapping("activity")
@IgnoreClientToken
@Slf4j
public class IndexController {
@RequestMapping(value ="/app/unauth/index",method = RequestMethod.GET)
@IgnoreUserToken
public ObjectRestResponse index(){
return ObjectRestResponse.succ();
}
@RequestMapping(value ="/app/unauth/info",method = RequestMethod.GET)
@IgnoreUserToken
public ObjectRestResponse info(){
return ObjectRestResponse.succ("123456");
}
}
\ No newline at end of file
package com.xxfc.platform.summit.interceptor;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import cn.hutool.core.codec.Base64;
import com.alibaba.fastjson.JSON;
import com.github.wxiaoqi.security.common.util.UserAgentUtil;
import com.xxfc.platform.summit.service.WeixinService;
import com.xxfc.platform.summit.vo.UserInfo;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;
import com.alibaba.fastjson.JSONObject;
/**
* 微信登陆拦截器
*
* @author
*
*/
@Slf4j
public class WeChatH5LoginInterceoptor extends HandlerInterceptorAdapter {
/**
* 微信公众号自动登陆令牌的url参数名
*/
public static final String WECHAT_AUTOLOGIN_CALLBACKURL_KEY = "wechat_autologin_callback_accesstoken";
public static final String frontSessionKey = "frontWeixKey";
@Value("${wx.url}")
private String url;
@Autowired
WeixinService weixinService;
@Override
public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
String curr_domain = request.getServerName();
HttpSession session = request.getSession();
log.error("curr_domain:" + curr_domain);
log.error("address:" + request.getRequestURL().toString());
log.error("params:" + request.getQueryString());
boolean isWx = UserAgentUtil.isWexinBrowser(request);
if (isWx) {
String frontSessionValue1 = (String) session.getAttribute(frontSessionKey);
if (StringUtils.isNotBlank(frontSessionValue1)) {
String frontSessionValue = new String(Base64.decode(frontSessionValue1), "utf-8");
return true;
}
String curr_url = request.getRequestURL().toString()
+ (StringUtils.isBlank(request.getQueryString()) ? "" : "?" + request.getQueryString());
String encrypt_curr_url = Base64.encode(curr_url);
String code = request.getParameter("code");
// 没有code, 则进行网页授权获取code
log.info("curr_url=====" + curr_url + "-----code=" + code);
if (StringUtils.isBlank(code)) {
String redirec_url=url+"?" + WECHAT_AUTOLOGIN_CALLBACKURL_KEY+ "=" + encrypt_curr_url;
String oauth_api=weixinService.getAuthorize(redirec_url);
log.info("curr_url=====" + curr_url);
response.sendRedirect(oauth_api);
return false;
}
// 有code, 换取openid
String openid = null;
String access_token = null;
try {
log.info("调用微信网页授权接口code=" + code);
JSONObject access_token_json=weixinService.getAccessToken(code);
if (access_token_json == null || StringUtils.isNotBlank(access_token_json.getString("errcode"))) {
log.info("err: " + JSON.toJSONString(access_token_json));
log.info("调用微信网页授权接口失败, appid或者appsecret不正确");
return false;
}
openid = access_token_json.getString("openid").trim();
access_token = access_token_json.getString("access_token");
UserInfo userInfo=new UserInfo();
userInfo.setOpenId(openid);
log.error("UserInfo===" + JSONObject.toJSONString(userInfo));
String encode = Base64.encode(JSONObject.toJSONString(userInfo));
session.removeAttribute(frontSessionKey);
session.setAttribute(frontSessionKey, encode);
} catch (Exception e) {
log.info("【" + curr_url + "】获取access_token失败");
return false;
}
// 重定向到原来地址后进行自动登陆
String encrypt_callbackurl = request.getParameter(WECHAT_AUTOLOGIN_CALLBACKURL_KEY);
String decrypt_callbackurl =Base64.encode(encrypt_callbackurl.getBytes("utf-8"));
log.error("decrypt_callbackurl===" + decrypt_callbackurl);
response.sendRedirect(decrypt_callbackurl);
return false;
}
return true;
}
}
package com.xxfc.platform.summit.service;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.xxfc.platform.summit.util.HttpRequestUtil;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
@Service
public class WeixinService {
/**
* 网页
*/
@Value("${wx.appid}")
private String wy_appid;
@Value("${wx.appSercet}")
private String wy_secret;
public JSONObject getAccessToken(String code){
String url = "https://api.weixin.qq.com/sns/oauth2/access_token?";
String params = "appid="+wy_appid+"&secret="+wy_secret+"&code="+code+"&grant_type=authorization_code";
String result = HttpRequestUtil.httpGet(url + params);
JSONObject data = JSON.parseObject(result);
return data;
}
public JSONObject getValidateData(String access_token,String openid){
String url = "https://api.weixin.qq.com/sns/auth?access_token=" + access_token + "&openid=" + openid;
String result = HttpRequestUtil.httpGet(url);
JSONObject data = JSON.parseObject(result);
return data;
}
public JSONObject getRefreshToken(String refresh_token){
String url = "https://api.weixin.qq.com/sns/oauth2/refresh_token?appid=" + wy_appid + "&grant_type=refresh_token&refresh_token=" + refresh_token;
String result = HttpRequestUtil.httpGet(url);
JSONObject data = JSON.parseObject(result);
return data;
}
public JSONObject getUserInfo(String access_token,String openid){
String url = "https://api.weixin.qq.com/sns/userinfo?access_token=" + access_token + "&openid=" + openid + "&lang=zh_CN";
String result = HttpRequestUtil.httpGet(url);
JSONObject data = JSON.parseObject(result);
return data;
}
public String getAuthorize(String redirec_url){
String oauth_api = "https://open.weixin.qq.com/connect/oauth2/authorize?appid={APPID}&redirect_uri={REDIRECT_URI}&response_type=code&scope={SCOPE}&state={STATE}#wechat_redirect";
oauth_api = oauth_api.replace("{APPID}", wy_appid)
.replace("{REDIRECT_URI}", redirec_url)
.replace("{SCOPE}", "snsapi_userinfo").replace("{STATE}", "state");
return oauth_api;
}
}
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment