Java Code Examples for com.github.scribejava.core.oauth.OAuth20Service#execute()

The following examples show how to use com.github.scribejava.core.oauth.OAuth20Service#execute() . 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: GithubController.java    From tutorials with MIT License 6 votes vote down vote up
@GetMapping(value = "/callback", produces = "text/plain")
@ResponseBody
public String callback(HttpServletRequest servletReq, @RequestParam("code") String code, @RequestParam("state") String state) throws InterruptedException, ExecutionException, IOException {
    String initialState = (String) servletReq.getSession().getAttribute("state");
    if(initialState.equals(state)) {
        OAuth20Service githubService = createService(initialState);
        OAuth2AccessToken accessToken = githubService.getAccessToken(code);

        OAuthRequest request = new OAuthRequest(Verb.GET, "https://api.github.com/user");
        githubService.signRequest(accessToken, request);
        Response response = githubService.execute(request);

        return response.getBody();
    }
    return "Error";
}
 
Example 3
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 4
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 5
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;
  }
}