com.google.api.client.auth.oauth2.AuthorizationCodeTokenRequest Java Examples

The following examples show how to use com.google.api.client.auth.oauth2.AuthorizationCodeTokenRequest. 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: AuthorizationFlow.java    From android-oauth-client with Apache License 2.0 6 votes vote down vote up
@Override
public AuthorizationCodeTokenRequest newTokenRequest(String authorizationCode) {
    return new LenientAuthorizationCodeTokenRequest(getTransport(), getJsonFactory(),
            new GenericUrl(getTokenServerEncodedUrl()), authorizationCode)
            .setClientAuthentication(getClientAuthentication())
            .setScopes(getScopes())
            .setRequestInitializer(
                    new HttpRequestInitializer() {
                        @Override
                        public void initialize(HttpRequest request) throws IOException {
                            HttpRequestInitializer requestInitializer = getRequestInitializer();
                            // If HttpRequestInitializer is set, initialize it as before
                            if (requestInitializer != null) {
                                requestInitializer.initialize(request);
                            }
                            // Also set JSON accept header
                            request.getHeaders().setAccept("application/json");
                        }
                    });
}
 
Example #2
Source File: MicrosoftAuthorizationCodeFlow.java    From codenvy with Eclipse Public License 1.0 5 votes vote down vote up
@Override
public AuthorizationCodeTokenRequest newTokenRequest(String authorizationCode) {
  // don't need to specify clientId
  // don't need to specify redirectUri to give control of it to user of this class
  return new MicrosoftAuthorizationCodeTokenRequest(
          getTransport(), getJsonFactory(), getTokenServerEncodedUrl(), "", authorizationCode, "")
      .setClientAuthentication(getClientAuthentication())
      .setRequestInitializer(getRequestInitializer())
      .setScopes(getScopes());
}
 
Example #3
Source File: MendeleyClient.java    From slr-toolkit with Eclipse Public License 1.0 5 votes vote down vote up
/**
 * This Method exchanges the authorization code for an access token. 
 * If successful the Tokens and Expiration Date will be stored.
 * 
 * @param code The authorization code from the user interface response has to be passed
 * @throws IOException
 * @throws TokenMgrException
 * @throws ParseException
 */
public void requestAccessToken(String code) throws IOException, TokenMgrException, ParseException {
 try {
   TokenResponse response =
       new AuthorizationCodeTokenRequest(new NetHttpTransport(), new JacksonFactory(),
           new GenericUrl("https://api.mendeley.com/oauth/token"),code)
           .setRedirectUri("https://localhost")
           .setGrantType("authorization_code")
           .setClientAuthentication(
               new BasicAuthentication("4335", "sSFcbUA38RS9Cpm7")).execute();
   
   this.access_token = response.getAccessToken();
   this.refresh_token = response.getRefreshToken();
   this.expires_at = this.generateExpiresAtFromExpiresIn(response.getExpiresInSeconds().intValue());
   
   updatePreferenceStore();
   refreshTokenIfNecessary();
 } catch (TokenResponseException e) {
   if (e.getDetails() != null) {
     System.err.println("Error: " + e.getDetails().getError());
     if (e.getDetails().getErrorDescription() != null) {
       System.err.println(e.getDetails().getErrorDescription());
     }
     if (e.getDetails().getErrorUri() != null) {
       System.err.println(e.getDetails().getErrorUri());
     }
   } else {
     System.err.println(e.getMessage());
   }
 }
}
 
Example #4
Source File: OpenIdConnectAuthenticator.java    From fess with Apache License 2.0 5 votes vote down vote up
protected TokenResponse getTokenUrl(final String code) throws IOException {
    return new AuthorizationCodeTokenRequest(httpTransport, jsonFactory, new GenericUrl(getOicTokenServerUrl()), code)//
            .setGrantType("authorization_code")//
            .setRedirectUri(getOicRedirectUrl())//
            .set("client_id", getOicClientId())//
            .set("client_secret", getOicClientSecret())//
            .execute();
}
 
Example #5
Source File: OicSecurityRealm.java    From oic-auth-plugin with MIT License 4 votes vote down vote up
/**
 * Handles the the securityRealm/commenceLogin resource and sends the user off to the IdP
 * @param from the relative URL to the page that the user has just come from
 * @param referer the HTTP referer header (where to redirect the user back to after login has finished)
 * @return an {@link HttpResponse} object
*/
public HttpResponse doCommenceLogin(@QueryParameter String from, @Header("Referer") final String referer) {
    final String redirectOnFinish = determineRedirectTarget(from, referer);

    final AuthorizationCodeFlow flow = new AuthorizationCodeFlow.Builder(
            BearerToken.queryParameterAccessMethod(),
            httpTransport,
            JSON_FACTORY,
            new GenericUrl(tokenServerUrl),
            new ClientParametersAuthentication(
                    clientId,
                    clientSecret.getPlainText()
            ),
            clientId,
            authorizationServerUrl
    )
        .setScopes(Arrays.asList(scopes))
        .build();

    return new OicSession(flow, from, buildOAuthRedirectUrl()) {
        @Override
        public HttpResponse onSuccess(String authorizationCode) {
            try {
                AuthorizationCodeTokenRequest tokenRequest = flow.newTokenRequest(authorizationCode)
                    .setRedirectUri(buildOAuthRedirectUrl());
                // Supplying scope is not allowed when obtaining an access token with an authorization code.
                tokenRequest.setScopes(Collections.<String>emptyList());

                IdTokenResponse response = IdTokenResponse.execute(tokenRequest);

                this.setIdToken(response.getIdToken());

                IdToken idToken = IdToken.parse(JSON_FACTORY, response.getIdToken());

                Object username;
                GenericJson userInfo = null;
                if (Strings.isNullOrEmpty(userInfoServerUrl)) {
                    username = getField(idToken.getPayload(), userNameField);
                    if(username == null) {
                        return HttpResponses.error(500,"no field '" + userNameField + "' was supplied in the token payload to be used as the username");
                    }
                } else {
                    userInfo = getUserInfo(flow, response.getAccessToken());
                    username = getField(userInfo, userNameField);
                    if(username == null) {
                        return HttpResponses.error(500,"no field '" + userNameField + "' was supplied by the UserInfo payload to be used as the username");
                    }
                }

                if(failedCheckOfTokenField(idToken)) {
                    return HttpResponses.errorWithoutStack(401, "Unauthorized");
                }

                flow.createAndStoreCredential(response, null);

                loginAndSetUserData(username.toString(), idToken, userInfo);

                return new HttpRedirect(redirectOnFinish);

            } catch (IOException e) {
                return HttpResponses.error(500,e);
            }

        }
    }.doCommenceLogin();
}
 
Example #6
Source File: OAuth2WebViewActivity.java    From apigee-android-sdk with Apache License 2.0 4 votes vote down vote up
@Override
protected Void doInBackground(String...params) {
    if (this.url.startsWith(this.redirectURL))
    {
        OAuth2WebViewActivity.this.handledRedirect = true;
        this.resultIntent = new Intent();
        try {
            Map<String,String> urlQueryParams = this.extractQueryParams(url);
            if( urlQueryParams.get(OAuth2AccessTokenExtraKey) != null ) {
                this.resultIntent.putExtra(OAuth2AccessTokenExtraKey,urlQueryParams.get(OAuth2AccessTokenExtraKey));
                if( urlQueryParams.get(OAuth2ExpiresInExtraKey) != null ) {
                    this.resultIntent.putExtra(OAuth2ExpiresInExtraKey,urlQueryParams.get(OAuth2ExpiresInExtraKey));
                }
                if( urlQueryParams.get(OAuth2RefreshTokenExtraKey) != null ) {
                    this.resultIntent.putExtra(OAuth2RefreshTokenExtraKey, urlQueryParams.get(OAuth2RefreshTokenExtraKey));
                }
            } else if ( urlQueryParams.get(OAuth2AccessCodeExtraKey) != null ) {
                String authorizationCode = urlQueryParams.get(OAuth2AccessCodeExtraKey);
                resultIntent.putExtra(OAuth2AccessCodeExtraKey, authorizationCode);

                OAuth2WebViewActivity.this.setResult(RESULT_OK,resultIntent);

                AuthorizationCodeTokenRequest codeTokenRequest = new AuthorizationCodeTokenRequest(new NetHttpTransport(),new JacksonFactory(),new GenericUrl(this.accessTokenURL),authorizationCode);
                codeTokenRequest.setRedirectUri(this.redirectURL);
                if( clientId != null ) {
                    codeTokenRequest.set("client_id", clientId);
                }
                if( clientSecret != null ) {
                    codeTokenRequest.set("client_secret", clientSecret);
                }
                HttpResponse response  = codeTokenRequest.executeUnparsed();

                InputStream in = response.getContent();
                InputStreamReader is = new InputStreamReader(in);
                StringBuilder sb=new StringBuilder();
                BufferedReader br = new BufferedReader(is);
                String read = br.readLine();

                while(read != null) {
                    sb.append(read);
                    read =br.readLine();
                }

                String accessTokenStringData = sb.toString();
                Map<String,String> queryParams = this.extractQueryParams(accessTokenStringData);
                if( queryParams.get(OAuth2AccessTokenExtraKey) != null ) {
                    this.resultIntent.putExtra(OAuth2AccessTokenExtraKey,queryParams.get(OAuth2AccessTokenExtraKey));
                }
                if( queryParams.get(OAuth2ExpiresInExtraKey) != null ) {
                    this.resultIntent.putExtra(OAuth2ExpiresInExtraKey, queryParams.get(OAuth2ExpiresInExtraKey));
                }
                if( queryParams.get(OAuth2RefreshTokenExtraKey) != null ) {
                    this.resultIntent.putExtra(OAuth2RefreshTokenExtraKey, queryParams.get(OAuth2RefreshTokenExtraKey));
                }
            } else if (urlQueryParams.get(OAuth2ErrorExtraKey) != null) {
                this.resultIntent.putExtra(OAuth2ErrorExtraKey,urlQueryParams.get(OAuth2ErrorExtraKey));
                OAuth2WebViewActivity.this.setResult(RESULT_OK, resultIntent);
            }
        } catch (Exception e) {
            this.resultIntent.putExtra("error",e.getLocalizedMessage());
            e.printStackTrace();
        }
    }
    return null;
}