com.nimbusds.oauth2.sdk.AuthorizationCode Java Examples

The following examples show how to use com.nimbusds.oauth2.sdk.AuthorizationCode. 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: OpenIdClient.java    From timbuctoo with GNU General Public License v3.0 6 votes vote down vote up
public Optional<Tokens> getUserTokens(String code) throws IOException, ParseException {
  final ClientAuthentication basicAuth = new ClientSecretBasic(new ClientID(clientId), new Secret(clientSecret));
  final URI redirectUri = fromUri(redirectUrl).build();
  final AuthorizationCodeGrant authzGrant = new AuthorizationCodeGrant(new AuthorizationCode(code), redirectUri);
  final TokenRequest tokenRequest = new TokenRequest(getTokenUrl(discoveryUrl), basicAuth, authzGrant);
  final TokenResponse response = OIDCTokenResponseParser.parse(tokenRequest.toHTTPRequest().send());

  if (response.indicatesSuccess()) {
    final Tokens tokens = response.toSuccessResponse().getTokens();

    // TODO check if the id is not fake
    return Optional.of(tokens);
  } else {
    LOG.error("Could not retrieve client token: {}", response.toErrorResponse().getErrorObject());
    return Optional.empty();
  }
}
 
Example #2
Source File: AzureAdAuthenticator.java    From fess with Apache License 2.0 6 votes vote down vote up
protected AuthenticationResult getAccessToken(final AuthorizationCode authorizationCode, final String currentUri) {
    final String authority = getAuthority() + getTenant() + "/";
    final String authCode = authorizationCode.getValue();
    if (logger.isDebugEnabled()) {
        logger.debug("authCode: {}, authority: {}, uri: {}", authCode, authority, currentUri);
    }
    final ClientCredential credential = new ClientCredential(getClientId(), getClientSecret());
    ExecutorService service = null;
    try {
        service = Executors.newFixedThreadPool(1);
        final AuthenticationContext context = new AuthenticationContext(authority, true, service);
        final Future<AuthenticationResult> future =
                context.acquireTokenByAuthorizationCode(authCode, new URI(currentUri), credential, null);
        final AuthenticationResult result = future.get(acquisitionTimeout, TimeUnit.MILLISECONDS);
        if (result == null) {
            throw new SsoLoginException("authentication result was null");
        }
        return result;
    } catch (final Exception e) {
        throw new SsoLoginException("Failed to get a token.", e);
    } finally {
        if (service != null) {
            service.shutdown();
        }
    }
}
 
Example #3
Source File: OidcClient.java    From sonar-auth-oidc with Apache License 2.0 6 votes vote down vote up
public AuthorizationCode getAuthorizationCode(HttpServletRequest callbackRequest) {
  LOGGER.debug("Retrieving authorization code from callback request's query parameters: {}",
      callbackRequest.getQueryString());
  AuthenticationResponse authResponse = null;
  try {
    HTTPRequest request = ServletUtils.createHTTPRequest(callbackRequest);
    authResponse = AuthenticationResponseParser.parse(request.getURL().toURI(), request.getQueryParameters());
  } catch (ParseException | URISyntaxException | IOException e) {
    throw new IllegalStateException("Error while parsing callback request", e);
  }
  if (authResponse instanceof AuthenticationErrorResponse) {
    ErrorObject error = ((AuthenticationErrorResponse) authResponse).getErrorObject();
    throw new IllegalStateException("Authentication request failed: " + error.toJSONObject());
  }
  AuthorizationCode authorizationCode = ((AuthenticationSuccessResponse) authResponse).getAuthorizationCode();
  LOGGER.debug("Authorization code: {}", authorizationCode.getValue());
  return authorizationCode;
}
 
Example #4
Source File: OidcClientTest.java    From sonar-auth-oidc with Apache License 2.0 6 votes vote down vote up
private OidcClient newSpyOidcClient() {
  setSettings(true);
  OidcClient client = createSpyOidcClient();
  try {
    OIDCTokenResponse tokenResponse = OIDCTokenResponse.parse(JSONObjectUtils.parse(
        "{\"access_token\":\"eyJhbGciOiJSUzI1NiIsInR5cCIgOiAiSldUIiwia2lkIiA6ICJ3djY4UzUybDZTWVUxNGFfd0N3VElJT01WV1d1RXVXUFNBcERjYXo5Rnd3In0.eyJqdGkiOiIzMWNkOWM3YS05YTM3LTRiOTktOTViMC1jNzJlNGYzNGY4ODEiLCJleHAiOjE1MTQzMDcwNTQsIm5iZiI6MCwiaWF0IjoxNTE0MzA2NzU0LCJpc3MiOiJodHRwOi8vbWFjYm9vay1wcm8uZnJpdHouYm94OjgwODAvYXV0aC9yZWFsbXMvc3NvIiwiYXVkIjoic29uYXJxdWJlIiwic3ViIjoiYWZhYmE1OTItYWM4NS00Y2YxLThlYzYtMDA1OGQxN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JqdGkiOiIwYzdkNDQ0Yy1iM2MxLTQzM2YtODQ1OC1iYzRlYmQ4YjM4MGIiLCJleHAiOjE1MTQzMDcwNTQsIm5iZiI6MCwiaWF0IjoxNTE0MzA2NzU0LCJpc3MiOiJodHRwOi8vbWFjYm9vay1wcm8uZnJpdHouYm94OjgwODAvYXV0aC9yZWFsbXMvc3NvIiwiYXVkIjoic29uYXJxdWJlIiwic3ViIjoiYWZhYmE1OTItYWM4NS00Y2YxLThlYzYtMDA1OGQxNTdmODgyIiwidHlwIjoiSUQiLCJhenAiOiJzb25hcnF1YmUiLCJhdXRoX3RpbWUiOjE1MTQzMDY3NTQsInNlc3Npb25fc3RhdGUiOiJhYTY3Y2M2OS03YTA2LTQ3ZDEtYmEwMC02OTY0NmU2MGI4YmUiLCJhY3IiOiIxIiwibmFtZSI6IkpvaG4gRG9vIiwicHJlZmVycmVkX3VzZXJuYW1lIjoiam9obi5kb28iLCJnaXZlbl9uYW1lIjoiSm9obiIsImZhbWlseV9uYW1lIjoiRG9vIiwiZW1haWwiOiJqb2huLmRvb0BhY21lLmNvbSJ9.UwqM6TGPrpMpK70FKxX9ZQWyUySjx7fxeV5IAT2PtzTH4xZKLJQbQmb4uD9z7o5azK5fgYc9xQfJKQX2y2euz-mtSdjueqkPAY-djQEc2kyvb-4Nd9Qc4Uiy19aAuooNdM-pAiYhfvyQQiGMRe3z68sq45mgfDpKMBcV-5bOJNafQ8tLLEonzT37-1GMfuAMv7ppx4HmdUDQccZ0D4nBqmeFRPcA3BghPZJ6eThR_mRsuYW1yZDg5tMle2cZe80mnIZSTW349cPwJFfmQDNT7XQBHHTCa6pYsBoqs2KYadOnbMSPCXZ-agd0DzffgtujsBvrUWV8tXSZ7axY34xMQQ\","
            + "\"token_type\":\"Bearer\",\"expires_in\":300}"));
    doReturn(tokenResponse).when(client).getTokenResponse(new AuthorizationCode(VALID_CODE), CALLBACK_URL);

    TokenErrorResponse errorTokenResponse = TokenErrorResponse
        .parse(JSONObjectUtils.parse("{\"error\":\"invalid_request\"}"));
    doReturn(errorTokenResponse).when(client).getTokenResponse(new AuthorizationCode(INVALID_CODE), CALLBACK_URL);

    UserInfo userInfo = new UserInfo(tokenResponse.getOIDCTokens().getIDToken().getJWTClaimsSet());
    doReturn(userInfo).when(client).getUserInfo(new AuthorizationCode(VALID_CODE), CALLBACK_URL);
  } catch (ParseException | java.text.ParseException e) {
    // ignore
  }
  return client;
}
 
Example #5
Source File: OidcClientTest.java    From sonar-auth-oidc with Apache License 2.0 5 votes vote down vote up
@Test
public void getUserInfoFromUserInfoEndpoint() {
  OidcClient underTest = newSpyOidcClientWithoutProfileInformation();
  UserInfo userInfo = underTest.getUserInfo(new AuthorizationCode(VALID_CODE), CALLBACK_URL);
  assertEquals("e65c9607-fd4e-4bcd-97b1-ca057616590e", userInfo.getSubject().getValue());
  assertEquals("john.doo", userInfo.getPreferredUsername());
  assertEquals("John Doo", userInfo.getName());
  assertEquals("http://localhost:8080/hub/users/e65c9607-fd4e-4bcd-97b1-ca057616590e",
      userInfo.getProfile().toString());
  assertEquals("[email protected]", userInfo.getEmailAddress());
  assertTrue(userInfo.getEmailVerified());
}
 
Example #6
Source File: OidcClientTest.java    From sonar-auth-oidc with Apache License 2.0 5 votes vote down vote up
private OidcClient newSpyOidcClientWithoutProfileInformation() {
  setSettings(true);
  OidcClient client = createSpyOidcClient();
  try {
    OIDCTokenResponse tokenResponse = OIDCTokenResponse.parse(JSONObjectUtils.parse(
        "{\"id_token\":\"eyJhbGciOiJSUzI1NiIsImtpZCI6IjEifQ.eyJzdWIiOiJlNjVjOTYwNy1mZDRlLTRiY2QtOTdiMS1jYTA1NzYxNjU5MGUiLCJpc3MiOiJodHRwOi8vbG9jYWxob3N0OjgwODAvaHViIiwiYXVkIjpbIjYwZGNhY2FmLThhOTQtNDE3Ny1iMmYyLTEzNDg0NjNmODhjZSJdLCJleHAiOjEuNTIzNTcyMTY3NTYxRTksImlhdCI6MS41MTU3OTYxNjc1OTdFOSwiYXV0aF90aW1lIjoxLjUxNTc5NjE2NzU2MUU5fQ.o_h3f6QK--p1Ru8pUquoLpvB1vdBCorUfdq_I8J_yBbjyPS4LUP9-e_xkXtql6yOSh9AewNUb7PSKnJOq-TlMMMlOr-Or676i1wT0hGQb2aKnzzFu7VYQOep8_6t-AQSXRhckaR5NIJnF6oxFWdTwhizcenO_Osf12R-PQOyQsA\","
            + "\"access_token\":\"1515799767598.60dcacaf-8a94-4177-b2f2-1348463f88ce.e65c9607-fd4e-4bcd-97b1-ca057616590e.0-0-0-0-0;1.MCwCFEjmjjDDL1yAQ+jYA+VxgYNNNr4hAhR66eAgXKfs6kOJehOALtRqw5wq9Q==\","
            + "\"token_type\":\"Bearer\"," + "\"expires_in\":3600," + "\"scope\":\"0-0-0-0-0\"}"));
    doReturn(tokenResponse).when(client).getTokenResponse(new AuthorizationCode(VALID_CODE), CALLBACK_URL);

    OIDCTokenResponse invalidTokenResponse = OIDCTokenResponse.parse(JSONObjectUtils.parse(
        "{\"id_token\":\"eyJhbGciOiJSUzI1NiIsImtpZCI6IjEifQ.eyJzdWIiOiJlNjVjOTYwNy1mZDRlLTRiY2QtOTdiMS1jYTA1NzYxNjU5MGUiLCJpc3MiOiJodHRwOi8vbG9jYWxob3N0OjgwODAvaHViIiwiYXVkIjpbIjYwZGNhY2FmLThhOTQtNDE3Ny1iMmYyLTEzNDg0NjNmODhjZSJdLCJleHAiOjEuNTIzNTcyMTY3NTYxRTksImlhdCI6MS41MTU3OTYxNjc1OTdFOSwiYXV0aF90aW1lIjoxLjUxNTc5NjE2NzU2MUU5fQ.o_h3f6QK--p1Ru8pUquoLpvB1vdBCorUfdq_I8J_yBbjyPS4LUP9-e_xkXtql6yOSh9AewNUb7PSKnJOq-TlMMMlOr-Or676i1wT0hGQb2aKnzzFu7VYQOep8_6t-AQSXRhckaR5NIJnF6oxFWdTwhizcenO_Osf12R-PQOyQsA\","
            + "\"access_token\":\"invalid\"," + "\"token_type\":\"Bearer\"," + "\"expires_in\":3600,"
            + "\"scope\":\"0-0-0-0-0\"}"));
    doReturn(invalidTokenResponse).when(client).getTokenResponse(new AuthorizationCode(INVALID_CODE), CALLBACK_URL);

    UserInfoSuccessResponse userInfoResponse = new UserInfoSuccessResponse(
        new UserInfo(JSONObjectUtils.parse("{\"sub\":\"e65c9607-fd4e-4bcd-97b1-ca057616590e\","
            + "\"name\":\"John Doo\",\"preferred_username\":\"john.doo\","
            + "\"profile\":\"http://localhost:8080/hub/users/e65c9607-fd4e-4bcd-97b1-ca057616590e\","
            + "\"email\":\"[email protected]\",\"email_verified\":true}")));
    doReturn(userInfoResponse).when(client).getUserInfoResponse(tokenResponse.getOIDCTokens().getBearerAccessToken());

    doCallRealMethod().when(client).getUserInfo(new AuthorizationCode(VALID_CODE), CALLBACK_URL);
  } catch (ParseException | java.text.ParseException e) {
    // ignore
  }
  return client;
}
 
Example #7
Source File: OidcClientTest.java    From sonar-auth-oidc with Apache License 2.0 5 votes vote down vote up
@Test
public void userInfoErrorResponseWithoutErrorCode() {
  OidcClient underTest = newSpyOidcClientWithoutProfileInformation();
  UserInfoErrorResponse userInfoResponse = new UserInfoErrorResponse(new ErrorObject(null));
  doReturn(userInfoResponse).when(underTest).getUserInfoResponse(INVALID_BEARER_ACCESS_TOKEN);
  try {
    underTest.getUserInfo(new AuthorizationCode(INVALID_CODE), CALLBACK_URL);
    failBecauseExceptionWasNotThrown(IllegalStateException.class);
  } catch (IllegalStateException e) {
    assertEquals("UserInfo request failed: No error code returned "
        + "(identity provider not reachable - check network proxy setting 'http.nonProxyHosts' in 'sonar.properties')",
        e.getMessage());
  }
}
 
Example #8
Source File: OidcClientTest.java    From sonar-auth-oidc with Apache License 2.0 5 votes vote down vote up
@Test
public void userInfoErrorResponse() {
  OidcClient underTest = newSpyOidcClientWithoutProfileInformation();
  UserInfoErrorResponse userInfoResponse = new UserInfoErrorResponse(new ErrorObject("some_error"));
  doReturn(userInfoResponse).when(underTest).getUserInfoResponse(INVALID_BEARER_ACCESS_TOKEN);
  try {
    underTest.getUserInfo(new AuthorizationCode(INVALID_CODE), CALLBACK_URL);
    failBecauseExceptionWasNotThrown(IllegalStateException.class);
  } catch (IllegalStateException e) {
    assertEquals("UserInfo request failed: {\"error\":\"some_error\"}", e.getMessage());
  }
}
 
Example #9
Source File: AuthHelper.java    From ms-identity-java-webapp with MIT License 5 votes vote down vote up
IAuthenticationResult getAuthResultByAuthCode(
        HttpServletRequest httpServletRequest,
        AuthorizationCode authorizationCode,
        String currentUri, Set<String> scopes) throws Throwable {

    IAuthenticationResult result;
    ConfidentialClientApplication app;
    try {
        app = createClientApplication();

        String authCode = authorizationCode.getValue();
        AuthorizationCodeParameters parameters = AuthorizationCodeParameters.builder(
                authCode,
                new URI(currentUri))
                .scopes(scopes)
                .build();

        Future<IAuthenticationResult> future = app.acquireToken(parameters);

        result = future.get();
    } catch (ExecutionException e) {
        throw e.getCause();
    }

    if (result == null) {
        throw new ServiceUnavailableException("authentication result was null");
    }

    storeTokenCacheInSession(httpServletRequest, app.tokenCache().serialize());

    return result;
}
 
Example #10
Source File: OidcClientTest.java    From sonar-auth-oidc with Apache License 2.0 5 votes vote down vote up
@Test
public void invalidTokenRequestUri() {
  OidcClient underTest = newSpyOidcClient();
  try {
    underTest.getUserInfo(new AuthorizationCode(VALID_CODE), INVALID_URL);
    failBecauseExceptionWasNotThrown(URISyntaxException.class);
  } catch (IllegalStateException e) {
    assertEquals("Retrieving access token failed", e.getMessage());
  }
}
 
Example #11
Source File: OidcClientTest.java    From sonar-auth-oidc with Apache License 2.0 5 votes vote down vote up
@Test
public void tokenErrorResponseWithoutErrorCode() {
  OidcClient underTest = newSpyOidcClient();
  TokenErrorResponse errorTokenResponse = new TokenErrorResponse(new ErrorObject(null));
  doReturn(errorTokenResponse).when(underTest).getTokenResponse(new AuthorizationCode("no_error"), CALLBACK_URL);
  try {
    underTest.getUserInfo(new AuthorizationCode("no_error"), CALLBACK_URL);
    failBecauseExceptionWasNotThrown(IllegalStateException.class);
  } catch (IllegalStateException e) {
    assertEquals("Token request failed: No error code returned (identity provider not reachable - "
        + "check network proxy setting 'http.nonProxyHosts' in 'sonar.properties')", e.getMessage());
  }
}
 
Example #12
Source File: OidcClientTest.java    From sonar-auth-oidc with Apache License 2.0 5 votes vote down vote up
@Test
public void tokenErrorResponse() {
  OidcClient underTest = newSpyOidcClient();
  try {
    underTest.getUserInfo(new AuthorizationCode(INVALID_CODE), CALLBACK_URL);
    failBecauseExceptionWasNotThrown(IllegalStateException.class);
  } catch (IllegalStateException e) {
    assertEquals("Token request failed: {\"error\":\"invalid_request\"}", e.getMessage());
  }
}
 
Example #13
Source File: OidcClientTest.java    From sonar-auth-oidc with Apache License 2.0 5 votes vote down vote up
@Test
public void getUserInfo() {
  OidcClient underTest = newSpyOidcClient();
  UserInfo userInfo = underTest.getUserInfo(new AuthorizationCode(VALID_CODE), CALLBACK_URL);
  assertEquals("afaba592-ac85-4cf1-8ec6-0058d157f882", userInfo.getSubject().getValue());
  assertEquals("john.doo", userInfo.getPreferredUsername());
  assertEquals("John Doo", userInfo.getName());
  assertEquals("John", userInfo.getGivenName());
  assertEquals("Doo", userInfo.getFamilyName());
  assertEquals("[email protected]", userInfo.getEmailAddress());
}
 
Example #14
Source File: OidcClientTest.java    From sonar-auth-oidc with Apache License 2.0 5 votes vote down vote up
@Test
public void getAuthorizationCode() {
  OidcClient underTest = newSpyOidcClient();
  HttpServletRequest request = mock(HttpServletRequest.class);
  when(request.getMethod()).thenReturn("GET");
  when(request.getHeaderNames()).thenReturn(Collections.emptyEnumeration());
  when(request.getQueryString()).thenReturn("state=" + STATE + "&code=" + VALID_CODE);

  AuthorizationCode code = underTest.getAuthorizationCode(request);
  assertEquals("invalid access code", VALID_CODE, code.getValue());
}
 
Example #15
Source File: OidcIdentityProvider.java    From sonar-auth-oidc with Apache License 2.0 5 votes vote down vote up
@Override
public void callback(CallbackContext context) {
  LOGGER.trace("Handling authentication response");
  context.verifyCsrfState();
  AuthorizationCode authorizationCode = client.getAuthorizationCode(context.getRequest());
  UserInfo userInfo = client.getUserInfo(authorizationCode, context.getCallbackUrl());
  UserIdentity userIdentity = userIdentityFactory.create(userInfo);
  LOGGER.debug("Authenticating user '{}' with groups {}", userIdentity.getProviderLogin(), userIdentity.getGroups());
  context.authenticate(userIdentity);
  LOGGER.trace("Redirecting to requested page");
  context.redirectToRequestedPage();
}
 
Example #16
Source File: AuthHelper.java    From ms-identity-java-webapp with MIT License 5 votes vote down vote up
private IAuthenticationResult getAuthResultByAuthCode(
        HttpServletRequest httpServletRequest,
        AuthorizationCode authorizationCode,
        String currentUri) throws Throwable {

    IAuthenticationResult result;
    ConfidentialClientApplication app;
    try {
        app = createClientApplication();

        String authCode = authorizationCode.getValue();
        AuthorizationCodeParameters parameters = AuthorizationCodeParameters.builder(
                authCode,
                new URI(currentUri)).
                build();

        Future<IAuthenticationResult> future = app.acquireToken(parameters);

        result = future.get();
    } catch (ExecutionException e) {
        throw e.getCause();
    }

    if (result == null) {
        throw new ServiceUnavailableException("authentication result was null");
    }

    SessionManagementHelper.storeTokenCacheInSession(httpServletRequest, app.tokenCache().serialize());

    return result;
}
 
Example #17
Source File: FacebookAuthorizationGrantTokenExchanger.java    From OAuth-2.0-Cookbook with MIT License 4 votes vote down vote up
@Override
public TokenResponseAttributes exchange(
    AuthorizationCodeAuthenticationToken authorizationCodeAuthenticationToken)
    throws OAuth2AuthenticationException {

    ClientRegistration clientRegistration = authorizationCodeAuthenticationToken.getClientRegistration();

    AuthorizationCode authorizationCode = new AuthorizationCode(
        authorizationCodeAuthenticationToken.getAuthorizationCode());
    AuthorizationGrant authorizationCodeGrant = new AuthorizationCodeGrant(
        authorizationCode, URI.create(clientRegistration.getRedirectUri()));
    URI tokenUri = URI.create(clientRegistration.getProviderDetails().getTokenUri());

    ClientID clientId = new ClientID(clientRegistration.getClientId());
    Secret clientSecret = new Secret(clientRegistration.getClientSecret());
    ClientAuthentication clientAuthentication = new ClientSecretGet(clientId, clientSecret);

    try {
        HTTPRequest httpRequest = createTokenRequest(
                clientRegistration, authorizationCodeGrant,
                tokenUri, clientAuthentication);

        TokenResponse tokenResponse = TokenResponse.parse(httpRequest.send());

        if (!tokenResponse.indicatesSuccess()) {
            OAuth2Error errorObject = new OAuth2Error("invalid_token_response");
            throw new OAuth2AuthenticationException(errorObject, "error");
        }

        return createTokenResponse((AccessTokenResponse) tokenResponse);

    } catch (MalformedURLException e) {
        throw new SerializeException(e.getMessage(), e);
    } catch (ParseException pe) {
        throw new OAuth2AuthenticationException(new OAuth2Error("invalid_token_response"), pe);
    } catch (IOException ioe) {
        throw new AuthenticationServiceException(
            "An error occurred while sending the Access Token Request: " +
            ioe.getMessage(), ioe);
    }

}
 
Example #18
Source File: OidcServiceTest.java    From nifi with Apache License 2.0 4 votes vote down vote up
private AuthorizationCodeGrant getAuthorizationCodeGrant() {
    return new AuthorizationCodeGrant(new AuthorizationCode("code"), URI.create("http://localhost:8080/nifi"));
}