Kaynağa Gözat

优化微信登录

xiongzhu 7 yıl önce
ebeveyn
işleme
f6e4cb3a06

+ 18 - 43
src/main/java/com/izouma/awesomeadmin/service/OSSFileService.java

@@ -22,44 +22,39 @@ public class OSSFileService {
     /**
      * 日志对象
      */
-    private static Logger logger = Logger.getLogger(OSSFileService.class);
+    private static       Logger logger      = Logger.getLogger(OSSFileService.class);
+    private static final String projectName = PropertiesFileLoader.getProperties("projectname");
 
+    public String upload(InputStream fin, String path) {
+        if (path.startsWith("/")) {
+            path = path.replaceFirst("\\\\/", "");
+        }
+        path = projectName + "/" + path;
 
-    public  String upload(InputStream fin, String path) {
-
-        logger.info("UpLoadImage :上传照片 开始  : fin:" + fin + "; phth: " + path);
-        // TODO Auto-generated method stub
         String aliid = PropertiesFileLoader.getDefaultProperties("aliossid", "");
         String alikey = PropertiesFileLoader.getDefaultProperties("aliosskey", "");
         String aliossendpoit = PropertiesFileLoader.getDefaultProperties("aliossendpoit", "");
         String bucketname = PropertiesFileLoader.getDefaultProperties("alibucketname", "");
+        logger.info(String.format("OSS上传:\naliid: %s\nalikey: %s\naliossendpoit: %s\nbucketname: %s\npath: %s", aliid, alikey, aliossendpoit, bucketname, path));
+
         OSSClient client = new OSSClient(aliossendpoit, aliid, alikey);
         OSSObject object = null;
-        logger.info("UpLoadImage :上传照片  : aliid:" + aliid + "; alikey: " + alikey + "; aliossendpoit : " + aliossendpoit + "; bucketname:"
-                + bucketname);
-        if (path.startsWith("/")) {
-            return "invalid path";
-        }
-        @SuppressWarnings("unused")
-        PutObjectResult result = client.putObject(bucketname, path, fin, new ObjectMetadata());
-
         try {
+            client.putObject(bucketname, path, fin, new ObjectMetadata());
             object = client.getObject(bucketname, path);
         } catch (Exception r) {
-            logger.error("UpLoadImage: 上传照片异常 ", r);
+            logger.error("OSS上传异常:", r);
         }
         // 如果不设置content-length, 默认为chunked编码。
         if (object != null) {
-            return GetRealImagePath(path);
+            return getFullPath(path);
         }
         return null;
     }
 
 
-    public static String GetRealImagePath(String Path) {
-
-        // TODO Auto-generated method stub
-        if (Path == null || "".equals(Path) || Path.startsWith("images")) {
+    private static String getFullPath(String Path) {
+        if (Path == null || "".equals(Path)) {
             return Path;
         }
         String aliossendpoit = PropertiesFileLoader.getDefaultProperties("aliImageSever", "");
@@ -68,38 +63,20 @@ public class OSSFileService {
 
 
     public String uploadImg(String base64) throws UnsupportedEncodingException {
-
-        String path = "izouma/application/";
-
         try {
             logger.info("uploadIcon:上传图片");
 
-            //图片原名称
-            String imgName = "";
-            //图片生成名称
-            String fileName = "";
             if (base64 == null) {
                 return null;
             }
-            String type = ".jpg";
-            Date nowDate = new Date();
-            //格式化时间对象返回字符串
-            SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddhhmmss");
-            fileName += sdf.format(nowDate);
             Random random = new Random();
-            String randomCode = "";
+            StringBuilder randomCode = new StringBuilder();
             for (int i = 0; i < 8; i++) {
-                randomCode += Integer.toString(random.nextInt(36), 36);
+                randomCode.append(Integer.toString(random.nextInt(36), 36));
             }
-            fileName += randomCode;
-            fileName += type;
-            String virtualPath = "";
             try {
-                virtualPath = path + "/" + fileName;
-                //item.write(new File(uploadPath + fileName));
-                String result = upload(ImagesUtil.GenerateImage(base64), virtualPath);
-                System.out.println("存入照片:" + result);
-                return result;
+                String path = String.format("images/%s-%s.jpg", new SimpleDateFormat("yyyy-MM-dd-hh-mm-ss").format(new Date()), randomCode);
+                return upload(ImagesUtil.GenerateImage(base64), path);
             } catch (Exception e) {
                 e.printStackTrace();
             }
@@ -107,9 +84,7 @@ public class OSSFileService {
             e.printStackTrace();
             logger.error("上传图片异常");
         }
-
         return null;
-
     }
 
 }

+ 1 - 1
src/main/java/com/izouma/awesomeadmin/service/UserInfoService.java

@@ -36,7 +36,7 @@ public interface UserInfoService {
 
     List<String> findUserByRoleName(String roleName);
 
-    UserInfo loginWeiXin(String openId, String nickname, String sex, String headimgurl);
+    UserInfo loginWechat(String code) throws UserInfoServiceImpl.LoginException;
 
 }
 

+ 93 - 63
src/main/java/com/izouma/awesomeadmin/service/impl/UserInfoServiceImpl.java

@@ -1,20 +1,19 @@
 package com.izouma.awesomeadmin.service.impl;
 
-import java.io.IOException;
-import java.net.HttpURLConnection;
-import java.net.URL;
-import java.text.SimpleDateFormat;
-import java.util.*;
-
+import com.fasterxml.jackson.databind.ObjectMapper;
 import com.izouma.awesomeadmin.constant.AppConstant;
 import com.izouma.awesomeadmin.dao.DepartInfoMapper;
 import com.izouma.awesomeadmin.dao.SysAppTokenMapper;
 import com.izouma.awesomeadmin.dao.SysRoleMapper;
+import com.izouma.awesomeadmin.dao.UserInfoMapper;
 import com.izouma.awesomeadmin.dto.Page;
+import com.izouma.awesomeadmin.model.UserInfo;
 import com.izouma.awesomeadmin.service.OSSFileService;
+import com.izouma.awesomeadmin.service.UserInfoService;
 import com.izouma.awesomeadmin.shiro.AppToken;
 import com.izouma.awesomeadmin.util.MD5Util;
 import com.izouma.awesomeadmin.util.PropertiesFileLoader;
+import com.izouma.awesomeadmin.util.WeixinUtil;
 import io.jsonwebtoken.Claims;
 import io.jsonwebtoken.Jwt;
 import io.jsonwebtoken.Jwts;
@@ -23,14 +22,17 @@ import io.rong.RongCloud;
 import io.rong.models.SMSVerifyCodeResult;
 import org.apache.commons.lang.StringUtils;
 import org.apache.log4j.Logger;
+import org.json.JSONException;
+import org.json.JSONObject;
 import org.springframework.beans.factory.annotation.Autowired;
 import org.springframework.stereotype.Service;
 
-import com.izouma.awesomeadmin.dao.UserInfoMapper;
-import com.izouma.awesomeadmin.model.UserInfo;
-import com.izouma.awesomeadmin.service.UserInfoService;
-
 import javax.crypto.SecretKey;
+import java.io.IOException;
+import java.net.HttpURLConnection;
+import java.net.URL;
+import java.text.SimpleDateFormat;
+import java.util.*;
 
 /**
  * user_info service接口实现类
@@ -42,7 +44,6 @@ public class UserInfoServiceImpl implements UserInfoService {
     private static Logger    logger    = Logger.getLogger(UserInfoServiceImpl.class);
     private        RongCloud rongCloud = RongCloud.getInstance(PropertiesFileLoader.getProperties("rongyunappkey"), PropertiesFileLoader.getProperties("rongyunappsecret"));
 
-
     @Autowired
     private UserInfoMapper    userInfoMapper;
     @Autowired
@@ -51,9 +52,8 @@ public class UserInfoServiceImpl implements UserInfoService {
     private DepartInfoMapper  departInfoMapper;
     @Autowired
     private SysAppTokenMapper sysAppTokenMapper;
-
     @Autowired
-    private OSSFileService ossFileService;
+    private OSSFileService    ossFileService;
 
     @Override
     public List<UserInfo> getUserInfoList(UserInfo record) {
@@ -285,65 +285,95 @@ public class UserInfoServiceImpl implements UserInfoService {
     }
 
     @Override
-    public UserInfo loginWeiXin(String openId, String nickname, String sex, String headimgurl) {
-        logger.info("loginWeiXin");
+    public UserInfo loginWechat(String code) {
         try {
+            final String APP_ID = PropertiesFileLoader.getProperties("weixinappid");
+            final String APP_SECRET = PropertiesFileLoader.getProperties("weixinsecret");
+
+            String accessTokenUrl = "https://api.weixin.qq.com/sns/oauth2/access_token?appid=" + APP_ID + "&secret=" + APP_SECRET + "&code=" + code
+                    + "&grant_type=authorization_code";
+            JSONObject data = WeixinUtil.loadJSON(accessTokenUrl);
+            logger.debug("微信授权获取access_token:\n" + data.toString(4));
+            String openId = data.getString("openid");
+            String access_token = data.getString("access_token");
+
+            String userDataUrl = "https://api.weixin.qq.com/sns/userinfo?access_token=" + access_token + "&openid=" + openId;
+            JSONObject userData = WeixinUtil.loadJSON(userDataUrl);
+            logger.debug("微信授权获取用户信息:\n" + userData.toString(4));
+
             UserInfo userInfo = new UserInfo();
             userInfo.setOpenId(openId);
             userInfo = getUserInfo(userInfo);
 
-            if (userInfo == null) {
-                userInfo = new UserInfo();
-                userInfo.setUsername(nickname);
-                userInfo.setNickname(nickname);
-                userInfo.setSex(sex);
-                userInfo.setOpenId(openId);
-                if (StringUtils.isNotEmpty(headimgurl)) {
-                    HttpURLConnection httpUrl = null;
-                    URL iconUrl = null;
-                    try {
-                        iconUrl = new URL(headimgurl);
-                        httpUrl = (HttpURLConnection) iconUrl.openConnection();
-                        httpUrl.connect();
-                        // 图片生成名称
-                        String fileName = "";
-                        Date nowDate = new Date();
-                        // 格式化时间对象返回字符串
-                        SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddhhmmss");
-                        fileName += sdf.format(nowDate);
-                        Random random = new Random();
-                        String randomCode = "";
-                        for (int i = 0; i < 8; i++) {
-                            randomCode += Integer.toString(random.nextInt(36), 36);
-                        }
-                        fileName += randomCode;
-                        String virtualPath = "awesomeAdmin/application/" + fileName + ".jpg";
-                        // item.write(new File(uploadPath + fileName));
-                        String result = ossFileService.upload(httpUrl.getInputStream(), virtualPath);
-                        System.out.println("存入照片:" + result);
-                        userInfo.setIcon(result);
-                    } catch (IOException e) {
-                        e.printStackTrace();
-                    } finally {
-                        if (httpUrl != null) {
-                            httpUrl.disconnect();
-                        }
-                    }
-                } else {
-
-                    userInfo.setIcon("https://microball.oss-cn-hangzhou.aliyuncs.com/huanbaojia/icon_morentouxiang.png");
-                }
-                if (!createUserInfo(userInfo)) {
-                    return null;
-                }
+            if (userInfo != null) {
+                return userInfo;
+            }
+            userInfo = new UserInfo();
+            userInfo.setOpenId(openId);
+            String nickname = userData.getString("nickname");
+            userInfo.setNickname(nickname);
+            userInfo.setUsername(nickname);
+            try {
+                String country = userData.getString("country");
+                userInfo.setCountry(country);
+            } catch (JSONException ignored) {
+            }
+            try {
+                String province = userData.getString("province");
+                userInfo.setProvince(province);
+            } catch (JSONException ignored) {
+            }
+            try {
+                String city = userData.getString("city");
+                userInfo.setCity(city);
+            } catch (JSONException ignored) {
+            }
+            int sex = 1;
+            try {
+                sex = userData.getInt("sex");
+            } catch (JSONException ignored) {
+            }
+            userInfo.setSex(sex == 1 ? "男" : "女");
+            String headimgurl = null;
+            try {
+                headimgurl = userData.getString("headimgurl");
+            } catch (JSONException ignored) {
+            }
+            userInfo.setIcon(saveAvatar(headimgurl));
+            if (createUserInfo(userInfo)) {
+                return userInfo;
             }
-
-            return userInfo;
-
         } catch (Exception e) {
-            logger.error("loginWeiXin", e);
+            logger.error("loginWechat", e);
         }
         return null;
     }
+
+    private String saveAvatar(String url) {
+        String path;
+        HttpURLConnection httpUrl = null;
+        URL iconUrl = null;
+        try {
+            iconUrl = new URL(url);
+            httpUrl = (HttpURLConnection) iconUrl.openConnection();
+            httpUrl.connect();
+
+            Random random = new Random();
+            StringBuilder randomCode = new StringBuilder();
+            for (int i = 0; i < 8; i++) {
+                randomCode.append(Integer.toString(random.nextInt(36), 36));
+            }
+            String uploadPath = String.format("images/%s-%s.jpg", new SimpleDateFormat("yyyy-MM-dd-hh-mm-ss").format(new Date()), randomCode);
+            path = ossFileService.upload(httpUrl.getInputStream(), uploadPath);
+        } catch (IOException e) {
+            path = "https://microball.oss-cn-hangzhou.aliyuncs.com/huanbaojia/icon_morentouxiang.png";
+            e.printStackTrace();
+        } finally {
+            if (httpUrl != null) {
+                httpUrl.disconnect();
+            }
+        }
+        return path;
+    }
 }
 

+ 8 - 9
src/main/java/com/izouma/awesomeadmin/shiro/WeiXinCodeRealm.java → src/main/java/com/izouma/awesomeadmin/shiro/WechatRealm.java

@@ -1,24 +1,23 @@
 package com.izouma.awesomeadmin.shiro;
 
 import com.izouma.awesomeadmin.model.UserInfo;
+import com.izouma.awesomeadmin.service.impl.UserInfoServiceImpl;
 import org.apache.shiro.authc.AuthenticationException;
 import org.apache.shiro.authc.AuthenticationInfo;
 import org.apache.shiro.authc.AuthenticationToken;
 import org.apache.shiro.authc.SimpleAuthenticationInfo;
 
-public class WeiXinCodeRealm extends BaseRealm {
+public class WechatRealm extends BaseRealm {
 
     @Override
     protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {
         UserInfo userInfo = null;
-        WeiXinCodeToken weiXinCodeToken = (WeiXinCodeToken) token;
-
-        userInfo = userInfoService.loginWeiXin(weiXinCodeToken.getOpenId(), weiXinCodeToken.getNickname(), weiXinCodeToken.getSex(), weiXinCodeToken.getHeadimgurl());
-        if (userInfo == null) {
-            throw new AuthenticationException("登录失败");
+        WechatToken wechatToken = (WechatToken) token;
+        try {
+            userInfo = userInfoService.loginWechat(wechatToken.getCode());
+            return new SimpleAuthenticationInfo(userInfo, token.getCredentials(), this.getName());
+        } catch (UserInfoServiceImpl.LoginException e) {
+            throw new AuthenticationException(e.getMessage());
         }
-        return new SimpleAuthenticationInfo(userInfo, token.getCredentials(), this.getName());
-
-
     }
 }

+ 32 - 0
src/main/java/com/izouma/awesomeadmin/shiro/WechatToken.java

@@ -0,0 +1,32 @@
+package com.izouma.awesomeadmin.shiro;
+
+import org.apache.shiro.authc.AuthenticationToken;
+
+public class WechatToken implements AuthenticationToken {
+    private String code;
+
+    public WechatToken() {
+    }
+
+    public WechatToken(String code) {
+        this.code = code;
+    }
+
+    public String getCode() {
+        return code;
+    }
+
+    public void setCode(String code) {
+        this.code = code;
+    }
+
+    @Override
+    public Object getPrincipal() {
+        return code;
+    }
+
+    @Override
+    public Object getCredentials() {
+        return code;
+    }
+}

+ 0 - 93
src/main/java/com/izouma/awesomeadmin/shiro/WeiXinCodeToken.java

@@ -1,93 +0,0 @@
-package com.izouma.awesomeadmin.shiro;
-
-import org.apache.shiro.authc.HostAuthenticationToken;
-import org.apache.shiro.authc.RememberMeAuthenticationToken;
-
-public class WeiXinCodeToken implements HostAuthenticationToken, RememberMeAuthenticationToken {
-
-    private boolean rememberMe;
-    private String host;
-    private String code;
-    private String openId;
-    private String nickname;
-    private String sex;
-
-    private String headimgurl;
-
-    public WeiXinCodeToken(String code, String openId, String nickname, String sex, String headimgurl) {
-        this.code = code;
-        this.openId = openId;
-        this.nickname = nickname;
-        this.sex = sex;
-        this.headimgurl = headimgurl;
-    }
-
-    public void setRememberMe(boolean rememberMe) {
-        this.rememberMe = rememberMe;
-    }
-
-    public void setHost(String host) {
-        this.host = host;
-    }
-
-
-    public String getCode() {
-        return code;
-    }
-
-    public void setCode(String code) {
-        this.code = code;
-    }
-
-    public String getOpenId() {
-        return openId;
-    }
-
-    public void setOpenId(String openId) {
-        this.openId = openId;
-    }
-
-    @Override
-    public String getHost() {
-        return host;
-    }
-
-    @Override
-    public boolean isRememberMe() {
-        return rememberMe;
-    }
-
-    @Override
-    public Object getPrincipal() {
-        return openId;
-    }
-
-    @Override
-    public Object getCredentials() {
-        return code;
-    }
-
-    public String getSex() {
-        return sex;
-    }
-
-    public void setSex(String sex) {
-        this.sex = sex;
-    }
-
-    public String getHeadimgurl() {
-        return headimgurl;
-    }
-
-    public void setHeadimgurl(String headimgurl) {
-        this.headimgurl = headimgurl;
-    }
-
-    public String getNickname() {
-        return nickname;
-    }
-
-    public void setNickname(String nickname) {
-        this.nickname = nickname;
-    }
-}

+ 16 - 23
src/main/java/com/izouma/awesomeadmin/web/AssetsController.java

@@ -15,7 +15,8 @@ import org.springframework.web.multipart.commons.CommonsMultipartResolver;
 import javax.servlet.http.HttpServletRequest;
 import java.io.IOException;
 import java.io.UnsupportedEncodingException;
-import java.util.Iterator;
+import java.text.SimpleDateFormat;
+import java.util.*;
 
 /**
  * Created by xiongzhu on 2017/3/8.
@@ -27,10 +28,9 @@ public class AssetsController {
     @Autowired
     private OSSFileService OSSFileService;
 
-
     @RequestMapping(value = "/uploadImg", method = RequestMethod.POST)
     @ResponseBody
-    public Result uploadImg(@RequestParam(value = "base64", required = true) String base64) {
+    public Result uploadImg(@RequestParam("base64") String base64) {
 
         try {
             String path = OSSFileService.uploadImg(base64);
@@ -41,40 +41,33 @@ public class AssetsController {
         return new Result(false, "上传失败");
     }
 
-
     @RequestMapping(value = "/uploadFile")
     @ResponseBody
     public Result uploadFile(HttpServletRequest request) {
-
-        long startTime = System.currentTimeMillis();
-        //将当前上下文初始化给  CommonsMutipartResolver (多部分解析器)
         CommonsMultipartResolver multipartResolver = new CommonsMultipartResolver(request.getSession().getServletContext());
-        //检查form中是否有enctype="multipart/form-data"
         if (multipartResolver.isMultipart(request)) {
-            //将request变成多部分request
             MultipartHttpServletRequest multiRequest = (MultipartHttpServletRequest) request;
-            //获取multiRequest 中所有的文件名
-            Iterator iter = multiRequest.getFileNames();
-
-            String paths = "";
-
-            while (iter.hasNext()) {
-                //一次遍历所有文件
-                MultipartFile file = multiRequest.getFile(iter.next().toString());
+            Iterator it = multiRequest.getFileNames();
+            List<String> paths = new ArrayList<>();
+            while (it.hasNext()) {
+                MultipartFile file = multiRequest.getFile(it.next().toString());
                 if (file != null) {
                     try {
-                        String path = OSSFileService.upload(file.getInputStream(), "izouma/application/" + System.currentTimeMillis()
-                                + file.getOriginalFilename().replaceAll(".+\\.", "."));
-                        paths += path + ";";
-
+                        Random random = new Random();
+                        StringBuilder randomCode = new StringBuilder();
+                        for (int i = 0; i < 8; i++) {
+                            randomCode.append(Integer.toString(random.nextInt(36), 36));
+                        }
+                        String uploadPath = String.format("images/%s-%s.jpg", new SimpleDateFormat("yyyy-MM-dd-hh-mm-ss").format(new Date()), randomCode);
+                        String path = OSSFileService.upload(file.getInputStream(), uploadPath);
+                        paths.add(path);
                     } catch (IOException e) {
                         e.printStackTrace();
                         return new Result(false, "上传失败");
                     }
                 }
-
             }
-            return new Result(true, paths.split(";"));
+            return new Result(true, paths);
         }
         return new Result(false, "上传失败");
     }

+ 35 - 150
src/main/java/com/izouma/awesomeadmin/web/WeiXinController.java

@@ -4,27 +4,21 @@ import com.izouma.awesomeadmin.dto.Result;
 import com.izouma.awesomeadmin.model.UserInfo;
 import com.izouma.awesomeadmin.service.UserInfoService;
 import com.izouma.awesomeadmin.service.WeiXinService;
-import com.izouma.awesomeadmin.shiro.WeiXinCodeToken;
-import com.izouma.awesomeadmin.util.CookieUtil;
+import com.izouma.awesomeadmin.shiro.WechatToken;
+import com.izouma.awesomeadmin.util.Base64;
 import com.izouma.awesomeadmin.util.PropertiesFileLoader;
 import com.izouma.awesomeadmin.util.WeixinUtil;
-import org.activiti.engine.IdentityService;
+import org.apache.commons.lang.StringUtils;
 import org.apache.log4j.Logger;
 import org.apache.shiro.SecurityUtils;
-import org.apache.shiro.authc.AuthenticationException;
 import org.apache.shiro.subject.Subject;
 import org.json.JSONObject;
 import org.springframework.beans.factory.annotation.Autowired;
 import org.springframework.stereotype.Controller;
-import org.springframework.web.bind.annotation.RequestMapping;
-import org.springframework.web.bind.annotation.RequestMethod;
-import org.springframework.web.bind.annotation.RequestParam;
-import org.springframework.web.bind.annotation.ResponseBody;
+import org.springframework.web.bind.annotation.*;
 import org.springframework.web.servlet.ModelAndView;
 
 import javax.servlet.http.HttpServletRequest;
-import javax.servlet.http.HttpServletResponse;
-import javax.servlet.http.HttpSession;
 import java.util.Map;
 
 @Controller
@@ -39,160 +33,53 @@ public class WeiXinController {
     @Autowired
     private UserInfoService userInfoService;
 
-    @Autowired
-    private IdentityService identityService;
-
-
-    @RequestMapping(value = "/getSignature", method = RequestMethod.GET)
-    @ResponseBody
-    public Map<String, String> getSignature(HttpServletRequest request) {
-
-        String shareUrl = request.getParameter("shareUrl");
-        return weiXinService.getSignature(shareUrl);
-
-    }
-
-
     @RequestMapping(value = "/auth", method = RequestMethod.GET)
     @ResponseBody
     public ModelAndView auth(@RequestParam("redirectUri") String redirectUri) {
-
-        return new ModelAndView("redirect:https://open.weixin.qq.com/connect/oauth2/authorize?appid=" + PropertiesFileLoader.getProperties("weixinappid")
-                + "&redirect_uri=" + "http://xjw.izouma.com/wx/redirectLogin?redirectUri=" + redirectUri
+        if (StringUtils.isNotEmpty(redirectUri)) {
+            redirectUri = Base64.getBase64(redirectUri);
+        } else {
+            redirectUri = "";
+        }
+        String wxRedirectUri = PropertiesFileLoader.getProperties("host")
+                + "/wx/doAuth/" + redirectUri;
+        return new ModelAndView("redirect:https://open.weixin.qq.com/connect/oauth2/authorize?appid="
+                + PropertiesFileLoader.getProperties("weixinappid")
+                + "&redirect_uri=" + wxRedirectUri
                 + "&response_type=code&scope=snsapi_userinfo&state=STATE#wechat_redirect");
     }
 
-
-    @RequestMapping(value = "/redirectLogin", method = RequestMethod.GET)
-    @ResponseBody
-    public ModelAndView redirectLogin(HttpServletRequest request, HttpServletResponse response,
-                                      @RequestParam(required = true, value = "code") String code, @RequestParam(required = false, value = "redirectUri") String redirectUri) {
-
-        ModelAndView mav = new ModelAndView("redirect:http://xjw.izouma.com/#/" + redirectUri);
-        final String APP_ID = PropertiesFileLoader.getProperties("weixinappid");
-        final String APP_SECRET = PropertiesFileLoader.getProperties("weixinsecret");
+    @RequestMapping("/doAuth/{redirectUri}")
+    public ModelAndView doAuth(@RequestParam("code") String code, @PathVariable("redirectUri") String redirectUri) {
+        ModelAndView modelAndView;
+        if (StringUtils.isNotEmpty(redirectUri)) {
+            redirectUri = Base64.getFromBase64(redirectUri);
+            modelAndView = new ModelAndView("redirect:" + redirectUri);
+        } else {
+            redirectUri = "";
+            modelAndView = new ModelAndView("redirect:/");
+        }
+        Subject subject = SecurityUtils.getSubject();
+        WechatToken wechatToken = new WechatToken(code);
         try {
-
-            // System.out.println("code : " + code);
-            String url = "https://api.weixin.qq.com/sns/oauth2/access_token?appid=" + APP_ID + "&secret=" + APP_SECRET + "&code=" + code
-                    + "&grant_type=authorization_code";
-            JSONObject data = WeixinUtil.loadJSON(url);
-            // System.out.println("data : " + data);
-
-            // System.out.println(json.toString());
-
-            String openId = (String) data.get("openid");
-
-            /**
-             * 新用户存储用户资料
-             */
-            String access_token = (String) data.get("access_token");
-            String userDataUrl = "https://api.weixin.qq.com/sns/userinfo?access_token=" + access_token + "&openid=" + openId;
-            JSONObject userData = WeixinUtil.loadJSON(userDataUrl);
-            String weixinInfo = userData.toString();
-            // System.out.println("userDate : " + userData);
-
-
-            System.out.println("loginUserInfo:" + weixinInfo);
-            JSONObject userJson = new JSONObject(weixinInfo);
-            System.out.println("userJson" + userJson);
-
-            String headimgurl = userJson.getString("headimgurl");
-            String sex = userJson.getInt("sex") != 0 ? "男" : "女";
-
-
-            Subject subject = SecurityUtils.getSubject();
-
-            WeiXinCodeToken weiXinCodeToken = new WeiXinCodeToken(code, openId, userJson.getString("nickname"), sex, headimgurl);
-            try {
-                subject.login(weiXinCodeToken);
-            } catch (AuthenticationException e) {
-                e.printStackTrace();
-                logger.error(e);
-            }
-            UserInfo user = (UserInfo) subject.getPrincipal();
-            identityService.setAuthenticatedUserId(user.getId().toString());
-            HttpSession session = request.getSession();
-            CookieUtil.addCookie(response, "JSESSIONID", session.getId(), 3 * 24 * 60 * 60);
-
+            subject.login(wechatToken);
         } catch (Exception e) {
-            e.printStackTrace();
-            return new ModelAndView("redirect:https://open.weixin.qq.com/connect/oauth2/authorize?appid=" + APP_ID + "&redirect_uri="
-                    + "http://xjw.izouma.com/wx/redirectLogin?redirectUri=" + redirectUri
-                    + "&response_type=code&scope=snsapi_userinfo&state=STATE#wechat_redirect");
+            logger.error("doAuth", e);
+            modelAndView = new ModelAndView("redirect:" + PropertiesFileLoader.getProperties("host")
+                    + "/wx/auth?redirectUri=" + redirectUri);
         }
-        return mav;
+        return modelAndView;
     }
 
-
-    /**
-     * 微信身份获取,登录验证
-     *
-     * @return
-     */
-    @RequestMapping(value = "/Login", method = RequestMethod.GET)
+    @RequestMapping(value = "/getSignature", method = RequestMethod.GET)
     @ResponseBody
-    public ModelAndView LoginService(HttpServletRequest request, HttpServletResponse response,
-                                     @RequestParam(required = true, value = "code") String code) {
-
-        ModelAndView mav = new ModelAndView("redirect:../#/");
-        final String APP_ID = PropertiesFileLoader.getProperties("weixinappid");
-        final String APP_SECRET = PropertiesFileLoader.getProperties("weixinsecret");
-        try {
-
-
-            /**
-             * 无缓存用户
-             */
-            // System.out.println("code : " + code);
-            String url = "https://api.weixin.qq.com/sns/oauth2/access_token?appid=" + APP_ID + "&secret=" + APP_SECRET + "&code=" + code
-                    + "&grant_type=authorization_code";
-            JSONObject data = WeixinUtil.loadJSON(url);
-            logger.error("Login微信身份获取,登录验证 data : " + data);
-
-            String openId = (String) data.get("openid");
-
-
-            /**
-             * 新用户存储用户资料
-             */
-            String access_token = (String) data.get("access_token");
-            String userDataUrl = "https://api.weixin.qq.com/sns/userinfo?access_token=" + access_token + "&openid=" + openId;
-            JSONObject userData = WeixinUtil.loadJSON(userDataUrl);
-            String weixinInfo = userData.toString();
-            // System.out.println("userDate : " + userData);
-
-
-            System.out.println("loginUserInfo:" + weixinInfo);
-            JSONObject userJson = new JSONObject(weixinInfo);
-            System.out.println("userJson" + userJson);
-
-            String headimgurl = userJson.getString("headimgurl");
-            String sex = userJson.getInt("sex") != 0 ? "男" : "女";
-
-            Subject subject = SecurityUtils.getSubject();
+    public Map<String, String> getSignature(HttpServletRequest request) {
 
-            WeiXinCodeToken weiXinCodeToken = new WeiXinCodeToken(code, openId, userJson.getString("nickname"), sex, headimgurl);
-            try {
-                subject.login(weiXinCodeToken);
-            } catch (AuthenticationException e) {
-                e.printStackTrace();
-                logger.error(e);
-            }
-            UserInfo user = (UserInfo) subject.getPrincipal();
-            identityService.setAuthenticatedUserId(user.getId().toString());
-            HttpSession session = request.getSession();
-            CookieUtil.addCookie(response, "JSESSIONID", session.getId(), 3 * 24 * 60 * 60);
+        String shareUrl = request.getParameter("shareUrl");
+        return weiXinService.getSignature(shareUrl);
 
-        } catch (Exception e) {
-            e.printStackTrace();
-            return new ModelAndView("redirect:https://open.weixin.qq.com/connect/oauth2/authorize?appid=" + APP_ID + "&redirect_uri="
-                    + "http://xjw.izouma.com/wx/Login" + "&response_type=code&scope=snsapi_userinfo&state=STATE#wechat_redirect");
-        }
-        return mav;
     }
 
-
     @RequestMapping(value = "/checkSubscribe", method = RequestMethod.GET)
     @ResponseBody
     public Result checkSubscribe(@RequestParam("userId") String userId) {
@@ -214,6 +101,4 @@ public class WeiXinController {
         }
         return new Result(false, null);
     }
-
-
 }

+ 2 - 1
src/main/resources/properties/outsidews.properties

@@ -1,3 +1,4 @@
+projectname=xinmuAdmin
 weixinapi=https://api.weixin.qq.com/sns/oauth2/
 weixinappid=wx0c2b9407cf94dc89
 weixinsecret=84fc992b85ba8070b324cc7b08252b72
@@ -9,4 +10,4 @@ aliImageSever=http://oss.izouma.com
 rongyunappkey=pwe86ga5ee376
 rongyunappsecret=ARj0hyU5Cp
 jwtsecret=3MgWy/pJjxHCQW2pHlQbkjomTUPRo9WhsPFjUPYZZlo=
-redirecturi=http://aosmith.tunnel.2bdata.com/wx/Login
+host=http://1eaed69e.ngrok.io

+ 6 - 4
src/main/resources/spring/beans-shiro.xml

@@ -23,7 +23,7 @@
                 <ref bean="phoneCodeRealm"/>
                 <ref bean="userPasswordRealm"/>
                 <ref bean="appTokenRealm"/>
-                <ref bean="weiXinCodeRealm"/>
+                <ref bean="wechatRealm"/>
             </list>
         </property>
         <!--<property name="subjectFactory" ref="agileSubjectFactory"/>-->
@@ -39,7 +39,7 @@
                 <ref bean="phoneCodeRealm"/>
                 <ref bean="userPasswordRealm"/>
                 <ref bean="appTokenRealm"/>
-                <ref bean="weiXinCodeRealm"/>
+                <ref bean="wechatRealm"/>
             </list>
         </property>
     </bean>
@@ -48,15 +48,17 @@
     <bean id="phoneCodeRealm" class="com.izouma.awesomeadmin.shiro.PhoneCodeRealm">
         <property name="authenticationTokenClass" value="com.izouma.awesomeadmin.shiro.PhoneCodeToken"/>
     </bean>
+
     <bean id="userPasswordRealm" class="com.izouma.awesomeadmin.shiro.UserPasswordRealm">
         <property name="authenticationTokenClass" value="org.apache.shiro.authc.UsernamePasswordToken"/>
     </bean>
+
     <bean id="appTokenRealm" class="com.izouma.awesomeadmin.shiro.AppTokenRealm">
         <property name="authenticationTokenClass" value="com.izouma.awesomeadmin.shiro.AppToken"/>
     </bean>
 
-    <bean id="weiXinCodeRealm" class="com.izouma.awesomeadmin.shiro.WeiXinCodeRealm">
-        <property name="authenticationTokenClass" value="com.izouma.awesomeadmin.shiro.WeiXinCodeToken"/>
+    <bean id="wechatRealm" class="com.izouma.awesomeadmin.shiro.WechatRealm">
+        <property name="authenticationTokenClass" value="com.izouma.awesomeadmin.shiro.WechatToken"/>
     </bean>
 
     <bean id="agileSubjectFactory" class="com.izouma.awesomeadmin.shiro.AgileSubjectFactory"/>