コード例 #1
0
ファイル: LoginController.java プロジェクト: jsjwk/77chi
  /** 用户选择登陆渠道 */
  @RequestMapping("/preLogin.do")
  public void preLogin(HttpServletRequest request, HttpServletResponse response)
      throws ServletException, IOException, ApiException {
    String regMethod = request.getParameter("regMethod");
    if ("weibo".equalsIgnoreCase(regMethod)) { // 新浪微博登陆
      weibo4j.Oauth oauth = new weibo4j.Oauth();
      try {
        String openUrl = oauth.authorize("code", ConstatVar.WEIBO_APPKEY, ConstatVar.WEIBO_SECRET);
        response.sendRedirect(openUrl);
      } catch (weibo4j.model.WeiboException e) {
        e.printStackTrace();
        // TODO 跳转到错误页,提示用户重新选择注册渠道
      }
    } else if ("qq".equalsIgnoreCase(regMethod)) { // QQ登陆
      com.qq.connect.oauth.Oauth oauth = new com.qq.connect.oauth.Oauth();
      try {
        String openUrl = oauth.getAuthorizeURL(request);
        response.sendRedirect(openUrl);
      } catch (com.qq.connect.QQConnectException e) {
        e.printStackTrace();
        // TODO 跳转到错误页,提示用户重新选择注册渠道
      }
    } else if ("taobao".equalsIgnoreCase(regMethod)) { // Taobao登陆

      // TODO
    } else {
      response.sendRedirect("/loginPage.do");
    }
    return;
  }
コード例 #2
0
  /**
   * 新浪登录返回接受器 接受从新浪登录后返回的信息 对enService进行解密,解密后的参数名为service,并进行URLEnCoder转码
   *
   * @param request
   * @param response
   * @return
   */
  @RequestMapping("ologin")
  public String execute(
      ModelMap model, final HttpServletRequest request, final HttpServletResponse response) {
    Map paramMap = getRequestMap(request);
    String v = paramMap.get("uv") != null ? paramMap.get("uv").toString() : null;
    if (!authorized(request, response, paramMap)) { // 非法第三方登录请求
      // model.addAttribute("redirUrl", "/login");
      // model.addAttribute("retMessage", "非法操作,系统将在3 秒后返回...");
      // return "result";
      return getRedirectLoginUrl(v);
    }

    String code = (String) paramMap.get("code");
    // String state = (String)paramMap.get("state");
    // 删除对应参数
    if (null == code || "".equals(code)) {
      return getRedirectLoginUrl(v);
    } else { // 删除对应参数
      paramMap.remove("code");
      paramMap.remove("state");
    }

    String enKey = request.getParameter(OUserConstant.ENCRYPT_SERVICE_TAG);
    if (!StringUtil.isEmpty(enKey)) {
      paramMap.remove(OUserConstant.ENCRYPT_SERVICE_TAG);
    }
    Oauth oauth = new Oauth();
    // 获取accCode
    AccessToken accToken;
    try {
      accToken = oauth.getAccessTokenByCode(code);
      if (accToken == null) {
        throw new WeiboException("code验证失败: " + code);
      }
      String paramStr = urlTransService.getUrl(enKey);
      Map<String, Object> oParaMap = new HashMap<String, Object>();
      oParaMap.put("token", accToken);
      return createdBindUrl(
          accToken.getUid(), OUserConstant.SINA_TYPE, paramStr, request, response, oParaMap);
    } catch (WeiboException e) {
      e.printStackTrace();
    }
    return getRedirectLoginUrl(v);
  }
コード例 #3
0
  // 授权,生成access_token
  // 使用情形:①程序初始化;②每隔一天左右重新授权access_token
  public static void generate() {
    initAccountInfo();
    accessToken.clear();

    logger.info("用户授权中...");
    try {
      // https://api.weibo.com/oauth2/authorize?client_id=750123511&redirect_uri=https://api.weibo.com/oauth2/default.html&response_type=code
      String url = "https://api.weibo.com/oauth2/authorize";
      String redirectUri = "https://api.weibo.com/oauth2/default.html";

      for (int i = 0; i < accountInfo.size(); i++) {
        // 获取应用的信息
        clientId = WeiboConfig.getValue("client_ID");
        clientSecret = WeiboConfig.getValue("client_SERCRET");

        // 构造授权的url参数
        PostMethod postMethod = new PostMethod(url);
        postMethod.addParameter("client_id", clientId);
        postMethod.addParameter("redirect_uri", redirectUri);
        postMethod.addParameter("userId", accountInfo.get(i).getUserId());
        postMethod.addParameter("passwd", accountInfo.get(i).getPasswd());
        postMethod.addParameter("isLoginSina", "0");
        postMethod.addParameter("action", "submit");
        postMethod.addParameter("response_type", "code");
        HttpMethodParams param = postMethod.getParams();
        param.setContentCharset("UTF-8");

        // 伪造头部域信息
        List<Header> headers = new ArrayList<Header>();
        headers.add(
            new Header(
                "Referer",
                "https://api.weibo.com/oauth2/authorize?client_id="
                    + clientId
                    + "&redirect_uri="
                    + redirectUri
                    + "&from=sina&response_type=code"));
        headers.add(new Header("Host", "api.weibo.com"));
        headers.add(
            new Header(
                "User-Agent", "Mozilla/5.0 (Windows NT 6.1; rv:11.0) Gecko/20100101 Firefox/11.0"));

        // 发送HTTP请求
        HttpClient client = new HttpClient();
        client.getHostConfiguration().getParams().setParameter("http.default-headers", headers);
        client.executeMethod(postMethod);

        // 获取授权响应
        int status = postMethod.getStatusCode();
        if (status == 302) {
          Header location = postMethod.getResponseHeader("location");
          if (location != null) {
            String retUrl = location.getValue();
            int begin = retUrl.indexOf("code=");
            int end = retUrl.length();
            String code = retUrl.substring(begin + 5, end);
            if (code != null) {
              Oauth oauth = new Oauth();
              String token = oauth.getAccessTokenByCode(code).getAccessToken();
              accessToken.add(token);
              logger.info("第" + (i + 1) + "个access_token:" + token);
            }
          }
        } else {
          logger.error("第" + (i + 1) + "个用户授权失败了!");
        }
      }
    } catch (Exception e) {
      e.printStackTrace();
      logger.error("授权发生异常!");
    }
  }
コード例 #4
0
ファイル: ProfileCtl.java プロジェクト: hhFate/FateCms
  @RequestMapping("/bindWeibo")
  public void weiboLogin(HttpServletRequest request, HttpServletResponse response, String code) {
    try {
      ThirdPartyAccess xinlang = thirdPartyAccessService.findByType(ThirdPartyAccess.TYPE_XINLANG);
      GlobalSetting globalSetting = (GlobalSetting) request.getSession().getAttribute("setting");
      weibo4j.Oauth oauth = new weibo4j.Oauth();
      weibo4j.http.AccessToken accessTokenObj =
          oauth.getAccessTokenByCode(
              code,
              xinlang.getAccessKey(),
              xinlang.getAccessSecret(),
              "http://" + globalSetting.getAppUrl() + "/profile/bindWeibo");
      String accessToken = null, uid = null, tokenExpireIn = null;
      if ("".equals(accessTokenObj.getAccessToken())) {
        // 我们的网站被CSRF攻击了或者用户取消了授权
        // 做一些数据统计工作
        LOG.info("没有获取到响应参数");
      } else {
        accessToken = accessTokenObj.getAccessToken();
        tokenExpireIn = accessTokenObj.getExpireIn();

        request.getSession().setAttribute("token_expirein", String.valueOf(tokenExpireIn));

        // 利用获取到的accessToken 去获取当前用的uid -------- start
        Account am = new Account(accessToken);
        JSONObject uidObj = am.getUid();
        uid = uidObj.getString("uid");
        request.getSession().setAttribute("openId", uid);
        request.getSession().setAttribute("loginType", UserSession.TYPE_XINLANG);
        // 利用获取到的accessToken 去获取当前用户的openid --------- end
        // 为空代表首次登录,此处获取的信息尚未完全
        ThirdPartyAccount tpa = tpaService.findByOpenId(uid);
        if (tpa == null) {
          // 获取新浪微博用户的信息
          Users um = new Users(accessToken);
          weibo4j.model.User wUser = um.showUserById(uid);
          tpa = new ThirdPartyAccount();
          tpa.setOpenId(uid);
          tpa.setAccountType(UserSession.TYPE_XINLANG);
          tpa.setAccessToken(accessToken);

          tpa.setHeadIconHD(wUser.getAvatarHD());
          tpa.setHeadIconBig(wUser.getAvatarLarge());
          tpa.setHeadIconMid(wUser.getProfileImageUrl());
          tpa.setHeadIconSmall(wUser.getProfileImageUrl());
          tpa = tpaService.update(tpa);
        }
        UserSession userSession =
            (UserSession) request.getSession(false).getAttribute("userSession");
        tpa.setUser(userSession.getUser());
        tpaService.update(tpa);
        response.sendRedirect("thirdParty");
      }
    } catch (IOException e) {
      LOG.error("重定向回本站失败", e);
    } catch (WeiboException e) {
      LOG.error("连接到新浪失败", e);
    } catch (JSONException e) {
      LOG.error("JSON解析错误", e);
    }
  }