/** * Handles the callback from the OAuth provider, returning a valid Credential if successful. * @param code * @param userId * @return * @throws IOException */ public Credential authorize(String code, @Nullable String userId) throws IOException { String redirectUri = getRedirectUrl(); AuthorizationCodeFlow codeFlow = createCodeFlow(); TokenResponse response = codeFlow .newTokenRequest(code) .setRedirectUri(redirectUri) .setScopes(scopes) .execute(); return codeFlow.createAndStoreCredential(response, userId); }
public static Credential getCredential(String userId) throws IOException { if (userId == null) { return null; } else { return AuthUtil.newAuthorizationCodeFlow().loadCredential(userId); } }
/** * Gets the authorization URL to retrieve the authorization code. */ @Nullable public String getAuthorizationUrl() throws UnsupportedEncodingException { String authorizationCodeRequestUrl = authorizationCodeFlow.newAuthorizationUrl().setScopes(scopes).build(); if (redirectUri != null) { authorizationCodeRequestUrl += "&redirect_uri=" + URLEncoder.encode(redirectUri, "UTF-8"); } return authorizationCodeRequestUrl; }
/** * Invalidate OAuth token for specified user. * * @param userId user * @return <code>true</code> if OAuth token invalidated and <code>false</code> otherwise, e.g. if * user does not have token yet */ public boolean invalidateToken(String userId) throws IOException { Credential credential = flow.loadCredential(userId); if (credential != null) { flow.getCredentialDataStore().delete(userId); return true; } return false; }
/** * Authorizes the installed application to access user's protected data. * * @param userId user ID or {@code null} if not using a persisted credential store * @return credential */ public Credential authorize(String userId) throws IOException { try { Credential credential = flow.loadCredential(userId); if (credential != null && (credential.getRefreshToken() != null || credential.getExpiresInSeconds() == null || credential.getExpiresInSeconds() > 60)) { return credential; } // open in browser String redirectUri = receiver.getRedirectUri(); AuthorizationCodeRequestUrl authorizationUrl = flow.newAuthorizationUrl().setRedirectUri(redirectUri); onAuthorization(authorizationUrl); // receive authorization code and exchange it for an access token String code = receiver.waitForCode(); TokenResponse response = flow.newTokenRequest(code).setRedirectUri(redirectUri).execute(); // store credential and return it return flow.createAndStoreCredential(response, userId); } finally { receiver.stop(); } }
flow.newTokenRequest(req.getParameter("code")) .setRedirectUri(WebUtil.buildUrl(req, "/oauth2callback")).execute(); flow.createAndStoreCredential(tokenResponse, userId); flow.newAuthorizationUrl().setRedirectUri(WebUtil.buildUrl(req, "/oauth2callback")); url.set("approval_prompt", "force"); res.sendRedirect(url.build());
flow.newTokenRequest(code) .setRequestInitializer( request -> { if (request.getParser() == null) { request.setParser(flow.getJsonFactory().createJsonObjectParser()); getUser(newDto(OAuthToken.class).withToken(tokenResponse.getAccessToken())).getId(); flow.createAndStoreCredential(tokenResponse, userId); return userId; } catch (IOException ioe) {
.setScopes(scopes) .build(); final AuthorizationCodeRequestUrl authorizationCodeRequestUrl = flow.newAuthorizationUrl(); authorizationCodeRequestUrl.setRedirectUri(redirectUri); authorizationCodeRequestUrl.setState(new AlphanumericRandomStringService().random()); final TokenResponse response = flow.newTokenRequest(input.getPassword()) .setRedirectUri(redirectUri).setScopes(scopes.isEmpty() ? null : scopes) .executeUnparsed().parseAs(PermissiveTokenResponse.class).toTokenResponse();
flow = initializeFlow(); credential = flow.loadCredential(userId); AuthorizationCodeRequestUrl authorizationUrl = flow.newAuthorizationUrl(); authorizationUrl.setRedirectUri(getRedirectUri(req)); onAuthorization(req, resp, authorizationUrl);
return (GoogleTokenResponse) flow.newTokenRequest(code).setRedirectUri("http://localhost:8080/appweb/ServletOAuth2Callback").execute();
public void setToken(String userId, OAuthToken token) throws IOException { flow.createAndStoreCredential( new TokenResponse().setAccessToken(token.getToken()).setScope(token.getScope()), userId); } }
/** * Clears the credential for the user in the underlying (@link DateStore}. * @throws AuthException If the credential could not be cleared. */ public void clearCredential(String userId) throws AuthException { try { authorizationCodeFlow.getCredentialDataStore().delete(userId); } catch (IOException e) { throw new AuthException("Unable to clear credential.", e); } }
@Override protected final void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { StringBuffer buf = req.getRequestURL(); if (req.getQueryString() != null) { buf.append('?').append(req.getQueryString()); } AuthorizationCodeResponseUrl responseUrl = new AuthorizationCodeResponseUrl(buf.toString()); String code = responseUrl.getCode(); if (responseUrl.getError() != null) { onError(req, resp, responseUrl); } else if (code == null) { resp.setStatus(HttpServletResponse.SC_BAD_REQUEST); resp.getWriter().print("Missing authorization code"); } else { lock.lock(); try { if (flow == null) { flow = initializeFlow(); } String redirectUri = getRedirectUri(req); TokenResponse response = flow.newTokenRequest(code).setRedirectUri(redirectUri).execute(); String userId = getUserId(req); Credential credential = flow.createAndStoreCredential(response, userId); onSuccess(req, resp, credential); } finally { lock.unlock(); } } }
public Credential loadCredential(String userId) { try { return createCodeFlow().loadCredential(userId); } catch (IOException e) { logger.error("Could not load credential", e); return null; } }
@Override public String getRedirectedUrl() { String uuid = UUID.randomUUID().toString(); log.trace("Registered oauth state {}", uuid); cache.put(uuid, DUMMY); return codeFlow.newAuthorizationUrl() .setState(uuid) .setRedirectUri(configuration.getRedirectedUri()).build(); }
/** * Returns an authorized Bitbucket API service. * @param authorizationCode authorization code received by the redirection * endpoint * @param redirectionEndpoint redirection endpoint URI that was used in the * authorization request; if this argument is <code>null</code>, the * <code>redirect_uri</code> parameter shall not be used. * @return authorized Bitbucket REST API service * @throws IOException if an I/O exception has occurred * @throws NullPointerException if this object has no client credentials */ public Service getService( String authorizationCode, URI redirectionEndpoint) throws IOException { AuthorizationCodeFlow flow = getAuthorizationCodeFlow(true); AuthorizationCodeTokenRequest request = flow.newTokenRequest(authorizationCode); if (redirectionEndpoint != null) { request.setRedirectUri(redirectionEndpoint.toString()); } TokenResponse tokenResponse = request.execute(); String tokenType = tokenResponse.getTokenType(); if (!tokenType.equals(BEARER_TOKEN_TYPE)) { throw new UnknownServiceException("Unsupported token type"); } return new RestService( flow.createAndStoreCredential(tokenResponse, getUser())); }
/** * Loads the Credential for the user from the underlying {@link DataStore}. * @throws AuthException If the credential could not be loaded. */ public Credential loadCredential(String userId) throws AuthException { try { return authorizationCodeFlow.loadCredential(userId); } catch (IOException e) { throw new AuthException("Unable to load credential.", e); } }
/** * Starts the login session. */ @SuppressFBWarnings("J2EE_STORE_OF_NON_SERIALIZABLE_OBJECT_INTO_SESSION") public HttpResponse doCommenceLogin() throws IOException { // remember this in the session Stapler.getCurrentRequest().getSession().setAttribute(SESSION_NAME, this); AuthorizationCodeRequestUrl authorizationCodeRequestUrl = flow.newAuthorizationUrl().setState(uuid).setRedirectUri(redirectUrl); return new HttpRedirect(authorizationCodeRequestUrl.toString()); }
/** * Authenticates using the authorization code for the user and stores the Credential in the * underlying {@link DataStore}. * @throws AuthException If the credential could not be created. */ public Credential authenticate(String authorizationCode, String userId) throws AuthException { Preconditions.checkNotNull(authorizationCode, "Authorization code must not be null"); AuthorizationCodeTokenRequest tokenRequest = authorizationCodeFlow.newTokenRequest(authorizationCode); TokenResponse tokenResponse; try { tokenResponse = tokenRequest .setRedirectUri(redirectUri) .setScopes(scopes) .execute(); } catch (IOException e) { throw new AuthException("Unable to request token.", e); } try { return authorizationCodeFlow.createAndStoreCredential(tokenResponse, userId); } catch (IOException e) { throw new AuthException("Unable to create and store credential.", e); } }
@Override public Credential loadCredential(String userId) throws IOException { return new OneDriveCredential(super.loadCredential(userId), businessResource); }