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

The following examples show how to use com.github.scribejava.core.oauth.OAuth20Service#getAccessToken() . 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: 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 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: 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 5
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 6
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"));
            }
        }
    }