com.github.scribejava.core.model.Response Java Examples
The following examples show how to use
com.github.scribejava.core.model.Response.
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 |
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: JamAuthConfig.java From jam-collaboration-sample with Apache License 2.0 | 6 votes |
public String getSingleUseToken() { OAuth10aService service = JamAuthConfig.instance().getOAuth10aService(); final OAuthRequest request = new OAuthRequest(Verb.POST, JamAuthConfig.instance().getServerUrl() + "/v1/single_use_tokens", service); service.signRequest(JamAuthConfig.instance().getOAuth10aAccessToken(), request); final Response response = request.send(); String body = response.getBody(); Matcher matcher = SINGLE_USE_TOKEN_PATTERN.matcher(body); if (matcher.find()) { return matcher.group(0); } return null; }
Example #3
Source File: GoogleController.java From tutorials with MIT License | 6 votes |
@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: GitHubApiHelper.java From gdx-texture-packer-gui with Apache License 2.0 | 5 votes |
/** 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 #5
Source File: DefaultOAuth2ServiceImpl.java From Orienteer with Apache License 2.0 | 5 votes |
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 #6
Source File: AccessTokenController.java From sso with MIT License | 4 votes |
/** * 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 #7
Source File: AccountService.java From runelite with BSD 2-Clause "Simplified" License | 4 votes |
@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 #8
Source File: Network.java From mirror with MIT License | 4 votes |
/** * 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 #9
Source File: UserController.java From tutorials with MIT License | 4 votes |
@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; }