com.github.scribejava.core.builder.ServiceBuilder Java Examples

The following examples show how to use com.github.scribejava.core.builder.ServiceBuilder. 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: ElexisEnvironmentLoginDialog.java    From elexis-3-core with Eclipse Public License 1.0 6 votes vote down vote up
public ElexisEnvironmentLoginDialog(Shell shell, String openidClientSecret, String keycloakUrl,
	String realmPublicKey){
	super(shell);
	
	logger = LoggerFactory.getLogger(getClass());
	
	oauthService = new ServiceBuilder(ElexisEnvironmentLoginContributor.OAUTH2_CLIENT_ID)
		.apiSecret(openidClientSecret).defaultScope("openid").callback(CALLBACK_URL)
		.build(KeycloakApi.instance(keycloakUrl, ElexisEnvironmentLoginContributor.REALM_ID));
	
	KeyFactory kf;
	try {
		kf = KeyFactory.getInstance("RSA");
		X509EncodedKeySpec keySpecX509 =
			new X509EncodedKeySpec(Base64.getDecoder().decode(realmPublicKey));
		RSAPublicKey publicKey = (RSAPublicKey) kf.generatePublic(keySpecX509);
		
		jwtParser = Jwts.parserBuilder().setSigningKey(publicKey).build();
	} catch (NoSuchAlgorithmException | InvalidKeySpecException e) {
		logger.error("Initialization error", e);
	}
	
}
 
Example #3
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 #4
Source File: OAuthManagerProviders.java    From react-native-oauth with MIT License 6 votes vote down vote up
private static OAuth10aService twitterService(
  final HashMap cfg,
  @Nullable final ReadableMap opts,
  final String callbackUrl) {
  String consumerKey = (String) cfg.get("consumer_key");
  String consumerSecret = (String) cfg.get("consumer_secret");

  ServiceBuilder builder = new ServiceBuilder()
        .apiKey(consumerKey)
        .apiSecret(consumerSecret)
        .debug();

  String scopes = (String) cfg.get("scopes");
  if (scopes != null) {
    // String scopeStr = OAuthManagerProviders.getScopeString(scopes, "+");
    // Log.d(TAG, "scopeStr: " + scopeStr);
    // builder.scope(scopeStr);
  }

  if (callbackUrl != null) {
    builder.callback(callbackUrl);
  }

  return builder.build(TwitterApi.instance());
}
 
Example #5
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 #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: 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 #8
Source File: OAuthManagerProviders.java    From react-native-oauth with MIT License 5 votes vote down vote up
private static ServiceBuilder _oauth2ServiceBuilder(
  final HashMap cfg,
  @Nullable final ReadableMap opts,
  final String callbackUrl
) {
  String clientKey = (String) cfg.get("client_id");
  String clientSecret = (String) cfg.get("client_secret");
  String state;
  if (cfg.containsKey("state")) {
    state = (String) cfg.get("state");
  } else {
    state = TAG + new Random().nextInt(999_999);
  }

  // Builder
  ServiceBuilder builder = new ServiceBuilder()
    .apiKey(clientKey)
    .apiSecret(clientSecret)
    .state(state)
    .debug();

  String scopes = "";
  if (cfg.containsKey("scopes")) {
    scopes = (String) cfg.get("scopes");
    String scopeStr = OAuthManagerProviders.getScopeString(scopes, ",");
    builder.scope(scopeStr);
  }

  if (opts != null && opts.hasKey("scopes")) {
    scopes = (String) opts.getString("scopes");
    String scopeStr = OAuthManagerProviders.getScopeString(scopes, ",");
    builder.scope(scopeStr);
  }

  if (callbackUrl != null) {
    builder.callback(callbackUrl);
  }

  return builder;
}
 
Example #9
Source File: OAuthTokenClient.java    From android-oauth-handler with MIT License 5 votes vote down vote up
public OAuthTokenClient(BaseApi apiInstance, String consumerKey, String consumerSecret, String callbackUrl,
                        String scope, OAuthTokenHandler handler) {
    this.apiInstance = apiInstance;
    this.handler = handler;
    if (callbackUrl == null) { callbackUrl = OAuthConstants.OUT_OF_BAND; };
    this.service = new ServiceBuilder()
            .apiKey(consumerKey)
            .apiSecret(consumerSecret).callback(callbackUrl)
            .httpClientConfig(OkHttpHttpClientConfig.defaultConfig())
            .scope(scope) // OAuth2 requires scope
            .build(apiInstance);
}
 
Example #10
Source File: GoogleService.java    From tutorials with MIT License 5 votes vote down vote up
@PostConstruct
private void init(){
    this.service  = new ServiceBuilder(API_KEY)
            .apiSecret(API_SECRET)
            .scope(SCOPE)
            .callback(CALLBACK)
            .build(GoogleApi20.instance());
}
 
Example #11
Source File: MyService.java    From tutorials with MIT License 5 votes vote down vote up
@PostConstruct
private void init(){
    this.service  = new ServiceBuilder(API_KEY)
            .apiSecret(API_SECRET)
            .scope("read write")
            .build(MyApi.instance());
}
 
Example #12
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 #13
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 #14
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 #15
Source File: GitHubApiHelper.java    From gdx-texture-packer-gui with Apache License 2.0 5 votes vote down vote up
public GitHubApiHelper() throws IOException {
    apiSecret = resolveApiKey();

    authCallbackHandler = new AuthCallbackHandler();

    // Request access to interact with public repos.
    apiService = new ServiceBuilder("466a909f95b8e2789a5e")
            .apiSecret(apiSecret)
            .defaultScope("public_repo")    // Request access to interact with public repos.
            .callback(AuthCallbackHandler.CALLBACK_URL)
            .build(GitHubApi.instance());

    json = new Json(JsonWriter.OutputType.json);
}
 
Example #16
Source File: OAuth.java    From openapi-generator with Apache License 2.0 5 votes vote down vote up
public OAuth setCredentials(String clientId, String clientSecret, Boolean debug) {
    if (Boolean.TRUE.equals(debug)) {
        service = new ServiceBuilder(clientId)
            .apiSecret(clientSecret).debug()
            .build(authApi);
    } else {
        service = new ServiceBuilder(clientId)
            .apiSecret(clientSecret)
            .build(authApi);
    }
    return this;
}
 
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
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 #19
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 #20
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 #21
Source File: GoogleIdentityProvider.java    From sonar-auth-google with Apache License 2.0 5 votes vote down vote up
private ServiceBuilder newScribeBuilder(OAuth2IdentityProvider.OAuth2Context context) {
  if (!isEnabled()) {
    throw new IllegalStateException("Google authentication is disabled");
  }
  return new ServiceBuilder()
    .provider(scribeApi)
    .apiKey(settings.clientId())
    .apiSecret(settings.clientSecret())
    .grantType("authorization_code")
    .callback(context.getCallbackUrl());
}
 
Example #22
Source File: TwitterAuthHelper.java    From PYX-Reloaded with Apache License 2.0 5 votes vote down vote up
private TwitterAuthHelper(@NotNull String appId, @NotNull String appSecret, @NotNull String callback) {
    service = new ServiceBuilder(appId)
            .apiSecret(appSecret)
            .callback(callback)
            .httpClient(new HttpClientWrapper())
            .build(TwitterApi.Authenticate.instance());
}
 
Example #23
Source File: OAuth.java    From openapi-generator with Apache License 2.0 5 votes vote down vote up
public OAuth setCredentials(String clientId, String clientSecret, Boolean debug) {
    if (Boolean.TRUE.equals(debug)) {
        service = new ServiceBuilder(clientId)
            .apiSecret(clientSecret).debug()
            .build(authApi);
    } else {
        service = new ServiceBuilder(clientId)
            .apiSecret(clientSecret)
            .build(authApi);
    }
    return this;
}
 
Example #24
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 #25
Source File: TwitterController.java    From tutorials with MIT License 4 votes vote down vote up
private OAuth10aService createService() {
    return new ServiceBuilder("PSRszoHhRDVhyo2RIkThEbWko")
        .apiSecret("prpJbz03DcGRN46sb4ucdSYtVxG8unUKhcnu3an5ItXbEOuenL")
        .callback("http://localhost:8080/spring-mvc-simple/twitter/callback")
        .build(TwitterApi.instance());
}
 
Example #26
Source File: TwitterService.java    From tutorials with MIT License 4 votes vote down vote up
@PostConstruct
private void init(){
    this.service = new ServiceBuilder(API_KEY)
            .apiSecret(API_SECRET)
            .build(TwitterApi.instance());
}
 
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 "";
}