com.google.api.client.auth.openidconnect.IdTokenResponse Java Examples

The following examples show how to use com.google.api.client.auth.openidconnect.IdTokenResponse. 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: CustomTokenRequestTest.java    From google-oauth-java-client with Apache License 2.0 6 votes vote down vote up
@Override
public LowLevelHttpRequest buildRequest(String method, String url) {
  return new MockLowLevelHttpRequest(url) {
    @Override
    public LowLevelHttpResponse execute() throws IOException {
      MockLowLevelHttpResponse response = new MockLowLevelHttpResponse();
      response.setContentType(Json.MEDIA_TYPE);
      IdTokenResponse json = new IdTokenResponse();
      json.setAccessToken("abc");
      json.setRefreshToken("def");
      json.setExpiresInSeconds(3600L);
      json.setIdToken(JWT_ENCODED_CONTENT);
      response.setContent(JSON_FACTORY.toString(json));
      return response;
    }
  };
}
 
Example #2
Source File: OIDCAccountManager.java    From android-java-connect-rest-sample with MIT License 5 votes vote down vote up
public void saveTokens(Account account, TokenResponse tokenResponse) throws UserNotAuthenticatedWrapperException {
    if (tokenResponse instanceof IdTokenResponse) {
        saveToken(account, Authenticator.TOKEN_TYPE_ID, ((IdTokenResponse) tokenResponse).getIdToken());
    }
    saveToken(account, Authenticator.TOKEN_TYPE_ACCESS, tokenResponse.getAccessToken());
    saveToken(account, Authenticator.TOKEN_TYPE_REFRESH, tokenResponse.getRefreshToken());
}
 
Example #3
Source File: OIDCAccountManager.java    From android-java-connect-rest-sample with MIT License 5 votes vote down vote up
public void saveTokens(String accountName, TokenResponse tokenResponse) throws UserNotAuthenticatedWrapperException {
    if (tokenResponse instanceof IdTokenResponse) {
        saveToken(accountName, Authenticator.TOKEN_TYPE_ID, ((IdTokenResponse)tokenResponse).getIdToken());
    }
    saveToken(accountName, Authenticator.TOKEN_TYPE_ACCESS, tokenResponse.getAccessToken());
    saveToken(accountName, Authenticator.TOKEN_TYPE_REFRESH, tokenResponse.getRefreshToken());
}
 
Example #4
Source File: OIDCRequestManager.java    From android-java-connect-rest-sample with MIT License 5 votes vote down vote up
/**
 *  Exchanges a Refresh Token for a new set of tokens.
 *
 *  Note that the Token Server may require you to use the `offline_access` scope to receive
 *  Refresh Tokens.
 *
 * @param refreshToken the refresh token used to request new Access Token / idToken.
 * @return the parsed successful token response received from the token endpoint
 * @throws IOException for an error response
 */
public TokenResponse refreshTokens(String refreshToken) throws IOException {

    List<String> scopesList = Arrays.asList(scopes);

    RefreshTokenRequest request = new RefreshTokenRequest(
            AndroidHttp.newCompatibleTransport(),
            new GsonFactory(),
            new GenericUrl(tokenEndpoint),
            refreshToken);

    if (!scopesList.isEmpty()) {
        request.setScopes(scopesList);
    }

    // This are extra query parameters that can be specific to an OP. For instance prompt -> consent
    // tells the Authorization Server that it SHOULD prompt the End-User for consent before returning
    // information to the Client.
    if (extras != null) {
        for (Map.Entry<String, String> queryParam : extras.entrySet()) {
            request.set(queryParam.getKey(), queryParam.getValue());
        }
    }

    // If the oidc client is confidential (needs authentication)
    if (!TextUtils.isEmpty(clientSecret)) {
        request.setClientAuthentication(new BasicAuthentication(clientId, clientSecret));
    } else {
        request.set("client_id", clientId);
    }

    if (useOAuth2) {
        if (scopesList.contains("openid")) {
            Log.w(TAG, "Using OAuth2 only request but scopes contain values for OpenId Connect");
        }
        return request.executeUnparsed().parseAs(TokenResponse.class);
    } else {
        return IdTokenResponse.execute(request);
    }
}
 
Example #5
Source File: AuthenticatorActivity.java    From android-java-connect-rest-sample with MIT License 5 votes vote down vote up
/**
 * AccountManager expects that each account has a unique name. If a new account has the same name
 * as a previously created one, it will overwrite the older account.
 *
 * Unfortunately the OIDC spec cannot guarantee[1] that any user information is unique, save for
 * the user ID (i.e. the ID Token subject) which, depending on the authentication server, is hardly
 * human-readable. This makes choosing between multiple accounts difficult.
 *
 * We'll resort to naming each account 'app_name : claim'. Usually a claim to use here could be 'name'
 * or 'email' if that user information is unique.
 *
 * [1]: http://openid.net/specs/openid-connect-basic-1_0.html#ClaimStability
 *
 * The 'app_name' will be as a fallback if the other information isn't available for some reason
 * (for instance no contact with UserInfo Endpoint, or bad claim extraction).
 *
 * @param response the TokenResponse receive from the authentication server.
 * @param claimAsPartOfAccountName claim to be use as part the account name (ex: email, name, given_name).
 *                                 If null it will use sub claim as part of the accout name.
 * @return the account name to be use when creating an account on the AccountManager
 */
private String getAccountName(TokenResponse response, String claimAsPartOfAccountName) {
    String accountName = null;
    if (response instanceof IdTokenResponse) {
        try {
            // Asserts the identity of the user, called subject in OpenID (sub)
            String accountSubject = ((IdTokenResponse)response).parseIdToken().getPayload().getSubject();

            if ((accountSubject != null && !TextUtils.isEmpty(accountSubject)) || claimAsPartOfAccountName == null){
                accountName = String.format("%1$s : %2$s", getString(R.string.app_name), accountSubject);
            } else {
                // If for a reason we can't get the subject or want to use a other claim instead,
                // we will try to get the `claimAsAccountName` using the UserInfo Endpoint
                Map userInfo = requestManager.getUserInfo(response.getAccessToken(), Map.class);
                if (userInfo.containsKey(claimAsPartOfAccountName)) {
                    String userName = (String) userInfo.get(claimAsPartOfAccountName);
                    accountName = String.format("%1$s : %2$s", getString(R.string.app_name), userName);
                }
            }
        } catch (IOException e) {
            Log.e(TAG, "Could not get needed account info using the given TokenResponse.", e);
        }
    }

    // Fallback to app's name if the other information isn't available
    if(accountName == null || TextUtils.isEmpty(accountName)) {
        accountName = getString(R.string.app_name);
    }

    return accountName.trim();
}
 
Example #6
Source File: CustomTokenRequestTest.java    From google-oauth-java-client with Apache License 2.0 5 votes vote down vote up
public void testSetResponseClass() throws IOException {
  TokenRequest request = new TokenRequest(new AccessTokenTransport(), JSON_FACTORY, AUTHORIZATION_SERVER_URL, "foo")
      .setResponseClass(IdTokenResponse.class);
  assertEquals(IdTokenResponse.class, request.getResponseClass());
  TokenResponse response = request.execute();
  assertTrue(response instanceof IdTokenResponse);
  IdTokenResponse tokenResponse = (IdTokenResponse)response;
  IdToken idToken = tokenResponse.parseIdToken();
  assertEquals("John Doe", idToken.getPayload().get("name"));
}
 
Example #7
Source File: ClientCredentialsTokenRequestTest.java    From google-oauth-java-client with Apache License 2.0 5 votes vote down vote up
public void testSetResponseClass() {
  ClientCredentialsTokenRequest request = new ClientCredentialsTokenRequest(
      TokenRequestTest.TRANSPORT, TokenRequestTest.JSON_FACTORY,
      TokenRequestTest.AUTHORIZATION_SERVER_URL)
      .setResponseClass(IdTokenResponse.class);
  assertEquals(IdTokenResponse.class, request.getResponseClass());
}
 
Example #8
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 #9
Source File: PasswordTokenRequestTest.java    From google-oauth-java-client with Apache License 2.0 4 votes vote down vote up
public void testSetResponseClass() {
  PasswordTokenRequest request = new PasswordTokenRequest(TokenRequestTest.TRANSPORT, TokenRequestTest.JSON_FACTORY,
      TokenRequestTest.AUTHORIZATION_SERVER_URL, USERNAME, PASSWORD)
      .setResponseClass(IdTokenResponse.class);
  assertEquals(IdTokenResponse.class, request.getResponseClass());
}
 
Example #10
Source File: AuthorizationCodeTokenRequestTest.java    From google-oauth-java-client with Apache License 2.0 4 votes vote down vote up
public void testSetResponseClass() {
  AuthorizationCodeTokenRequest request = new AuthorizationCodeTokenRequest(TokenRequestTest.TRANSPORT,
      TokenRequestTest.JSON_FACTORY, TokenRequestTest.AUTHORIZATION_SERVER_URL, CODE)
      .setResponseClass(IdTokenResponse.class);
  assertEquals(IdTokenResponse.class, request.getResponseClass());
}
 
Example #11
Source File: RefreshTokenRequestTest.java    From google-oauth-java-client with Apache License 2.0 4 votes vote down vote up
public void testSetResponseClass() {
  RefreshTokenRequest request = new RefreshTokenRequest(TokenRequestTest.TRANSPORT, TokenRequestTest.JSON_FACTORY,
      TokenRequestTest.AUTHORIZATION_SERVER_URL, REFRESH_TOKEN)
      .setResponseClass(IdTokenResponse.class);
  assertEquals(IdTokenResponse.class, request.getResponseClass());
}
 
Example #12
Source File: CustomTokenRequestTest.java    From google-oauth-java-client with Apache License 2.0 4 votes vote down vote up
public void testConstructorResponseClass() {
  TokenRequest request = new TokenRequest(TRANSPORT, JSON_FACTORY, AUTHORIZATION_SERVER_URL, "foo",
      IdTokenResponse.class);
  assertEquals(IdTokenResponse.class, request.getResponseClass());
}