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

The following examples show how to use com.github.scribejava.core.model.OAuth2AccessToken. 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: OAuthAsyncHttpClient.java    From android-oauth-handler with MIT License 6 votes vote down vote up
public static OAuthAsyncHttpClient create(final OAuth2AccessToken token) {
    final String bearer = String.format("%s %s", BEARER, token.getAccessToken());

    HttpLoggingInterceptor logging = createLogger();

    OkHttpClient httpClient = new OkHttpClient.Builder()
            .addInterceptor(logging)
            .addNetworkInterceptor(new StethoInterceptor())
            .addInterceptor(new Interceptor() {
                                @NotNull
                                @Override
                                public Response intercept(@NotNull Chain chain) throws IOException {
                                    Request originalRequest = chain.request();
                                    Request authedRequest = originalRequest.newBuilder().header("Authorization", bearer).build();
                                    return chain.proceed(authedRequest);
                                }
                            }).build();

    OAuthAsyncHttpClient asyncHttpClient = new OAuthAsyncHttpClient(httpClient);
    return asyncHttpClient;
}
 
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: 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 #4
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 #5
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 #6
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 #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: OAuthManagerFragmentController.java    From react-native-oauth with MIT License 5 votes vote down vote up
@Override
protected void onPostExecute(final OAuth2AccessToken accessToken) {
  runOnMainThread(new Runnable() {
    @Override
    public void run() {
      if (accessToken == null) {
        mCtrl.onError(-1, "No accessToken found", "");
        return;
      }
      mCtrl.loaded20AccessToken(accessToken);
    }
  });
}
 
Example #9
Source File: OAuth.java    From openapi-generator with Apache License 2.0 5 votes vote down vote up
public OAuth2AccessToken renewAccessToken() throws ApiException {
    String refreshToken = null;
    if (accessToken != null) {
        refreshToken = accessToken.getRefreshToken();
        accessToken = null;
    }
    return obtainAccessToken(refreshToken);
}
 
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: 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 #12
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 #13
Source File: OAuthManagerStore.java    From react-native-oauth with MIT License 5 votes vote down vote up
public void store(String providerName, final OAuth2AccessToken accessToken) {
  if (accessToken == null) {
    throw new IllegalArgumentException("Token is null");
  }
  if (providerName.equals("") || providerName == null) {
    throw new IllegalArgumentException("Provider is null");
  }
  editor.putString(providerName, new Gson().toJson(accessToken));
}
 
Example #14
Source File: OAuthBaseClient.java    From android-oauth-handler with MIT License 5 votes vote down vote up
public void instantiateClient(String consumerKey, String consumerSecret, Token token) {

        if (token instanceof OAuth1AccessToken) {
            client = OAuthAsyncHttpClient.create(consumerKey, consumerSecret, (OAuth1AccessToken)(token));
        } else if (token instanceof OAuth2AccessToken){
            client = OAuthAsyncHttpClient.create((OAuth2AccessToken) token);
        } else {
            throw new IllegalStateException("unrecognized token type" + token);
        }

    }
 
Example #15
Source File: OAuth.java    From openapi-generator with Apache License 2.0 5 votes vote down vote up
public OAuth2AccessToken renewAccessToken() throws ApiException {
    String refreshToken = null;
    if (accessToken != null) {
        refreshToken = accessToken.getRefreshToken();
        accessToken = null;
    }
    return obtainAccessToken(refreshToken);
}
 
Example #16
Source File: OAuthBaseClient.java    From android-oauth-handler with MIT License 5 votes vote down vote up
public Token checkAccessToken() {
    int oAuthVersion = prefs.getInt(OAuthConstants.VERSION, 0);

    if (oAuthVersion == 1 && prefs.contains(OAuthConstants.TOKEN) && prefs.contains(OAuthConstants.TOKEN_SECRET)) {
        return new OAuth1AccessToken(prefs.getString(OAuthConstants.TOKEN, ""),
                prefs.getString(OAuthConstants.TOKEN_SECRET, ""));
    } else if (oAuthVersion == 2 && prefs.contains(OAuthConstants.TOKEN)) {
        return new OAuth2AccessToken(prefs.getString(OAuthConstants.TOKEN, ""));
    }
    return null;
}
 
Example #17
Source File: OAuthManagerFragmentController.java    From react-native-oauth with MIT License 4 votes vote down vote up
public void loaded20AccessToken(final OAuth2AccessToken accessToken) {
  mWebView = null;
  this.dismissDialog();
  mListener.onOAuth2AccessToken(accessToken);
}
 
Example #18
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;

}
 
Example #19
Source File: OAuthBaseClient.java    From android-oauth-handler with MIT License 4 votes vote down vote up
public OAuthBaseClient(Context c, final BaseApi apiInstance, String consumerUrl, final String consumerKey, final String consumerSecret, @Nullable String scope, String callbackUrl) {
    this.baseUrl = consumerUrl;
    this.callbackUrl = callbackUrl;
    tokenClient = new OAuthTokenClient(apiInstance, consumerKey,
            consumerSecret, callbackUrl, scope, new OAuthTokenClient.OAuthTokenHandler() {

        // Store request token and launch the authorization URL in the browser
        @Override
        public void onReceivedRequestToken(Token requestToken, String authorizeUrl, String oAuthVersion) {
            if (requestToken != null) {
                if (oAuthVersion == OAUTH1_VERSION) {  // store for OAuth1.0a
                    OAuth1RequestToken oAuth1RequestToken = (OAuth1RequestToken) requestToken;
                    editor.putString(OAUTH1_REQUEST_TOKEN, oAuth1RequestToken.getToken());
                    editor.putString(OAUTH1_REQUEST_TOKEN_SECRET, oAuth1RequestToken.getTokenSecret());
                    editor.putInt(OAuthConstants.VERSION, 1);
                    editor.commit();
                }
            }
            // Launch the authorization URL in the browser
            Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse(authorizeUrl));
            if (requestIntentFlags != -1) {
                intent.setFlags(requestIntentFlags);
            }
            OAuthBaseClient.this.context.startActivity(intent);
        }

        // Store the access token in preferences, set the token in the tokenClient and fire the success callback
        @Override
        public void onReceivedAccessToken(Token accessToken, String oAuthVersion) {

            if (oAuthVersion == OAUTH1_VERSION) {
                OAuth1AccessToken oAuth1AccessToken = (OAuth1AccessToken) accessToken;

                tokenClient.setAccessToken(accessToken);
                instantiateClient(consumerKey, consumerSecret, oAuth1AccessToken);
                editor.putString(OAuthConstants.TOKEN, oAuth1AccessToken.getToken());
                editor.putString(OAuthConstants.TOKEN_SECRET, oAuth1AccessToken.getTokenSecret());
                editor.putInt(OAuthConstants.VERSION, 1);
                editor.commit();
            } else if (oAuthVersion == OAUTH2_VERSION) {
                OAuth2AccessToken oAuth2AccessToken = (OAuth2AccessToken) accessToken;
                instantiateClient(consumerKey, consumerSecret, oAuth2AccessToken);
                tokenClient.setAccessToken(accessToken);
                editor.putString(OAuthConstants.TOKEN, oAuth2AccessToken.getAccessToken());
                editor.putString(OAuthConstants.SCOPE, oAuth2AccessToken.getScope());
                editor.putString(OAuthConstants.REFRESH_TOKEN, oAuth2AccessToken.getRefreshToken());
                editor.putInt(OAuthConstants.VERSION, 2);
                editor.commit();

            }
            accessHandler.onLoginSuccess();
        }

        @Override
        public void onFailure(Exception e) {
            accessHandler.onLoginFailure(e);
        }

    });

    this.context = c;
    // Store preferences namespaced by the class and consumer key used
    this.prefs = this.context.getSharedPreferences("OAuth_" + apiInstance.getClass().getSimpleName() + "_" + consumerKey, 0);
    this.editor = this.prefs.edit();
    // Set access token in the tokenClient if already stored in preferences
    Token accessToken = this.checkAccessToken();
    if (accessToken != null) {
        tokenClient.setAccessToken(accessToken);
        instantiateClient(consumerKey, consumerSecret, accessToken);
    }
}
 
Example #20
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 #21
Source File: Network.java    From mirror with MIT License 4 votes vote down vote up
/**
 * Creates a new access token by wrapping a {@link OAuth2AccessToken}.
 */
public AccessToken(OAuth2AccessToken accessToken, long refreshTime) {
  this(accessToken.getAccessToken(), accessToken.getExpiresIn(), accessToken.getRefreshToken(),
      refreshTime);
}
 
Example #22
Source File: OAuthManagerModule.java    From react-native-oauth with MIT License 4 votes vote down vote up
private WritableMap accessTokenResponse(
  final String providerName,
  final HashMap<String,Object> cfg,
  final OAuth2AccessToken accessToken,
  final String oauthVersion
) {
  WritableMap resp = Arguments.createMap();
  WritableMap response = Arguments.createMap();

  resp.putString("status", "ok");
  resp.putBoolean("authorized", true);
  resp.putString("provider", providerName);

  String uuid = accessToken.getParameter("user_id");
  response.putString("uuid", uuid);
  
  WritableMap credentials = Arguments.createMap();
  Log.d(TAG, "Credential raw response: " + accessToken.getRawResponse());
  
  credentials.putString("accessToken", accessToken.getAccessToken());
  String authHeader;

  String tokenType = accessToken.getTokenType();
  if (tokenType == null) {
    tokenType = "Bearer";
  }
  
  String scope = accessToken.getScope();
  if (scope == null) {
    scope = (String) cfg.get("scopes");
  }

  String clientID = (String) cfg.get("client_id");
  String idToken = accessToken.getParameter("id_token");

  authHeader = tokenType + " " + accessToken.getAccessToken();
  credentials.putString("authorizationHeader", authHeader);
  credentials.putString("type", tokenType);
  credentials.putString("scopes", scope);
  credentials.putString("clientID", clientID);
  credentials.putString("idToken", idToken);
  response.putMap("credentials", credentials);

  resp.putMap("response", response);

  return resp;
}
 
Example #23
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 #24
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 #25
Source File: AccessTokenController.java    From sso with MIT License 4 votes vote down vote up
/**
 * qq代理转发
 *
 * @return
 */
@RequestMapping(value = "/qq", produces = {"application/json"})
public Object qq(
        @RequestParam(OAuthConstants.CLIENT_ID) String client_id,
        @RequestParam(OAuthConstants.CLIENT_SECRET) String client_secret,
        @RequestParam(OAuthConstants.CODE) String code,
        @RequestParam(OAuthConstants.REDIRECT_URI) String redirect_uri,
        @RequestParam(OAuthConstants.GRANT_TYPE) String authorization_code,
        HttpServletResponse response) throws Exception {
    HttpHeaders headers = new HttpHeaders();
    headers.setContentType(MediaType.APPLICATION_FORM_URLENCODED);

    MultiValueMap<String, String> map = new LinkedMultiValueMap<>();

    map.add(OAuthConstants.CLIENT_ID, client_id);
    map.add(OAuthConstants.CLIENT_SECRET, client_secret);
    map.add(OAuthConstants.CODE, code);
    map.add(OAuthConstants.REDIRECT_URI, redirect_uri);
    map.add(OAuthConstants.GRANT_TYPE, authorization_code);

    HttpEntity<MultiValueMap<String, String>> request = new HttpEntity<>(map, headers);
    ResponseEntity<String> resp = restTemplate.exchange("https://graph.qq.com/oauth2.0/token", HttpMethod.POST, request, String.class);


    response.setContentType("application/json");
    OAuth2AccessToken token = tokenExtractor.extract(new Response(
            resp.getStatusCodeValue(),
            resp.toString(),
            resp.getHeaders().toSingleValueMap(),
            resp.getBody(), null
    ));

    //返回结果
    Map<String, Object> res = new HashMap<>();
    res.put("access_token", token.getAccessToken());
    res.put("token_type", token.getTokenType());
    res.put("expires_in", token.getExpiresIn());
    res.put("refresh_token", token.getRefreshToken());
    res.put("error_description", token.getTokenType());
    res.put("scope", token.getScope());
    return res;
}
 
Example #26
Source File: OAuth.java    From openapi-generator with Apache License 2.0 4 votes vote down vote up
public OAuth setAccessToken(String accessToken) {
    this.accessToken = new OAuth2AccessToken(accessToken);
    return this;
}
 
Example #27
Source File: OAuth.java    From openapi-generator with Apache License 2.0 4 votes vote down vote up
public OAuth setAccessToken(OAuth2AccessToken accessToken) {
    this.accessToken = accessToken;
    return this;
}
 
Example #28
Source File: OAuth.java    From openapi-generator with Apache License 2.0 4 votes vote down vote up
public OAuth2AccessToken getAccessToken() {
    return accessToken;
}
 
Example #29
Source File: OAuth.java    From openapi-generator with Apache License 2.0 4 votes vote down vote up
public OAuth setAccessToken(String accessToken) {
    this.accessToken = new OAuth2AccessToken(accessToken);
    return this;
}
 
Example #30
Source File: OAuth.java    From openapi-generator with Apache License 2.0 4 votes vote down vote up
public OAuth setAccessToken(OAuth2AccessToken accessToken) {
    this.accessToken = accessToken;
    return this;
}