Search in sources :

Example 6 with UserInfo

use of com.guhanjie.weixin.model.UserInfo in project weixin-boot by guhanjie.

the class WeixinController method oauth2.

@RequestMapping(value = "oauth2", method = RequestMethod.GET)
public void oauth2(HttpServletRequest req, HttpServletResponse resp) throws IOException {
    LOGGER.debug("entering oauth2 return url for weixin...");
    final HttpSession session = req.getSession();
    final HttpServletResponse response = resp;
    String originState = (String) session.getAttribute(AppConstants.SESSION_KEY_OAUTH_STATE);
    // 根据state校验是否是刚刚发出的授权申请,防止CSRF跨站伪造攻击
    String state = req.getParameter("state");
    if (!state.equals(originState)) {
        LOGGER.warn("The state[{}] does not match original value[{}]. You may be a victim of CSRF.", state, originState);
        resp.getWriter().write("Authentication failed. It may be CSRF attack.");
        resp.getWriter().flush();
        return;
    }
    String code = req.getParameter("code");
    String url = WeixinConstants.OAUTH2_ACCESS_TOKEN;
    url = url.replaceAll("APPID", weixinContants.APPID);
    url = url.replaceAll("SECRET", weixinContants.APPSECRET);
    url = url.replaceAll("CODE", code);
    WeixinHttpUtil.sendGet(url, new WeixinHttpCallback() {

        @Override
        public void process(String json) {
            AccessToken at = JSONObject.parseObject(json, AccessToken.class);
            if (at != null && at.getAccess_token() != null && at.getOpenid() != null) {
                // 拿到accesstoken,绑定到对应的人
                final String token = at.getAccess_token();
                final String openid = at.getOpenid();
                LOGGER.info("User authentication successful, access token:[{}], openid:[{}].", token, openid);
                session.setAttribute(AppConstants.SESSION_KEY_ACCESS_TOKEN, token);
                session.setAttribute(AppConstants.SESSION_KEY_OPEN_ID, openid);
                User user = userService.getUserByOpenId(openid);
                if (user == null) {
                    user = new User();
                    user.setOpenId(openid);
                    UserInfo userInfo = UserKit.getUserInfoByOauth2(openid, token);
                    user.setUnionid(userInfo.getUnionid());
                    user.setName(userInfo.getNickname());
                    user.setNickname(userInfo.getNickname());
                    user.setSex(userInfo.getSex());
                    user.setLanguage(userInfo.getLanguage());
                    user.setCountry(userInfo.getCountry());
                    user.setProvince(userInfo.getProvince());
                    user.setCity(userInfo.getCity());
                    if (StringUtils.isNumeric(userInfo.getSubscribe_time())) {
                        user.setSubscribeTime(new Date(Long.parseLong(userInfo.getSubscribe_time())));
                    }
                    userService.addUser(user);
                }
                session.setAttribute(AppConstants.SESSION_KEY_USER, user);
                try {
                    String returnURL = (String) session.getAttribute(AppConstants.SESSION_KEY_RETURN_URL);
                    if (StringUtils.isBlank(returnURL)) {
                        response.getWriter().write("Welcome, user authentication successful.");
                        response.getWriter().flush();
                    } else {
                        // 跳转回原来地址
                        LOGGER.debug("redirecting back to last request[{}] for user.", returnURL);
                        response.sendRedirect(returnURL);
                    }
                } catch (Exception e) {
                    LOGGER.error("error in user authentication for weixin oauth2.0.", e);
                }
            } else {
                LOGGER.error("User authentication failed in weixin oauth2.0, error response:[{}].", json);
            }
        }
    });
}
Also used : User(com.guhanjie.model.User) HttpSession(javax.servlet.http.HttpSession) AccessToken(com.guhanjie.weixin.model.AccessToken) HttpServletResponse(javax.servlet.http.HttpServletResponse) UserInfo(com.guhanjie.weixin.model.UserInfo) Date(java.util.Date) IOException(java.io.IOException) WeixinHttpCallback(com.guhanjie.weixin.WeixinHttpUtil.WeixinHttpCallback) RequestMapping(org.springframework.web.bind.annotation.RequestMapping)

Aggregations

UserInfo (com.guhanjie.weixin.model.UserInfo)6 WeixinHttpCallback (com.guhanjie.weixin.WeixinHttpUtil.WeixinHttpCallback)3 User (com.guhanjie.model.User)2 IOException (java.io.IOException)2 Date (java.util.Date)2 Test (org.junit.Test)2 UserService (com.guhanjie.service.UserService)1 AccessToken (com.guhanjie.weixin.model.AccessToken)1 HashMap (java.util.HashMap)1 HttpServletResponse (javax.servlet.http.HttpServletResponse)1 HttpSession (javax.servlet.http.HttpSession)1 RequestMapping (org.springframework.web.bind.annotation.RequestMapping)1