Search in sources :

Example 1 with IdToken

use of com.google.api.client.auth.openidconnect.IdToken in project google-oauth-java-client by googleapis.

the class CustomTokenRequestTest method testSetResponseClass.

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"));
}
Also used : IdToken(com.google.api.client.auth.openidconnect.IdToken) IdTokenResponse(com.google.api.client.auth.openidconnect.IdTokenResponse) IdTokenResponse(com.google.api.client.auth.openidconnect.IdTokenResponse)

Example 2 with IdToken

use of com.google.api.client.auth.openidconnect.IdToken in project sigstore-maven-plugin by sigstore.

the class Sign method getIDToken.

/**
 * Obtains an OpenID Connect Identity Token from the OIDC provider specified in <code>oidcAuthURL</code>
 *
 * @param  expectedEmailAddress The email address we expected to see in the identity token
 * @return      the ID token String (in JWS format)
 * @throws MojoExecutionException If any exception happened during the OIDC authentication flow
 */
public String getIDToken(String expectedEmailAddress) throws MojoExecutionException {
    try {
        JsonFactory jsonFactory = new GsonFactory();
        HttpTransport httpTransport = getHttpTransport();
        DataStoreFactory memStoreFactory = new MemoryDataStoreFactory();
        final String idTokenKey = "id_token";
        if (!oidcDeviceCodeFlow) {
            AuthorizationCodeFlow.Builder flowBuilder = new AuthorizationCodeFlow.Builder(BearerToken.authorizationHeaderAccessMethod(), httpTransport, jsonFactory, new GenericUrl(oidcTokenURL.toString()), new ClientParametersAuthentication(oidcClientID, null), oidcClientID, oidcAuthURL.toString()).enablePKCE().setScopes(List.of("openid", "email")).setCredentialCreatedListener(new AuthorizationCodeFlow.CredentialCreatedListener() {

                @Override
                public void onCredentialCreated(Credential credential, TokenResponse tokenResponse) throws IOException {
                    memStoreFactory.getDataStore("user").set(idTokenKey, tokenResponse.get(idTokenKey).toString());
                }
            });
            AuthorizationCodeInstalledApp app = new AuthorizationCodeInstalledApp(flowBuilder.build(), new LocalServerReceiver());
            app.authorize("user");
        }
        // TODO: add device code flow support
        String idTokenString = (String) memStoreFactory.getDataStore("user").get(idTokenKey);
        IdTokenVerifier idTokenVerifier = new IdTokenVerifier();
        IdToken parsedIdToken = IdToken.parse(jsonFactory, idTokenString);
        if (!idTokenVerifier.verify(parsedIdToken)) {
            throw new InvalidObjectException("id token could not be verified");
        }
        String emailFromIDToken = (String) parsedIdToken.getPayload().get("email");
        Boolean emailVerified = (Boolean) parsedIdToken.getPayload().get("email_verified");
        if (expectedEmailAddress != null && !emailFromIDToken.equals(expectedEmailAddress)) {
            throw new InvalidObjectException(String.format("email in ID token '%s' does not match address specified to plugin '%s'", emailFromIDToken, emailAddress));
        } else if (Boolean.FALSE.equals(emailVerified)) {
            throw new InvalidObjectException(String.format("identity provider '%s' reports email address '%s' has not been verified", parsedIdToken.getPayload().getIssuer(), emailAddress));
        }
        this.emailAddress = emailFromIDToken;
        return idTokenString;
    } catch (Exception e) {
        throw new MojoExecutionException("Error signing email address:", e);
    }
}
Also used : IdToken(com.google.api.client.auth.openidconnect.IdToken) Credential(com.google.api.client.auth.oauth2.Credential) GsonFactory(com.google.api.client.json.gson.GsonFactory) MojoExecutionException(org.apache.maven.plugin.MojoExecutionException) JsonFactory(com.google.api.client.json.JsonFactory) AuthorizationCodeInstalledApp(com.google.api.client.extensions.java6.auth.oauth2.AuthorizationCodeInstalledApp) GenericUrl(com.google.api.client.http.GenericUrl) IOException(java.io.IOException) LocalServerReceiver(com.google.api.client.extensions.jetty.auth.oauth2.LocalServerReceiver) InvalidObjectException(java.io.InvalidObjectException) NoSuchAlgorithmException(java.security.NoSuchAlgorithmException) IOException(java.io.IOException) MojoExecutionException(org.apache.maven.plugin.MojoExecutionException) AuthorizationCodeFlow(com.google.api.client.auth.oauth2.AuthorizationCodeFlow) HttpTransport(com.google.api.client.http.HttpTransport) ApacheHttpTransport(com.google.api.client.http.apache.v2.ApacheHttpTransport) ClientParametersAuthentication(com.google.api.client.auth.oauth2.ClientParametersAuthentication) MemoryDataStoreFactory(com.google.api.client.util.store.MemoryDataStoreFactory) TokenResponse(com.google.api.client.auth.oauth2.TokenResponse) InvalidObjectException(java.io.InvalidObjectException) MemoryDataStoreFactory(com.google.api.client.util.store.MemoryDataStoreFactory) DataStoreFactory(com.google.api.client.util.store.DataStoreFactory) IdTokenVerifier(com.google.api.client.auth.openidconnect.IdTokenVerifier)

Example 3 with IdToken

use of com.google.api.client.auth.openidconnect.IdToken in project idempiere by idempiere.

the class MAuthorizationCredential method processToken.

/**
 * Create or Update an Account based on the token received
 * @param ctx
 * @param code
 * @param paramScope
 * @param pilog       MPInstanceLog to set the log message and record_ID, it is not saved, the caller must save it
 * @return String message indicating success
 */
public String processToken(Properties ctx, String code, String paramScope, MPInstanceLog pilog) {
    String msg = null;
    try {
        String clientId = getAuthorizationClientId();
        String clientSecret = getAuthorizationClientSecret();
        Timestamp ts = new Timestamp(System.currentTimeMillis());
        MAuthorizationProvider ap = new MAuthorizationProvider(ctx, getAD_AuthorizationProvider_ID(), get_TrxName());
        AuthorizationCodeTokenRequest request = new AuthorizationCodeTokenRequest(new NetHttpTransport(), GsonFactory.getDefaultInstance(), new GenericUrl(ap.getTokenEndpoint()), code);
        request.setRedirectUri(getAuthorizationRedirectURL());
        request.setClientAuthentication(new ClientParametersAuthentication(clientId, clientSecret));
        TokenResponse tokenResponse = request.execute();
        Object id_token = tokenResponse.get("id_token");
        String email = null;
        if (id_token != null && id_token instanceof String) {
            IdToken idtoken = IdToken.parse(tokenResponse.getFactory(), (String) tokenResponse.get("id_token"));
            email = (String) idtoken.getPayload().get("email");
        }
        if (email == null) {
            msg = Msg.parseTranslation(ctx, "@Error@ @OAuthProcessToken_CouldNotGetEMail@");
            return msg;
        }
        boolean newAccount = false;
        MAuthorizationAccount account = null;
        Query query = new Query(ctx, MAuthorizationAccount.Table_Name, "AD_Client_ID=? AND AD_User_ID=? AND EMail=? AND AD_AuthorizationCredential_ID=?", get_TrxName());
        query.setParameters(Env.getAD_Client_ID(ctx), Env.getAD_User_ID(ctx), email, getAD_AuthorizationCredential_ID());
        account = query.setOnlyActiveRecords(true).first();
        if (account == null) {
            account = new MAuthorizationAccount(ctx, 0, get_TrxName());
            account.setEMail(email);
            account.setAD_AuthorizationCredential_ID(getAD_AuthorizationCredential_ID());
            account.setAD_User_ID(Env.getAD_User_ID(ctx));
            newAccount = true;
        }
        account.setAD_AuthorizationScopes(paramScope);
        account.setAccessToken(tokenResponse.getAccessToken());
        account.setAccessTokenTimestamp(ts);
        account.setExpireInSeconds(BigDecimal.valueOf(tokenResponse.getExpiresInSeconds()));
        account.setIsAuthorized(true);
        account.setIsActive(true);
        if (tokenResponse.getRefreshToken() == null && account.getRefreshToken() == null) {
            String refreshToken = account.findRefreshToken();
            if (refreshToken != null) {
                account.setRefreshToken(refreshToken);
            }
        }
        if (tokenResponse.getRefreshToken() == null && account.getRefreshToken() == null) {
            // revoke access and ask for retry
            MAuthorizationProvider provider = new MAuthorizationProvider(ctx, getAD_AuthorizationProvider_ID(), get_TrxName());
            String revokeEndPoint = provider.getRevokeEndpoint();
            if (revokeEndPoint != null) {
                HttpRequestFactory factory = new NetHttpTransport().createRequestFactory();
                GenericUrl url = new GenericUrl(revokeEndPoint + "?token=" + account.getAccessToken());
                HttpRequest revokeRequest = factory.buildGetRequest(url);
                revokeRequest.execute();
            }
            msg = Msg.parseTranslation(ctx, "@Error@ @OAuthProcessToken_NoRefreshToken@");
            return msg;
        }
        if (tokenResponse.getRefreshToken() != null) {
            account.setRefreshToken(tokenResponse.getRefreshToken());
        }
        account.saveEx();
        if (pilog != null) {
            String logmsg = Msg.parseTranslation(ctx, (newAccount ? "@Created@" : "@Updated@") + " @AD_AuthorizationAccount_ID@ for ") + account.getEMail();
            pilog.setP_Msg(logmsg);
            pilog.setRecord_ID(account.getAD_AuthorizationAccount_ID());
        }
        account.syncOthers();
        if (newAccount)
            msg = Msg.getMsg(ctx, "Authorization_Access_OK", new Object[] { account.getEMail(), paramScope });
        else
            msg = Msg.getMsg(ctx, "Authorization_Access_Previous", new Object[] { account.getEMail(), paramScope });
    } catch (Exception ex) {
        ex.printStackTrace();
        msg = Msg.getMsg(ctx, "Error") + ex.getLocalizedMessage();
        return msg;
    }
    return msg;
}
Also used : HttpRequest(com.google.api.client.http.HttpRequest) IdToken(com.google.api.client.auth.openidconnect.IdToken) HttpRequestFactory(com.google.api.client.http.HttpRequestFactory) GenericUrl(com.google.api.client.http.GenericUrl) Timestamp(java.sql.Timestamp) AdempiereException(org.adempiere.exceptions.AdempiereException) ClientParametersAuthentication(com.google.api.client.auth.oauth2.ClientParametersAuthentication) TokenResponse(com.google.api.client.auth.oauth2.TokenResponse) AuthorizationCodeTokenRequest(com.google.api.client.auth.oauth2.AuthorizationCodeTokenRequest) NetHttpTransport(com.google.api.client.http.javanet.NetHttpTransport)

Aggregations

IdToken (com.google.api.client.auth.openidconnect.IdToken)3 ClientParametersAuthentication (com.google.api.client.auth.oauth2.ClientParametersAuthentication)2 TokenResponse (com.google.api.client.auth.oauth2.TokenResponse)2 GenericUrl (com.google.api.client.http.GenericUrl)2 AuthorizationCodeFlow (com.google.api.client.auth.oauth2.AuthorizationCodeFlow)1 AuthorizationCodeTokenRequest (com.google.api.client.auth.oauth2.AuthorizationCodeTokenRequest)1 Credential (com.google.api.client.auth.oauth2.Credential)1 IdTokenResponse (com.google.api.client.auth.openidconnect.IdTokenResponse)1 IdTokenVerifier (com.google.api.client.auth.openidconnect.IdTokenVerifier)1 AuthorizationCodeInstalledApp (com.google.api.client.extensions.java6.auth.oauth2.AuthorizationCodeInstalledApp)1 LocalServerReceiver (com.google.api.client.extensions.jetty.auth.oauth2.LocalServerReceiver)1 HttpRequest (com.google.api.client.http.HttpRequest)1 HttpRequestFactory (com.google.api.client.http.HttpRequestFactory)1 HttpTransport (com.google.api.client.http.HttpTransport)1 ApacheHttpTransport (com.google.api.client.http.apache.v2.ApacheHttpTransport)1 NetHttpTransport (com.google.api.client.http.javanet.NetHttpTransport)1 JsonFactory (com.google.api.client.json.JsonFactory)1 GsonFactory (com.google.api.client.json.gson.GsonFactory)1 DataStoreFactory (com.google.api.client.util.store.DataStoreFactory)1 MemoryDataStoreFactory (com.google.api.client.util.store.MemoryDataStoreFactory)1