com.github.scribejava.core.oauth.OAuth20Service Java Examples

The following examples show how to use com.github.scribejava.core.oauth.OAuth20Service. 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: AccountService.java    From runelite with BSD 2-Clause "Simplified" License 8 votes vote down vote up
@GetMapping("/login")
public OAuthResponse login(@RequestParam UUID uuid)
{
	State state = new State();
	state.setUuid(uuid);
	state.setApiVersion(RuneLiteAPI.getVersion());

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

	final Map<String, String> additionalParams = new HashMap<>();
	additionalParams.put("prompt", "select_account");

	String authorizationUrl = service.getAuthorizationUrl(additionalParams);

	OAuthResponse lr = new OAuthResponse();
	lr.setOauthUrl(authorizationUrl);
	lr.setUid(uuid);

	return lr;
}
 
Example #2
Source File: OAuthManagerFragmentController.java    From react-native-oauth with MIT License 6 votes vote down vote up
public OAuthManagerFragmentController(
  final ReactContext mReactContext,
  android.app.FragmentManager fragmentManager,
  final String providerName,
  OAuth20Service oauthService,
  final String callbackUrl
) {
  this.uiHandler = new Handler(Looper.getMainLooper());
  this.fragmentManager = fragmentManager;

  this.context = mReactContext;
  this.providerName = providerName;
  this.authVersion = "2.0";
  this.oauth20Service = oauthService;
  this.callbackUrl = callbackUrl;
}
 
Example #3
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 #4
Source File: StripeConnectManager.java    From alf.io with GNU General Public License v3.0 6 votes vote down vote up
@Override
public AccessTokenResponseDetails storeConnectedAccountId(String code, int organizationId) {
    try {
        String clientSecret = baseStripeManager.getSystemSecretKey();
        OAuth20Service service = new ServiceBuilder(clientSecret).apiSecret(clientSecret).build(new StripeConnectApi());
        Map<String, String> token = Json.fromJson(service.getAccessToken(code).getRawResponse(), new TypeReference<>() {});
        String accountId = token.get("stripe_user_id");
        if(accountId != null) {
            configurationManager.saveConfig(Configuration.from(organizationId, ConfigurationKeys.STRIPE_CONNECTED_ID), accountId);
        }
        return new AccessTokenResponseDetails(accountId, null, token.get("error_message"), accountId != null);
    } catch (Exception e) {
        log.error("cannot retrieve account ID", e);
        return new AccessTokenResponseDetails(null, null, e.getMessage(), false);
    }
}
 
Example #5
Source File: MollieConnectManager.java    From alf.io with GNU General Public License v3.0 6 votes vote down vote up
@Override
public AccessTokenResponseDetails storeConnectedAccountId(String code, int organizationId) {
    try {
        ConfigurationLevel configurationLevel = ConfigurationLevel.organization(organizationId);
        var options = configurationManager.getFor(Set.of(MOLLIE_API_KEY, MOLLIE_CONNECT_CLIENT_ID, MOLLIE_CONNECT_CLIENT_SECRET, MOLLIE_CONNECT_CALLBACK, BASE_URL), configurationLevel);
        OAuth20Service service = new ServiceBuilder(options.get(MOLLIE_CONNECT_CLIENT_ID).getRequiredValue())
            .apiSecret(options.get(MOLLIE_CONNECT_CLIENT_SECRET).getRequiredValue())
            .callback(options.get(MOLLIE_CONNECT_CALLBACK).getRequiredValue())
            .build(new MollieConnectApi());
        OAuth2AccessToken accessTokenResponse = service.getAccessToken(code);
        var refreshToken = accessTokenResponse.getRefreshToken();
        if(refreshToken != null) {
            //var mollieProfileId = retrieveProfileId(accessTokenResponse.getAccessToken());
            configurationManager.saveConfig(Configuration.from(organizationId, MOLLIE_CONNECT_REFRESH_TOKEN), refreshToken);
            //configurationManager.saveConfig(Configuration.from(organizationId, MOLLIE_PROFILE_ID), mollieProfileId);
        }
        return new AccessTokenResponseDetails(accessTokenResponse.getAccessToken(), refreshToken, null, true);
    } catch (Exception e) {
        log.warn("Got exception while retrieving access token", e);
        return new AccessTokenResponseDetails(null, null, e.getMessage(), false);
    }
}
 
Example #6
Source File: OAuthManagerProviders.java    From react-native-oauth with MIT License 6 votes vote down vote up
private static OAuth20Service configurableService(
  final HashMap cfg,
  @Nullable final ReadableMap opts,
  final String callbackUrl
) {
  ServiceBuilder builder = OAuthManagerProviders._oauth2ServiceBuilder(cfg, opts, callbackUrl);
  Log.d(TAG, "Creating ConfigurableApi");
  //Log.d(TAG, "    authorize_url:     " + cfg.get("authorize_url"));
  //Log.d(TAG, "    access_token_url:  " + cfg.get("access_token_url"));
  ConfigurableApi api = ConfigurableApi.instance()
    .setAccessTokenEndpoint((String) cfg.get("access_token_url"))
    .setAuthorizationBaseUrl((String) cfg.get("authorize_url"));
  if (cfg.containsKey("access_token_verb")) {
    //Log.d(TAG, "    access_token_verb: " + cfg.get("access_token_verb"));
    api.setAccessTokenVerb((String) cfg.get("access_token_verb"));
  }

  return builder.build(api);
}
 
Example #7
Source File: Oauth20Service.java    From jweb-cms with GNU Affero General Public License v3.0 6 votes vote down vote up
private OAuth20Service service(Provider provider) {
    OauthStrategy strategy = strategy(provider);
    String secretState = "secret" + new Random().nextInt(999_999);
    OAuth20Service service = services.get(provider);
    if (service == null) {
        ServiceBuilder serviceBuilder = new ServiceBuilder(strategy.clientId)
            .apiSecret(strategy.clientSecret)
            .state(secretState)
            .callback(strategy.callback);
        if (!Strings.isNullOrEmpty(provider.scope)) {
            serviceBuilder.scope(provider.scope);
        }
        service = serviceBuilder
            .build(instance(provider));
        services.put(provider, service);
    }
    return service;
}
 
Example #8
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 #9
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 #10
Source File: MollieConnectManager.java    From alf.io with GNU General Public License v3.0 5 votes vote down vote up
public AccessTokenResponseDetails refreshAccessToken(Map<ConfigurationKeys, MaybeConfiguration> options) {
    try {
        OAuth20Service service = new ServiceBuilder(options.get(MOLLIE_CONNECT_CLIENT_ID).getRequiredValue())
            .apiSecret(options.get(MOLLIE_CONNECT_CLIENT_SECRET).getRequiredValue())
            .callback(options.get(MOLLIE_CONNECT_CALLBACK).getRequiredValue())
            .build(new MollieConnectApi());
        String refreshToken = options.get(MOLLIE_CONNECT_REFRESH_TOKEN).getRequiredValue();
        OAuth2AccessToken accessTokenResponse = service.refreshAccessToken(refreshToken);
        return new AccessTokenResponseDetails(accessTokenResponse.getAccessToken(), refreshToken, null, true);
    } catch (Exception e) {
        log.warn("Got exception while retrieving access token", e);
        return new AccessTokenResponseDetails(null, null, e.getMessage(), false);
    }
}
 
Example #11
Source File: GithubController.java    From tutorials with MIT License 5 votes vote down vote up
private OAuth20Service createService(String state) {
    return new ServiceBuilder("e1f8d4f1a5c71467a159")
        .apiSecret("4851597541a8f33a4f1bf1c70f3cedcfefbeb13b")
        .state(state)
        .callback("http://localhost:8080/spring-mvc-simple/github/callback")
        .build(GitHubApi.instance());
}
 
Example #12
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 #13
Source File: DefaultOAuth2ServiceImpl.java    From Orienteer with Apache License 2.0 5 votes vote down vote up
private OAuth2AccessToken getAccessToken(OAuth20Service service, String code) {
    try {
        return service.getAccessToken(code);
    } catch (IOException | ExecutionException | InterruptedException e) {
        throw new IllegalStateException("Can't retrieve access token with code " + code, e);
    }
}
 
Example #14
Source File: DefaultOAuth2ServiceImpl.java    From Orienteer with Apache License 2.0 5 votes vote down vote up
private OAuth20Service createService(OAuth2Service service) {
    IOAuth2Provider provider = service.getProvider();

    ServiceBuilder builder = new ServiceBuilder(service.getApiKey());

    builder.apiSecret(service.getApiSecret())
            .callback(service.getCallback());

    if (!Strings.isNullOrEmpty(provider.getScope())) {
        builder.defaultScope(provider.getScope());
    }

    return builder.build(provider.getInstance());
}
 
Example #15
Source File: DefaultOAuth2ServiceImpl.java    From Orienteer with Apache License 2.0 5 votes vote down vote up
private JsonNode requestProtectedData(OAuth2Service service, IOAuth2Provider provider, String code) {
    OAuth20Service authService = createService(service);
    OAuth2AccessToken accessToken = getAccessToken(authService, code);

    JsonNode jsonNode = requestProtectedData(authService, accessToken, provider.getProtectedResource());
    LOG.debug("Success request protected data: {} {}", jsonNode, service);
    return jsonNode;
}
 
Example #16
Source File: DefaultOAuth2ServiceImpl.java    From Orienteer with Apache License 2.0 5 votes vote down vote up
@Override
public OAuth2ServiceContext requestAuthorizationUrl(OAuth2Service service, String secretState) {
    OAuth20Service auth20Service = createService(service);
    OAuth2ServiceContext state = new OAuth2ServiceContext();

    state.setService(service)
            .setUsed(false)
            .setState(secretState)
            .setAuthorizationUrl(auth20Service.getAuthorizationUrl(secretState));
    return state;
}
 
Example #17
Source File: OAuthManagerProviders.java    From react-native-oauth with MIT License 5 votes vote down vote up
private static OAuth20Service slackService(
  final HashMap cfg,
  @Nullable final ReadableMap opts,
  final String callbackUrl
  ) {

  Log.d(TAG, "Make the builder: " + SlackApi.class);
  ServiceBuilder builder = OAuthManagerProviders._oauth2ServiceBuilder(cfg, opts, callbackUrl);
  return builder.build(SlackApi.instance());
}
 
Example #18
Source File: OAuthManagerProviders.java    From react-native-oauth with MIT License 5 votes vote down vote up
static public OAuth20Service getApiFor20Provider(
  final String providerName,
  final HashMap params,
  @Nullable final ReadableMap opts,
  final String callbackUrl
) {
  if (providerName.equalsIgnoreCase("facebook")) {
    return OAuthManagerProviders.facebookService(params, opts, callbackUrl);
  }

  if (providerName.equalsIgnoreCase("google")) {
    return OAuthManagerProviders.googleService(params, opts, callbackUrl);
  }

  if (providerName.equalsIgnoreCase("github")) {
    return OAuthManagerProviders.githubService(params, opts, callbackUrl);
  }

  if (providerName.equalsIgnoreCase("slack")) {
    return OAuthManagerProviders.slackService(params, opts, callbackUrl);
  }

  if (params.containsKey("access_token_url") && params.containsKey("authorize_url")) {
    return OAuthManagerProviders.configurableService(params, opts, callbackUrl);
  }

  return null;
}
 
Example #19
Source File: OAuthManagerProviders.java    From react-native-oauth with MIT License 5 votes vote down vote up
private static OAuth20Service githubService(
  final HashMap cfg,
  @Nullable final ReadableMap opts,
  final String callbackUrl)
{

  ServiceBuilder builder = OAuthManagerProviders._oauth2ServiceBuilder(cfg, opts, callbackUrl);
  return builder.build(GitHubApi.instance());
}
 
Example #20
Source File: OAuthManagerProviders.java    From react-native-oauth with MIT License 5 votes vote down vote up
private static OAuth20Service googleService(
  final HashMap cfg,
  @Nullable final ReadableMap opts,
  final String callbackUrl)
{
  ServiceBuilder builder = OAuthManagerProviders._oauth2ServiceBuilder(cfg, opts, callbackUrl);
  return builder.build(GoogleApi20.instance());
}
 
Example #21
Source File: OAuthManagerProviders.java    From react-native-oauth with MIT License 5 votes vote down vote up
private static OAuth20Service facebookService(
  final HashMap cfg,
  @Nullable final ReadableMap opts,
  final String callbackUrl) {
  ServiceBuilder builder = OAuthManagerProviders._oauth2ServiceBuilder(cfg, opts, callbackUrl);
  return builder.build(FacebookApi.instance());
}
 
Example #22
Source File: AuthenticationManager.java    From console-java-connect-sample with MIT License 4 votes vote down vote up
public OAuth20Service getOAuthService() {
    return mOAuthService;
}
 
Example #23
Source File: GoogleService.java    From tutorials with MIT License 4 votes vote down vote up
public OAuth20Service getService() {
    return service;
}
 
Example #24
Source File: OAuthTokenClient.java    From android-oauth-handler with MIT License 4 votes vote down vote up
public void fetchAccessToken(final Token requestToken, final Uri uri) {

        Uri authorizedUri = uri;

        if (service.getVersion() == "1.0") {
            // Use verifier token to fetch access token

            if (authorizedUri.getQuery().contains(OAuthConstants.VERIFIER)) {
                String oauth_verifier = authorizedUri.getQueryParameter(OAuthConstants.VERIFIER);
                OAuth1RequestToken oAuth1RequestToken = (OAuth1RequestToken) requestToken;
                OAuth10aService oAuth10aService = (OAuth10aService) service;

                oAuth10aService.getAccessTokenAsync(oAuth1RequestToken, oauth_verifier,
                        new OAuthAsyncRequestCallback<OAuth1AccessToken>() {

                            @Override
                            public void onCompleted(OAuth1AccessToken oAuth1AccessToken) {
                                setAccessToken(oAuth1AccessToken);
                                handler.onReceivedAccessToken(oAuth1AccessToken, service.getVersion());
                            }

                            @Override
                            public void onThrowable(Throwable e) {
                                handler.onFailure(new OAuthException(e.getMessage()));
                            }
                        });

            }
            else { // verifier was null
                throw new OAuthException("No verifier code was returned with uri '" + uri + "' " +
                        "and access token cannot be retrieved");
            }
        } else if (service.getVersion() == "2.0") {
            if (authorizedUri.getQuery().contains(OAuthConstants.CODE)) {
                String code = authorizedUri.getQueryParameter(OAuthConstants.CODE);
                OAuth20Service oAuth20Service = (OAuth20Service) service;
                oAuth20Service.getAccessToken(code, new OAuthAsyncRequestCallback<OAuth2AccessToken>() {
                    @Override
                    public void onCompleted(OAuth2AccessToken accessToken) {
                        setAccessToken(accessToken);
                        handler.onReceivedAccessToken(accessToken, service.getVersion());

                    }

                    @Override
                    public void onThrowable(Throwable t) {

                    }
                });
            }
            else { // verifier was null
                handler.onFailure(new OAuthException("No code was returned with uri '" + uri + "' " +
                        "and access token cannot be retrieved"));
            }
        }
    }
 
Example #25
Source File: MyService.java    From tutorials with MIT License 4 votes vote down vote up
public OAuth20Service getService() {
    return service;
}
 
Example #26
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 #27
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 "";
}