Exemplo n.º 1
0
  /**
   * アクセストークンを取得します. OAuthサービスプロバイダに認証コードを送信して、 認証済みリクエストトークンを交換してアクセストークンを取得します.
   *
   * @param verifier 認証コード
   * @param requestToken 認証済みリクエストトークン
   * @param tokenSecret トークンシークレット
   */
  public void getAccessToken(String verifier, String requestToken, String tokenSecret) {
    // OAuthコンシューマを作成
    OAuthConsumer consumer = new OAuthConsumer(callbackUrl, consumerKey, consumerSecret, provider);

    // OAuthのアクセサーを作成
    accessor = new OAuthAccessor(consumer);
    accessor.requestToken = requestToken;
    accessor.tokenSecret = tokenSecret;

    try {
      // アクセスコードをパラメータで渡す
      Map<String, Object> parameters = new HashMap<String, Object>();
      parameters.put(OAuth.OAUTH_VERIFIER, verifier);

      // アクセストークンを取得する
      OAuthMessage response = client.getAccessToken(accessor, null, parameters.entrySet());
      response.requireParameters(OAuth.OAUTH_TOKEN, OAuth.OAUTH_TOKEN_SECRET);
      System.out.println(OAuth.OAUTH_TOKEN + "(AccessToken): " + accessor.accessToken);
      System.out.println(OAuth.OAUTH_TOKEN_SECRET + ": " + accessor.tokenSecret);
    } catch (IOException e) {
      e.printStackTrace();
    } catch (OAuthException e) {
      e.printStackTrace();
    } catch (URISyntaxException e) {
      e.printStackTrace();
    }
  }
  protected SecurityToken verifyMessage(OAuthMessage message) throws OAuthProblemException {
    OAuthEntry entry = getOAuthEntry(message);
    OAuthConsumer authConsumer = getConsumer(message);

    OAuthAccessor accessor = new OAuthAccessor(authConsumer);

    if (entry != null) {
      accessor.tokenSecret = entry.tokenSecret;
      accessor.accessToken = entry.token;
    }

    try {
      message.validateMessage(accessor, new SimpleOAuthValidator());
    } catch (OAuthProblemException e) {
      throw e;
    } catch (OAuthException e) {
      OAuthProblemException ope = new OAuthProblemException(OAuth.Problems.SIGNATURE_INVALID);
      ope.setParameter(OAuth.Problems.OAUTH_PROBLEM_ADVICE, e.getMessage());
      throw ope;
    } catch (IOException e) {
      OAuthProblemException ope = new OAuthProblemException(OAuth.Problems.SIGNATURE_INVALID);
      ope.setParameter(OAuth.Problems.OAUTH_PROBLEM_ADVICE, e.getMessage());
      throw ope;
    } catch (URISyntaxException e) {
      OAuthProblemException ope = new OAuthProblemException(OAuth.Problems.SIGNATURE_INVALID);
      ope.setParameter(OAuth.Problems.OAUTH_PROBLEM_ADVICE, e.getMessage());
      throw ope;
    }
    return getTokenFromVerifiedRequest(message, entry, authConsumer);
  }
Exemplo n.º 3
0
  @Override
  protected void doGet(HttpServletRequest request, HttpServletResponse response)
      throws IOException, ServletException {
    try {
      OAuthMessage requestMessage = OAuthServlet.getMessage(request, null);
      OAuthAccessor accessor = SimpleOAuthProvider.getAccessor(requestMessage);
      SimpleOAuthProvider.VALIDATOR.validateMessage(requestMessage, accessor);
      String userId = (String) accessor.getProperty("user");

      response.setContentType("text/plain");
      PrintWriter out = response.getWriter();
      out.println("Your OpenId: " + userId);
      out.close();

    } catch (Exception e) {
      e.printStackTrace();
      SimpleOAuthProvider.handleException(e, request, response, false);
    }
  }
Exemplo n.º 4
0
  /**
   * APIを実行します.
   *
   * @param url APIのURL
   * @param accessToken アクセストークン
   * @param tokenSecret トークンシークレット
   * @return boolean success
   */
  public boolean api(
      String method,
      String url,
      Collection<? extends Entry<String, String>> parameters,
      String accessToken,
      String tokenSecret) {

    // OAuthコンシューマを作成
    OAuthConsumer consumer = new OAuthConsumer(callbackUrl, consumerKey, consumerSecret, provider);

    // OAuthのアクセサーを作成
    OAuthAccessor accessor = new OAuthAccessor(consumer);
    accessor.accessToken = accessToken;
    accessor.tokenSecret = tokenSecret;

    apiResponse = null;

    try {
      OAuthMessage request = accessor.newRequestMessage(method, url, parameters);
      OAuthResponseMessage responseMessage =
          client.access(request, ParameterStyle.AUTHORIZATION_HEADER);
      int statusCode = responseMessage.getHttpResponse().getStatusCode();
      System.out.println("API: " + url);
      System.out.println("body type: " + responseMessage.getBodyType());
      System.out.println("body encoding: " + responseMessage.getBodyEncoding());
      if (statusCode == HttpResponseMessage.STATUS_OK) {
        apiResponse = responseMessage;
        return true;
      } else {
        System.out.println("API Error: " + statusCode);
      }
    } catch (OAuthException e) {
      e.printStackTrace();
    } catch (IOException e) {
      e.printStackTrace();
    } catch (URISyntaxException e) {
      e.printStackTrace();
    }

    return false;
  }
  /** Tests the case when the user has not started the authorization process (no request token). */
  public final void testCheckAuthorizationNoRequestToken() {
    // Setup.
    LoginFormHandler loginForm = mock(LoginFormHandler.class);
    OAuthClient client = mock(OAuthClient.class);
    PersistenceManager pm = mock(PersistenceManager.class);
    PersistenceManagerFactory pmf = mock(PersistenceManagerFactory.class);

    OAuthAccessor accessor =
        buildAccessor(
            CONSUMER_KEY,
            CONSUMER_SECRET,
            REQUEST_TOKEN_URL,
            AUTHORIZE_URL,
            CALLBACK_URL,
            ACCESS_TOKEN_URL);
    accessor.requestToken = REQUEST_TOKEN_STRING;
    oauthService = new OAuthServiceImpl(accessor, client, pmf, USER_RECORD_KEY);
    OAuthUser userWithRequestToken = new OAuthUser(USER_RECORD_KEY, REQUEST_TOKEN_STRING);

    // Expectations.
    when(pmf.getPersistenceManager()).thenReturn(pm);
    when(pm.getObjectById(OAuthUser.class, USER_RECORD_KEY))
        .thenReturn(null, userWithRequestToken, userWithRequestToken);

    assertFalse(oauthService.checkAuthorization(null, loginForm));

    String authUrl = userWithRequestToken.getAuthUrl();
    try {
      new URL(authUrl);
    } catch (MalformedURLException e) {
      fail("Malformed authUrl");
    }

    assertTrue(Pattern.matches(".+(oauth_token){1}.+", authUrl));
    assertTrue(Pattern.matches(".+(oauth_callback){1}.+", authUrl));
  }
Exemplo n.º 6
0
  private OAuthEntry getValidatedEntry(OAuthMessage requestMessage)
      throws IOException, ServletException, OAuthException, URISyntaxException {

    OAuthEntry entry = dataStore.getEntry(requestMessage.getToken());
    if (entry == null) throw new OAuthProblemException(OAuth.Problems.TOKEN_REJECTED);

    if (entry.type != OAuthEntry.Type.REQUEST)
      throw new OAuthProblemException(OAuth.Problems.TOKEN_USED);

    if (entry.isExpired()) throw new OAuthProblemException(OAuth.Problems.TOKEN_EXPIRED);

    // find consumer key, compare with supplied value, if present.

    if (requestMessage.getConsumerKey() == null) {
      OAuthProblemException e = new OAuthProblemException(OAuth.Problems.PARAMETER_ABSENT);
      e.setParameter(OAuth.Problems.OAUTH_PARAMETERS_ABSENT, OAuth.OAUTH_CONSUMER_KEY);
      throw e;
    }

    String consumerKey = entry.consumerKey;
    if (!consumerKey.equals(requestMessage.getConsumerKey()))
      throw new OAuthProblemException(OAuth.Problems.CONSUMER_KEY_REFUSED);

    OAuthConsumer consumer = dataStore.getConsumer(consumerKey);

    if (consumer == null) throw new OAuthProblemException(OAuth.Problems.CONSUMER_KEY_UNKNOWN);

    OAuthAccessor accessor = new OAuthAccessor(consumer);

    accessor.requestToken = entry.token;
    accessor.tokenSecret = entry.tokenSecret;

    VALIDATOR.validateMessage(requestMessage, accessor);

    return entry;
  }
  private HttpResponse handleResourceUrl(HttpRequest request) throws Exception {
    MessageInfo info = parseMessage(request);
    String consumerId = info.message.getParameter("oauth_consumer_key");
    OAuthConsumer consumer;
    if (CONSUMER_KEY.equals(consumerId)) {
      consumer = oauthConsumer;
    } else if ("signedfetch".equals(consumerId)) {
      consumer = signedFetchConsumer;
    } else if ("container.com".equals(consumerId)) {
      consumer = signedFetchConsumer;
    } else {
      return makeOAuthProblemReport(
          OAuthConstants.PROBLEM_PARAMETER_MISSING,
          "oauth_consumer_key not found",
          HttpResponse.SC_BAD_REQUEST);
    }
    OAuthAccessor accessor = new OAuthAccessor(consumer);
    String responseBody = null;
    if (throttled) {
      return makeOAuthProblemReport(
          OAuthConstants.PROBLEM_CONSUMER_KEY_REFUSED, "exceeded quota", HttpResponse.SC_FORBIDDEN);
    }
    if (unauthorized) {
      return makeOAuthProblemReport(
          OAuthConstants.PROBLEM_PERMISSION_DENIED,
          "user refused access",
          HttpResponse.SC_UNAUTHORIZED);
    }
    if (consumer == oauthConsumer) {
      // for OAuth, check the access token.  We skip this for signed fetch
      String accessToken = info.message.getParameter("oauth_token");
      TokenState state = tokenState.get(accessToken);
      if (state == null) {
        return makeOAuthProblemReport(
            OAuthConstants.PROBLEM_TOKEN_REJECTED,
            "Access token unknown",
            HttpResponse.SC_UNAUTHORIZED);
      }
      // Check the signature
      accessor.accessToken = accessToken;
      accessor.tokenSecret = state.getSecret();
      validateMessage(accessor, info, false);

      if (state.getState() != State.APPROVED) {
        return makeOAuthProblemReport(
            OAuthConstants.PROBLEM_TOKEN_REVOKED,
            "User revoked permissions",
            HttpResponse.SC_UNAUTHORIZED);
      }
      if (sessionExtension) {
        long expiration = state.issued + TOKEN_EXPIRATION_SECONDS * 1000;
        if (expiration < clock.currentTimeMillis()) {
          return makeOAuthProblemReport(
              OAuthConstants.PROBLEM_ACCESS_TOKEN_EXPIRED,
              "token needs to be refreshed",
              HttpResponse.SC_UNAUTHORIZED);
        }
      }
      responseBody = "User data is " + state.getUserData();
    } else {
      // Check the signature
      validateMessage(accessor, info, false);

      // For signed fetch, just echo back the query parameters in the body
      responseBody = request.getUri().getQuery();
    }

    // Send back a response
    HttpResponseBuilder resp =
        new HttpResponseBuilder()
            .setHttpStatusCode(HttpResponse.SC_OK)
            .setResponseString(responseBody);
    if (info.aznHeader != null) {
      resp.setHeader(AUTHZ_ECHO_HEADER, info.aznHeader);
    }
    if (info.body != null) {
      resp.setHeader(BODY_ECHO_HEADER, info.body);
    }
    if (info.rawBody != null) {
      resp.setHeader(RAW_BODY_ECHO_HEADER, new String(Base64.encodeBase64(info.rawBody)));
    }
    return resp.create();
  }
  private HttpResponse handleAccessTokenUrl(HttpRequest request) throws Exception {
    MessageInfo info = parseMessage(request);
    String requestToken = info.message.getParameter("oauth_token");
    TokenState state = tokenState.get(requestToken);
    if (throttled) {
      return makeOAuthProblemReport(
          OAuthConstants.PROBLEM_CONSUMER_KEY_REFUSED, "exceeded quota", HttpResponse.SC_FORBIDDEN);
    } else if (unauthorized) {
      return makeOAuthProblemReport(
          OAuthConstants.PROBLEM_PERMISSION_DENIED,
          "user refused access",
          HttpResponse.SC_UNAUTHORIZED);
    } else if (state == null) {
      return makeOAuthProblemReport(
          OAuthConstants.PROBLEM_TOKEN_REJECTED,
          "Unknown request token",
          HttpResponse.SC_UNAUTHORIZED);
    }
    if (rejectExtraParams) {
      String extra = hasExtraParams(info.message);
      if (extra != null) {
        return makeOAuthProblemReport(
            OAuthConstants.PROBLEM_PARAMETER_REJECTED, extra, HttpResponse.SC_BAD_REQUEST);
      }
    }

    OAuthAccessor accessor = new OAuthAccessor(oauthConsumer);
    accessor.requestToken = requestToken;
    accessor.tokenSecret = state.tokenSecret;
    validateMessage(accessor, info, true);

    if (state.getState() == State.APPROVED_UNCLAIMED) {
      String sentVerifier = info.message.getParameter("oauth_verifier");
      if (state.verifier != null && !state.verifier.equals(sentVerifier)) {
        return makeOAuthProblemReport(
            OAuthConstants.PROBLEM_BAD_VERIFIER,
            "wrong oauth verifier",
            HttpResponse.SC_UNAUTHORIZED);
      }
      state.claimToken();
    } else if (state.getState() == State.APPROVED) {
      // Verify can refresh
      String sentHandle = info.message.getParameter("oauth_session_handle");
      if (sentHandle == null) {
        return makeOAuthProblemReport(
            OAuthConstants.PROBLEM_PARAMETER_ABSENT,
            "no oauth_session_handle",
            HttpResponse.SC_BAD_REQUEST);
      }
      if (!sentHandle.equals(state.sessionHandle)) {
        return makeOAuthProblemReport(
            OAuthConstants.PROBLEM_TOKEN_INVALID, "token not valid", HttpResponse.SC_UNAUTHORIZED);
      }
      state.renewToken();
    } else if (state.getState() == State.REVOKED) {
      return makeOAuthProblemReport(
          OAuthConstants.PROBLEM_TOKEN_REVOKED,
          "Revoked access token can't be renewed",
          HttpResponse.SC_UNAUTHORIZED);
    } else {
      throw new Exception("Token in weird state " + state.getState());
    }

    String accessToken = Crypto.getRandomString(16);
    String accessTokenSecret = Crypto.getRandomString(16);
    state.tokenSecret = accessTokenSecret;
    tokenState.put(accessToken, state);
    tokenState.remove(requestToken);
    List<OAuth.Parameter> params =
        OAuth.newList(
            "oauth_token", accessToken,
            "oauth_token_secret", accessTokenSecret);
    if (sessionExtension) {
      params.add(new OAuth.Parameter("oauth_session_handle", state.sessionHandle));
      if (reportExpirationTimes) {
        params.add(new OAuth.Parameter("oauth_expires_in", "" + TOKEN_EXPIRATION_SECONDS));
      }
    }
    if (returnAccessTokenData) {
      params.add(new OAuth.Parameter("userid", "userid value"));
      params.add(new OAuth.Parameter("xoauth_stuff", "xoauth_stuff value"));
      params.add(new OAuth.Parameter("oauth_stuff", "oauth_stuff value"));
    }
    return new HttpResponse(OAuth.formEncode(params));
  }