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"));
}
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);
}
}
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;
}
Aggregations