コード例 #1
0
ファイル: OAuthService.java プロジェクト: AirGrowz/repo
  /**
   * アクセストークンを取得します. 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();
    }
  }
コード例 #2
0
  /** 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));
  }
コード例 #3
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;
  }
コード例 #4
0
  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));
  }