com.github.scribejava.core.model.OAuthRequest Java Examples

The following examples show how to use com.github.scribejava.core.model.OAuthRequest. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: OAuth2CookieFilter.java    From datashare with GNU Affero General Public License v3.0 6 votes vote down vote up
protected Payload callback(Context context) throws IOException, ExecutionException, InterruptedException {
    if (context.get(REQUEST_CODE_KEY) == null || context.get(REQUEST_STATE_KEY) == null || !"GET".equals(context.method()) ||
            sessionIdStore.getLogin(context.get(REQUEST_STATE_KEY)) == null) {
        return Payload.badRequest();
    }
    OAuth20Service service = new ServiceBuilder(oauthClientId).apiSecret(oauthClientSecret).
            callback(getCallbackUrl(context)).
            build(defaultOauthApi);
    OAuth2AccessToken accessToken = service.getAccessToken(context.get(REQUEST_CODE_KEY));

    final OAuthRequest request = new OAuthRequest(Verb.GET, oauthApiUrl);
    service.signRequest(accessToken, request);
    final Response oauthApiResponse = service.execute(request);

    HashMapUser user = fromJson(oauthApiResponse.getBody());
    redisUsers().createUser(user);
    return Payload.seeOther(this.validRedirectUrl(this.readRedirectUrlInCookie(context))).withCookie(this.authCookie(this.buildCookie(user, "/")));
}
 
Example #2
Source File: OAuthManagerProviders.java    From react-native-oauth with MIT License 6 votes vote down vote up
static public OAuthRequest getRequestForProvider(
  final String providerName,
  final Verb httpVerb,
  final OAuth1AccessToken oa1token,
  final URL url,
  final HashMap<String,Object> cfg,
  @Nullable final ReadableMap params
) {
  final OAuth10aService service =
        OAuthManagerProviders.getApiFor10aProvider(providerName, cfg, null, null);

  String token = oa1token.getToken();
  OAuthConfig config = service.getConfig();
  OAuthRequest request = new OAuthRequest(httpVerb, url.toString(), config);

  request = OAuthManagerProviders.addParametersToRequest(request, token, params);
  // Nothing special for Twitter
  return request;
}
 
Example #3
Source File: OAuthManagerProviders.java    From react-native-oauth with MIT License 6 votes vote down vote up
static public OAuthRequest getRequestForProvider(
  final String providerName,
  final Verb httpVerb,
  final OAuth2AccessToken oa2token,
  final URL url,
  final HashMap<String,Object> cfg,
  @Nullable final ReadableMap params
) {
  final OAuth20Service service =
      OAuthManagerProviders.getApiFor20Provider(providerName, cfg, null, null);

  OAuthConfig config = service.getConfig();
  OAuthRequest request = new OAuthRequest(httpVerb, url.toString(), config);
  String token = oa2token.getAccessToken();

  request = OAuthManagerProviders.addParametersToRequest(request, token, params);

  //
  Log.d(TAG, "Making request for " + providerName + " to add token " + token);
  // Need a way to standardize this, but for now
  if (providerName.equalsIgnoreCase("slack")) {
    request.addParameter("token", token);
  }

  return request;
}
 
Example #4
Source File: OAuthManagerProviders.java    From react-native-oauth with MIT License 6 votes vote down vote up
static private OAuthRequest addParametersToRequest(
  OAuthRequest request,
  final String access_token,
  @Nullable final ReadableMap params
) {
  if (params != null && params.hasKey("params")) {
    ReadableMapKeySetIterator iterator = params.keySetIterator();
    while (iterator.hasNextKey()) {
      String key = iterator.nextKey();
      ReadableType readableType = params.getType(key);
      switch(readableType) {
        case String:
          String val = params.getString(key);
          // String escapedVal = Uri.encode(val);
          if (val.equals("access_token")) {
            val = access_token;
          }
          request.addParameter(key, val);
          break;
        default:
          throw new IllegalArgumentException("Could not read object with key: " + key);
      }
    }
  }
  return request;
}
 
Example #5
Source File: JamAuthConfig.java    From jam-collaboration-sample with Apache License 2.0 6 votes vote down vote up
public String getSingleUseToken() {
    OAuth10aService service = JamAuthConfig.instance().getOAuth10aService();
    final OAuthRequest request = new OAuthRequest(Verb.POST,
            JamAuthConfig.instance().getServerUrl() + "/v1/single_use_tokens",
            service);
    service.signRequest(JamAuthConfig.instance().getOAuth10aAccessToken(), request);

    final Response response = request.send();
    String body = response.getBody();

    Matcher matcher = SINGLE_USE_TOKEN_PATTERN.matcher(body);
    if (matcher.find()) {
        return matcher.group(0);
    }
    return null;
}
 
Example #6
Source File: GoogleController.java    From tutorials with MIT License 6 votes vote down vote up
@GetMapping(value = "/auth/google")
public String google(@RequestParam String code, HttpServletResponse servletResponse){

    try {
        OAuth2AccessToken token = service.getService().getAccessToken(code);

        OAuthRequest request = new OAuthRequest(Verb.GET, "https://www.googleapis.com/oauth2/v1/userinfo?alt=json");
        service.getService().signRequest(token, request);
        Response response = service.getService().execute(request);
        return response.getBody();

    }catch (Exception e){
        servletResponse.setStatus(HttpServletResponse.SC_BAD_REQUEST);
    }

    return null;
}
 
Example #7
Source File: GitHubApiHelper.java    From gdx-texture-packer-gui with Apache License 2.0 5 votes vote down vote up
/** Beware: there is no timeout for browser GitHub authorization and in case user closed/left
 * authorization page without completing whole process, there will be no feedback in {@link CreateIssueResultHandler}. */
public void createIssue(final String title, final String body, final CreateIssueResultHandler resultHandler) {
    if (!checkApiKey()) {
        resultHandler.onError(new IllegalStateException("GitHub API key is invalid."));
        return;
    }

    authCallbackHandler.setListener(new AuthCallbackHandler.Listener() {
        @Override
        public void onAuthCodeReceived(String authCode) {
            authCallbackHandler.setListener(null);
            try {
                String contentJson = json.toJson(new CreateIssueBody(title, body));

                OAuth2AccessToken accessToken = apiService.getAccessToken(authCode);

                OAuthRequest request = new OAuthRequest(Verb.POST, "https://api.github.com/repos/"+GITHUB_OWNER+"/"+GITHUB_REPO+"/issues");
                request.setPayload(contentJson);
                apiService.signRequest(accessToken, request);
                Response response = apiService.execute(request);

                if (response.getCode() != 201) {
                    resultHandler.onError(new IllegalStateException("GitHub returned bad code: " +
                            response.getCode() + "\n" +
                            response.getMessage() + "\n" +
                            response.getBody()));
                } else {
                    JsonValue jsonRoot = new JsonReader().parse(response.getBody());
                    String issueUrl = jsonRoot.getString("html_url");
                    resultHandler.onSuccess(issueUrl);
                }
            } catch (IOException | InterruptedException | ExecutionException | OAuthException e) {
                e.printStackTrace();
                resultHandler.onError(e);
            }
        }
    });
    Sys.openURL(apiService.getAuthorizationUrl());
}
 
Example #8
Source File: DefaultOAuth2ServiceImpl.java    From Orienteer with Apache License 2.0 5 votes vote down vote up
private JsonNode requestProtectedData(OAuth20Service service, OAuth2AccessToken token, String url) {
    OAuthRequest request = new OAuthRequest(Verb.GET, url);
    service.signRequest(token, request);
    try {
        Response response = service.execute(request);
        return new ObjectMapper().readTree(response.getBody());
    } catch (InterruptedException | ExecutionException | IOException e) {
        throw new IllegalStateException("Error during request protected data", e);
    }
}
 
Example #9
Source File: AccountService.java    From runelite with BSD 2-Clause "Simplified" License 4 votes vote down vote up
@GetMapping("/callback")
public Object callback(
	HttpServletRequest request,
	HttpServletResponse response,
	@RequestParam(required = false) String error,
	@RequestParam String code,
	@RequestParam("state") String stateStr
) throws InterruptedException, ExecutionException, IOException
{
	if (error != null)
	{
		logger.info("Error in oauth callback: {}", error);
		return null;
	}

	State state = gson.fromJson(stateStr, State.class);

	logger.info("Got authorization code {} for uuid {}", code, state.getUuid());

	OAuth20Service service = new ServiceBuilder()
		.apiKey(oauthClientId)
		.apiSecret(oauthClientSecret)
		.scope(SCOPE)
		.callback(oauthCallback)
		.state(gson.toJson(state))
		.build(GoogleApi20.instance());

	OAuth2AccessToken accessToken = service.getAccessToken(code);

	// Access user info
	OAuthRequest orequest = new OAuthRequest(Verb.GET, USERINFO);
	service.signRequest(accessToken, orequest);

	Response oresponse = service.execute(orequest);

	if (oresponse.getCode() / 100 != 2)
	{
		// Could be a forged result
		return null;
	}

	UserInfo userInfo = gson.fromJson(oresponse.getBody(), UserInfo.class);

	logger.info("Got user info: {}", userInfo);

	try (Connection con = sql2o.open())
	{
		con.createQuery("insert ignore into users (username) values (:username)")
			.addParameter("username", userInfo.getEmail())
			.executeUpdate();

		UserEntry user = con.createQuery("select id from users where username = :username")
			.addParameter("username", userInfo.getEmail())
			.executeAndFetchFirst(UserEntry.class);

		if (user == null)
		{
			logger.warn("Unable to find newly created user session");
			return null; // that's weird
		}

		// insert session
		con.createQuery("insert ignore into sessions (user, uuid) values (:user, :uuid)")
			.addParameter("user", user.getId())
			.addParameter("uuid", state.getUuid().toString())
			.executeUpdate();

		logger.info("Created session for user {}", userInfo.getEmail());
	}

	response.sendRedirect(RL_REDIR);

	notifySession(state.getUuid(), userInfo.getEmail());

	return "";
}
 
Example #10
Source File: OAuthManagerModule.java    From react-native-oauth with MIT License 4 votes vote down vote up
private OAuthRequest oauthRequestWithParams(
  final String providerName,
  final HashMap<String,Object> cfg,
  final String authVersion,
  final Verb httpVerb,
  final URL url,
  @Nullable final ReadableMap params
  ) throws Exception {
  OAuthRequest request;
  // OAuthConfig config;

  if (authVersion.equals("1.0")) {  
    // final OAuth10aService service = 
        // OAuthManagerProviders.getApiFor10aProvider(providerName, cfg, null, null);
    OAuth1AccessToken oa1token = _credentialsStore.get(providerName, OAuth1AccessToken.class);
    request = OAuthManagerProviders.getRequestForProvider(
      providerName, 
      httpVerb,
      oa1token, 
      url,
      cfg,
      params);
    
    // config = service.getConfig();
    // request = new OAuthRequest(httpVerb, url.toString(), config);
  } else if (authVersion.equals("2.0")) {
    // final OAuth20Service service =
      // OAuthManagerProviders.getApiFor20Provider(providerName, cfg, null, null);
    // oa2token = _credentialsStore.get(providerName, OAuth2AccessToken.class);

    OAuth2AccessToken oa2token = _credentialsStore.get(providerName, OAuth2AccessToken.class);
    request = OAuthManagerProviders.getRequestForProvider(
      providerName, 
      httpVerb,
      oa2token, 
      url,
      cfg,
      params);
    
    // config = service.getConfig();
    // request = new OAuthRequest(httpVerb, url.toString(), config);
  } else {
    Log.e(TAG, "Error in making request method");
    throw new Exception("Provider not handled yet");
  }

  return request;
}
 
Example #11
Source File: Network.java    From mirror with MIT License 4 votes vote down vote up
/**
 * Like {@link #get(String)}, but for OAuth authenticated requests.
 */
public static String get(Activity activity, String urlString, DefaultApi20 api,
                         OAuthDataProvider data) {
  if (urlString == null) {
    return null;
  }
  Log.d(TAG, "Requesting OAuth URL: " + urlString);

  try {
    OAuth20Service service = new ServiceBuilder(data.getClientId())
        .apiSecret(data.getClientSecret())
        .build(api);

    // Look for any saved access token. If there is none, refresh using the initial refresh token.
    // If there is one but it is expired, refresh using the saved refresh token.
    AccessToken accessToken = loadAccessToken(activity, data);
    if ((accessToken == null) || accessToken.shouldRefreshNow()) {
      Log.w(TAG, "Refreshing access token.");

      // Figure out which refresh token to use.
      String refreshToken;
      if (accessToken == null) {
        Log.d(TAG, "Using initial refresh token.");
        refreshToken = data.getRefreshToken();
      } else {
        Log.d(TAG, "Using saved refresh token.");
        refreshToken = accessToken.getRefreshToken();
      }

      // Get the new access token.
      long refreshTime = System.currentTimeMillis() / 1000;
      accessToken = new AccessToken(service.refreshAccessToken(refreshToken), refreshTime);

      // Save it for next time.
      saveAccessToken(activity, data, accessToken, refreshTime);
    }

    // Make the authenticated request.
    OAuthRequest request = new OAuthRequest(Verb.GET, urlString);
    service.signRequest(accessToken, request);
    Response response = service.execute(request);

    return response.getBody();
  } catch (IOException | InterruptedException | ExecutionException e) {
    Log.e(TAG, "OAuth request failed.", e);
    return null;
  }
}
 
Example #12
Source File: UserController.java    From tutorials with MIT License 4 votes vote down vote up
@GetMapping("/me/myapi")
public String me(@RequestParam String username, @RequestParam String password, HttpServletResponse responsehttp) {

    try {
        OAuth2AccessToken token = service.getService().getAccessTokenPasswordGrant(username, password);

        OAuthRequest request = new OAuthRequest(Verb.GET, "http://localhost:8080/me");
        service.getService().signRequest(token, request);
        Response response = service.getService().execute(request);

        return response.getBody();

    } catch (Exception e) {
        responsehttp.setStatus(HttpServletResponse.SC_BAD_REQUEST);
    }

    return null;

}