com.nimbusds.oauth2.sdk.ParseException Java Examples

The following examples show how to use com.nimbusds.oauth2.sdk.ParseException. 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: LoginEndPoint.java    From timbuctoo with GNU General Public License v3.0 6 votes vote down vote up
@GET
@Path("/callback")
public Response callback(@QueryParam("state") UUID loginSession, @QueryParam("code") String code) {
  if (!loginSessionRedirects.containsKey(loginSession)) {
    return Response.status(417).entity("Login session unknown").build();
  }

  try {
    final Optional<Tokens> userTokens = openIdClient.getUserTokens(code);
    final String value = userTokens.isPresent() ? userTokens.get().getBearerAccessToken().getValue() : "no-token";
    final URI userUri = UriBuilder.fromUri(loginSessionRedirects.get(loginSession))
                                  .queryParam("sessionToken", value)
                                  .build();
    return Response.temporaryRedirect(userUri).build();

  } catch (IOException | ParseException e) {
    LOG.error("Retrieval of userTokes failed", e);
    return Response.serverError().build();
  }
}
 
Example #2
Source File: AbstractOidcTest.java    From sonar-auth-oidc with Apache License 2.0 6 votes vote down vote up
protected OIDCProviderMetadata getProviderMetadata(String issuerUri) {
  try {
    return OIDCProviderMetadata.parse("{\"issuer\":\"" + issuerUri + "\"," + "\"authorization_endpoint\":\""
        + issuerUri + "/protocol/openid-connect/auth" + "\"," + "\"token_endpoint\":\"" + issuerUri
        + "/protocol/openid-connect/token\"," + "\"userinfo_endpoint\":\"" + issuerUri
        + "/protocol/openid-connect/userinfo\"," + "\"jwks_uri\":\"" + issuerUri + "/protocol/openid-connect/certs\","
        + "\"grant_types_supported\":[\"authorization_code\",\"implicit\",\"refresh_token\",\"password\",\"client_credentials\"],"
        + "\"response_types_supported\":[\"code\",\"none\",\"id_token\",\"token\",\"id_token token\",\"code id_token\",\"code token\",\"code id_token token\"],"
        + "\"subject_types_supported\":[\"public\",\"pairwise\"],"
        + "\"id_token_signing_alg_values_supported\":[\"RS256\"],"
        + "\"userinfo_signing_alg_values_supported\":[\"RS256\"],"
        + "\"request_object_signing_alg_values_supported\":[\"none\",\"RS256\"],"
        + "\"response_modes_supported\":[\"query\",\"fragment\",\"form_post\"],"
        + "\"token_endpoint_auth_methods_supported\":[\"private_key_jwt\",\"client_secret_basic\",\"client_secret_post\"],"
        + "\"token_endpoint_auth_signing_alg_values_supported\":[\"RS256\"],"
        + "\"claims_supported\":[\"sub\",\"iss\",\"auth_time\",\"name\",\"given_name\",\"family_name\",\"preferred_username\",\"email\"],"
        + "\"claim_types_supported\":[\"normal\"]," + "\"claims_parameter_supported\":false,"
        + "\"scopes_supported\":[\"openid\",\"offline_access\"]," + "\"request_parameter_supported\":true,"
        + "\"request_uri_parameter_supported\":true}");
  } catch (ParseException e) {
    throw new IllegalStateException("Invalid provider metadata", e);
  }
}
 
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: GitHubConnector.java    From onedev with MIT License 6 votes vote down vote up
@Override
protected SsoAuthenticated processTokenResponse(OIDCAccessTokenResponse tokenSuccessResponse) {
	BearerAccessToken accessToken = (BearerAccessToken) tokenSuccessResponse.getAccessToken();

	try {
		UserInfoRequest userInfoRequest = new UserInfoRequest(
				new URI(getCachedProviderMetadata().getUserInfoEndpoint()), accessToken);
		HTTPResponse httpResponse = userInfoRequest.toHTTPRequest().send();

		if (httpResponse.getStatusCode() == HTTPResponse.SC_OK) {
			JSONObject json = httpResponse.getContentAsJSONObject();
			String userName = (String) json.get("login");
			String email = (String) json.get("email");
			if (StringUtils.isBlank(email))
				throw new AuthenticationException("A public email is required");
			String fullName = (String) json.get("name");
			
			return new SsoAuthenticated(userName, userName, email, fullName, null, null, this);
		} else {
			throw buildException(UserInfoErrorResponse.parse(httpResponse).getErrorObject());
		}
	} catch (SerializeException | ParseException | URISyntaxException | IOException e) {
		throw new RuntimeException(e);
	}
}
 
Example #5
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.eyJqdGkiOiIzMWNkOWM3YS05YTM3LTRiOTktOTViMC1jNzJlNGYzNGY4ODEiLCJleHAiOjE1MTQzMDcwNTQsIm5iZiI6MCwiaWF0IjoxNTE0MzA2NzU0LCJpc3MiOiJodHRwOi8vbWFjYm9vay1wcm8uZnJpdHouYm94OjgwODAvYXV0aC9yZWFsbXMvc3NvIiwiYXVkIjoic29uYXJxdWJlIiwic3ViIjoiYWZhYmE1OTItYWM4NS00Y2YxLThlYzYtMDA1OGQxNTdmODgyIiwidHlwIjoiQmVhcmVyIiwiYXpwIjoic29uYXJxdWJlIiwiYXV0aF90aW1lIjoxNTE0MzA2NzU0LCJzZXNzaW9uX3N0YXRlIjoiYWE2N2NjNjktN2EwNi00N2QxLWJhMDAtNjk2NDZlNjBiOGJlIiwiYWNyIjoiMSIsImFsb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XV0aC9yZWFsbXMvc3NvIiwiYXVkIjoic29uYXJxdWJlIiwic3ViIjoiYWZhYmE1OTItYWM4NS00Y2YxLThlYzYtMDA1OGQxNTdmODgyIiwidHlwIjoiSUQiLCJhenAiOiJzb25hcnF1YmUiLCJhdXRoX3RpbWUiOjE1MTQzMDY3NTQsInNlc3Npb25fc3RhdGUiOiJhYTY3Y2M2OS03YTA2LTQ3ZDEtYmEwMC02OTY0NmU2MGI4YmUiLCJhY3IiOiIxIiwibmFtZSI6IkpvaG4gRG9vIiwicHJlZmVycmVkX3VzZXJuYW1lIjoiam9obi5kb28iLCJnaXZlbl9uYW1lIjoiSm9obiIsImZhbWlseV9uYW1lIjoiRG9vIiwiZW1haWwiOiJqb2huLmRvb0BhY21lLmNvbSJ9.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 #6
Source File: LoginEndPoint.java    From timbuctoo with GNU General Public License v3.0 6 votes vote down vote up
@GET
@Path("/login")
public Response login(@QueryParam("redirect-uri") String clientRedirectUri) {
  LOG.info("login");
  if (StringUtils.isBlank(clientRedirectUri)) {
    return Response.status(400).entity("expected a query param redirect-uri").build();
  }

  UUID sessionId = UUID.randomUUID();
  loginSessionRedirects.put(sessionId, clientRedirectUri);

  try {
    return openIdClient.createRedirectResponse(sessionId);
  } catch (IOException | ParseException e) {
    LOG.error("Could not create redirect to OpenID Connect server", e);
    return Response.serverError().build();
  }
}
 
Example #7
Source File: OpenIdAuthorizer.java    From incubator-iotdb with Apache License 2.0 6 votes vote down vote up
private static JSONObject getProviderRSAJWK(InputStream is) throws ParseException {
    // Read all data from stream
    StringBuilder sb = new StringBuilder();
    try (Scanner scanner = new Scanner(is);) {
        while (scanner.hasNext()) {
            sb.append(scanner.next());
        }
    }

    // Parse the data as json
    String jsonString = sb.toString();
    JSONObject json = JSONObjectUtils.parse(jsonString);

    // Find the RSA signing key
    JSONArray keyList = (JSONArray) json.get("keys");
    for (Object key : keyList) {
        JSONObject k = (JSONObject) key;
        if (k.get("use").equals("sig") && k.get("kty").equals("RSA")) {
            return k;
        }
    }
    return null;
}
 
Example #8
Source File: OpenIdAuthorizer.java    From incubator-iotdb with Apache License 2.0 6 votes vote down vote up
private static JSONObject getJWKfromProvider(String providerUrl) throws URISyntaxException, IOException, ParseException, AuthException {
    if (providerUrl == null) {
        throw new IllegalArgumentException("OpenID Connect Provider URI must be given!");
    }

    // Fetch Metadata
    OIDCProviderMetadata providerMetadata = fetchMetadata(providerUrl);

    logger.debug("Using Provider Metadata: {}", providerMetadata);

    try {
        URL url = new URI(providerMetadata.getJWKSetURI().toString().replace("http", "https")).toURL();
        logger.debug("Using url {}", url);
        return getProviderRSAJWK(url.openStream());
    } catch (IOException e) {
        throw new AuthException("Unable to start the Auth", e);
    }
}
 
Example #9
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 #10
Source File: OpenIdClient.java    From timbuctoo with GNU General Public License v3.0 5 votes vote down vote up
private URI getAuthorizationUrl(String discoveryUrl) throws IOException, ParseException {
  final OIDCProviderConfigurationRequest configurationRequest =
      new OIDCProviderConfigurationRequest(new Issuer(discoveryUrl));
  final OIDCProviderMetadata metadata =
      OIDCProviderMetadata.parse(configurationRequest.toHTTPRequest().send().getContentAsJSONObject());

  return metadata.getAuthorizationEndpointURI();
}
 
Example #11
Source File: OpenIdClient.java    From timbuctoo with GNU General Public License v3.0 5 votes vote down vote up
private URI getUserInfUrl(String discoveryUrl) throws IOException, ParseException {
  final OIDCProviderConfigurationRequest configurationRequest =
      new OIDCProviderConfigurationRequest(new Issuer(discoveryUrl));
  final OIDCProviderMetadata metadata =
      OIDCProviderMetadata.parse(configurationRequest.toHTTPRequest().send().getContentAsJSONObject());

  return metadata.getUserInfoEndpointURI();
}
 
Example #12
Source File: OpenIdClient.java    From timbuctoo with GNU General Public License v3.0 5 votes vote down vote up
public Optional<UserInfo> getUserInfo(String accessToken) throws IOException, ParseException {
  final URI userInfoUri = fromUri(getUserInfUrl(discoveryUrl)).build();
  final UserInfoRequest userInfoRequest = new UserInfoRequest(userInfoUri, new BearerAccessToken(accessToken));
  final UserInfoResponse userInfoResponse = UserInfoResponse.parse(userInfoRequest.toHTTPRequest().send());

  if (userInfoResponse.indicatesSuccess()) {
    return Optional.of(userInfoResponse.toSuccessResponse().getUserInfo());
  } else {
    LOG.warn("User info request failed: {}", userInfoResponse.toErrorResponse().getErrorObject());
    return Optional.empty();
  }
}
 
Example #13
Source File: OpenIdConnectUserValidator.java    From timbuctoo with GNU General Public License v3.0 5 votes vote down vote up
@Override
public Optional<User> getUserFromAccessToken(String accessToken) throws UserValidationException {
  if (StringUtils.isBlank(accessToken)) {
    return Optional.empty();
  }

  final User local = users.getIfPresent(accessToken);
  if (local != null) {
    return Optional.of(local);
  }

  try {
    final Optional<UserInfo> userInfoOpt = openIdClient.getUserInfo(accessToken);
    if (userInfoOpt.isEmpty()) {
      return Optional.empty();
    }

    final UserInfo userInfo = userInfoOpt.get();

    final String subject = userInfo.getSubject().getValue();
    final Optional<User> user = userStore.userFor(subject);
    if (user.isPresent()) {
      user.ifPresent(value -> users.put(accessToken, value));
      return user;
    } else {
      final User newUser = userStore.saveNew(userInfo.getNickname(), subject);
      users.put(subject, newUser);
      return Optional.of(newUser);
    }

  } catch (AuthenticationUnavailableException | IOException | ParseException e) {
    throw new UserValidationException(e);
  }

}
 
Example #14
Source File: OpenIdClient.java    From timbuctoo with GNU General Public License v3.0 5 votes vote down vote up
private URI getTokenUrl(String discoveryUrl) throws IOException, ParseException {
  final OIDCProviderConfigurationRequest configurationRequest =
      new OIDCProviderConfigurationRequest(new Issuer(discoveryUrl));
  final OIDCProviderMetadata metadata =
      OIDCProviderMetadata.parse(configurationRequest.toHTTPRequest().send().getContentAsJSONObject());

  return metadata.getTokenEndpointURI();
}
 
Example #15
Source File: StandardOidcIdentityProvider.java    From nifi with Apache License 2.0 5 votes vote down vote up
private String lookupIdentityInUserInfo(final BearerAccessToken bearerAccessToken) throws IOException {
    try {
        // build the user request
        final UserInfoRequest request = new UserInfoRequest(oidcProviderMetadata.getUserInfoEndpointURI(), bearerAccessToken);
        final HTTPRequest tokenHttpRequest = request.toHTTPRequest();
        tokenHttpRequest.setConnectTimeout(oidcConnectTimeout);
        tokenHttpRequest.setReadTimeout(oidcReadTimeout);

        // send the user request
        final UserInfoResponse response = UserInfoResponse.parse(request.toHTTPRequest().send());

        // interpret the details
        if (response.indicatesSuccess()) {
            final UserInfoSuccessResponse successResponse = (UserInfoSuccessResponse) response;

            final JWTClaimsSet claimsSet;
            if (successResponse.getUserInfo() != null) {
                claimsSet = successResponse.getUserInfo().toJWTClaimsSet();
            } else {
                claimsSet = successResponse.getUserInfoJWT().getJWTClaimsSet();
            }

            final String identity = claimsSet.getStringClaim(properties.getOidcClaimIdentifyingUser());

            // ensure we were able to get the user's identity
            if (StringUtils.isBlank(identity)) {
                throw new IllegalStateException("Unable to extract identity from the UserInfo token using the claim '" +
                        properties.getOidcClaimIdentifyingUser() + "'.");
            } else {
                return identity;
            }
        } else {
            final UserInfoErrorResponse errorResponse = (UserInfoErrorResponse) response;
            throw new RuntimeException("An error occurred while invoking the UserInfo endpoint: " + errorResponse.getErrorObject().getDescription());
        }
    } catch (final ParseException | java.text.ParseException e) {
        throw new RuntimeException("Unable to parse the response from the UserInfo token request: " + e.getMessage());
    }
}
 
Example #16
Source File: StandardOidcIdentityProvider.java    From nifi with Apache License 2.0 5 votes vote down vote up
private OIDCProviderMetadata retrieveOidcProviderMetadata(final String discoveryUri) throws IOException, ParseException {
    final URL url = new URL(discoveryUri);
    final HTTPRequest httpRequest = new HTTPRequest(HTTPRequest.Method.GET, url);
    httpRequest.setConnectTimeout(oidcConnectTimeout);
    httpRequest.setReadTimeout(oidcReadTimeout);

    final HTTPResponse httpResponse = httpRequest.send();

    if (httpResponse.getStatusCode() != 200) {
        throw new IOException("Unable to download OpenId Connect Provider metadata from " + url + ": Status code " + httpResponse.getStatusCode());
    }

    final JSONObject jsonObject = httpResponse.getContentAsJSONObject();
    return OIDCProviderMetadata.parse(jsonObject);
}
 
Example #17
Source File: UserIdentityFactoryTest.java    From sonar-auth-oidc with Apache License 2.0 5 votes vote down vote up
private UserInfo newUserInfo() {
  UserInfo userInfo = null;
  try {
    return UserInfo.parse("{\"sub\":\"8f63a486-6699-4f25-beef-118dd240bef8\",\"groups\":[\"admins\",\"internal\"],"
        + "\"iss\":\"http://localhost/auth/realms/sso\",\"typ\":\"ID\",\"preferred_username\":\"jdoo\","
        + "\"given_name\":\"John\",\"aud\":\"sonarqube\",\"acr\":\"1\",\"nbf\":0,\"azp\":\"sonarqube\","
        + "\"auth_time\":1514307002,\"name\":\"John Doo\",\"exp\":1514307302,"
        + "\"session_state\":\"f57b7a35-0de4-4ac1-8d8e-a93fc8e65cb2\",\"iat\":1514307002,"
        + "\"family_name\":\"Doo\",\"jti\":\"c4a1a958-21de-47b6-b860-d0417519de00\","
        + "\"email\":\"[email protected]\"}");
  } catch (ParseException e) {
    // ignore
  }
  return userInfo;
}
 
Example #18
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 #19
Source File: OpenIdClient.java    From timbuctoo with GNU General Public License v3.0 5 votes vote down vote up
public Response createRedirectResponse(UUID sessionId) throws IOException, ParseException {
  final URI openIdServer = fromUri(getAuthorizationUrl(discoveryUrl))
                                     .queryParam("response_type", "code")
                                     .queryParam("client_id", clientId)
                                     .queryParam("redirect_uri", redirectUrl)
                                     .queryParam("scope", scope)
                                     .queryParam("state", sessionId)
                                     .build();

  return Response.status(308).location(openIdServer).build();
}
 
Example #20
Source File: OpenIdAuthorizerTest.java    From incubator-iotdb with Apache License 2.0 5 votes vote down vote up
/**
 * Can be run manually as long as the site below is active...
 */
@Test
@Ignore("We have to find a way to test this against a defined OIDC Provider")
public void fetchMetadata() throws ParseException, IOException, URISyntaxException, AuthException {
    OpenIdAuthorizer openIdAuthorizer = new OpenIdAuthorizer("https://auth.demo.pragmaticindustries.de/auth/realms/IoTDB/");
    final boolean login = openIdAuthorizer.login("eyJhbGciOiJSUzI1NiIsInR5cCIgOiAiSldUIiwia2lkIiA6ICJxMS1XbTBvelE1TzBtUUg4LVNKYXAyWmNONE1tdWNXd25RV0tZeFpKNG93In0.eyJleHAiOjE1OTAzMTcxNzYsImlhdCI6MTU5MDMxNjg3NiwianRpIjoiY2MyNWQ3MDAtYjc5NC00O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EiotqhXn70uEBWYxGXIVlm3vn3MDe3pTKA2TZy7U5xcrE7S8aGMg", "");

    assertTrue(login);
}
 
Example #21
Source File: OpenIdAuthorizerTest.java    From incubator-iotdb with Apache License 2.0 5 votes vote down vote up
@Test
public void isAdmin_noAdminClaim() throws AuthException, ParseException, IOException, URISyntaxException {
    // IOTDB_ADMIN = false
    String jwt = "eyJhbGciOiJSUzI1NiIsInR5cCIgOiAiSldUIiwia2lkIiA6ICJxMS1XbTBvelE1TzBtUUg4LVNKYXAyWmNONE1tdWNXd25RV0tZeFpKNG93In0.eyJleHAiOjE1OTAzMTcxNzYsImlhdCI6MTU5MDMxNjg3NiwianRpIjoiY2MyNWQ3MDAtYjc5NC00OTA4LTg0OGUtOTRhNzYzNmM5YzQxIiwiaXNzIjoiaHR0cDovL2F1dGguZGVtby5wcmFnbWF0aWNpbmR1c3RyaWVzLmRlL2F1dGgvcmVhbG1zL0lvVERCIiwiYXVkIjoiYWNjb3VudCIsInN1YiI6Ijg2YWRmNGIzLWE4ZTUtNDc1NC1iNWEwLTQ4OGI0OWY0M2VkMiIsInR5cCI6IkJlYXJlciIsImF6cCI6ImlvdGRiIiwic2Vzc2lvbl9zdGF0ZSI6Ijk0ZmI5NGZjLTg3YTMtNDg4Ny04M2Q3LWE5MmQ1MzMzOTMzMCIsImFjciI6IjEiLCJyZWFsbV9hY2Nlc3MiOnsicm9sZXMiOlsib2ZmbGluZV9hY2Nlc3MiLCJ1bWFfYXV0aG9yaXphdGlvbiJdfSwicmVzb3VyY2VfYWNjZXNzIjp7ImFjY291bnQiOnsicm9sZXMiOlsibWFuYWdlLWFjY291bnQiLCJtYW5hZ2UtYWNjb3VudC1saW5rcyIsInZpZXctcHJvZmlsZSJdfX0sInNjb3BlIjoiZW1haWwgcHJvZmlsZSIsImNsaWVudEhvc3QiOiIxOTIuMTY4LjE2OS4yMSIsImNsaWVudElkIjoiaW90ZGIiLCJlbWFpbF92ZXJpZmllZCI6ZmFsc2UsInByZWZlcnJlZF91c2VybmFtZSI6InNlcnZpY2UtYWNjb3VudC1pb3RkYiIsImNsaWVudEFkZHJlc3MiOiIxOTIuMTY4LjE2OS4yMSJ9.GxQFltm1PrZzVL7rR6K-GpQINFLymjqAxxoDt_DGfQEMt61M6ebmx2oHiP_3G0HDSl7sbamajQbbRrfyTg--emBC2wfhdZ7v_7O0qWC60Yd8cWZ9qxwqwTFKYb8a0Z6_TeH9-vUmsy6kp2BfJZXq3mSy0My21VGUAXRmWTbghiM4RFoHKjAZVhsPHWelFmtLftYPdOGxv-7c9iUOVh_W-nOcCNRJpYY7BEjUYN24TsjvCEwWDQWD9E29LMYfA6LNeG0KdL9Jvqad4bc2FTJn9TaCnJMCiAJ7wEEiotqhXn70uEBWYxGXIVlm3vn3MDe3pTKA2TZy7U5xcrE7S8aGMg";

    OpenIdAuthorizer authorizer = new OpenIdAuthorizer(JSONObjectUtils.parse(OPEN_ID_PUBLIC_JWK));
    boolean admin = authorizer.isAdmin(jwt);

    assertFalse(admin);
}
 
Example #22
Source File: OpenIdAuthorizerTest.java    From incubator-iotdb with Apache License 2.0 5 votes vote down vote up
@Test
public void isAdmin_hasAccess() throws AuthException, ParseException, IOException, URISyntaxException {
    // IOTDB_ADMIN = true
    String jwt = "eyJhbGciOiJSUzI1NiIsInR5cCIgOiAiSldUIiwia2lkIiA6ICJxMS1XbTBvelE1TzBtUUg4LVNKYXAyWmNONE1tdWNXd25RV0tZeFpKNG93In0.eyJleHAiOjE1OTAzMjM5MjgsImlhdCI6MTU5MDMyMzYyOCwianRpIjoiZGQ5ZDZhNmItZjgzOC00Mjk3LTg5YWUtMjdlZTgxNzVhMThiIiwiaXNzIjoiaHR0cDovL2F1dGguZGVtby5wcmFnbWF0aWNpbmR1c3RyaWVzLmRlL2F1dGgvcmVhbG1zL0lvVERCIiwiYXVkIjoiYWNjb3VudCIsInN1YiI6ImJhMzJlNDcxLWM3NzItNGIzMy04ZGE2LTZmZThhY2RhMDA3MyIsInR5cCI6IkJlYXJlciIsImF6cCI6ImlvdGRiIiwic2Vzc2lvbl9zdGF0ZSI6IjViZDRhNmM5LTBmYzItNGIxMy05Y2QxLTFhN2NjMzk3NjVhNyIsImFjciI6IjEiLCJyZWFsbV9hY2Nlc3MiOnsicm9sZXMiOlsib2ZmbGluZV9hY2Nlc3MiLCJ1bWFfYXV0aG9yaXphdGlvbiIsImlvdGRiX2FkbWluIl19LCJyZXNvdXJjZV9hY2Nlc3MiOnsiYWNjb3VudCI6eyJyb2xlcyI6WyJtYW5hZ2UtYWNjb3VudCIsIm1hbmFnZS1hY2NvdW50LWxpbmtzIiwidmlldy1wcm9maWxlIl19fSwic2NvcGUiOiJlbWFpbCBwcm9maWxlIiwiZW1haWxfdmVyaWZpZWQiOmZhbHNlLCJwcmVmZXJyZWRfdXNlcm5hbWUiOiJ1c2VyIn0.LthDI93A3jqATc_8Fm0ismqQSN62TUknD6ara6w43eao2hY6KBoMXVY1c6SXSy8hhQeHLiWpopjJE6fsG9xbaV2Gs24SJYnP4DkHvhULlBJ_PUjFy18QxzeexwYK358a99eVHG_8yu-f2kN3mJslOSrlny8oZDxeSxUi9wYNIuQFeLPmGfSISVFn_5V8lpoUAHeENmf9h8mSyEcUHGqtZfVm5zEYIbPPSBqvNei2NvKAFle6qoaJ1l13dpbw39KkOtIUF8dJ7v8XY_xgO2GXCJCvZ5YGr-q4UnA9v_GM3h3vSa5dyCuG0HXBmAujxSxywzPl5RB_QCTiYcTm7MGKLg";

    OpenIdAuthorizer authorizer = new OpenIdAuthorizer(JSONObjectUtils.parse(OPEN_ID_PUBLIC_JWK));
    boolean admin = authorizer.isAdmin(jwt);

    assertTrue(admin);
}
 
Example #23
Source File: OpenIdAuthorizerTest.java    From incubator-iotdb with Apache License 2.0 5 votes vote down vote up
@Test
public void loginWithJWT() throws AuthException, ParseException, IOException, URISyntaxException {
    String jwt = "eyJhbGciOiJSUzI1NiIsInR5cCIgOiAiSldUIiwia2lkIiA6ICJxMS1XbTBvelE1TzBtUUg4LVNK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sPHWelFmtLftYPdOGxv-7c9iUOVh_W-nOcCNRJpYY7BEjUYN24TsjvCEwWDQWD9E29LMYfA6LNeG0KdL9Jvqad4bc2FTJn9TaCnJMCiAJ7wEEiotqhXn70uEBWYxGXIVlm3vn3MDe3pTKA2TZy7U5xcrE7S8aGMg";

    OpenIdAuthorizer authorizer = new OpenIdAuthorizer(JSONObjectUtils.parse(OPEN_ID_PUBLIC_JWK));
    boolean login = authorizer.login(jwt, null);

    assertTrue(login);
}
 
Example #24
Source File: OpenIdAuthorizer.java    From incubator-iotdb with Apache License 2.0 5 votes vote down vote up
static OIDCProviderMetadata fetchMetadata(String providerUrl) throws URISyntaxException, IOException, ParseException {
    URI issuerURI = new URI(providerUrl);
    URL providerConfigurationURL = issuerURI.resolve(".well-known/openid-configuration").toURL();
    InputStream stream = providerConfigurationURL.openStream();
    // Read all data from URL
    String providerInfo = null;
    try (java.util.Scanner s = new java.util.Scanner(stream)) {
        providerInfo = s.useDelimiter("\\A").hasNext() ? s.next() : "";
    }
    return OIDCProviderMetadata.parse(providerInfo);
}
 
Example #25
Source File: OpenIdAuthorizer.java    From incubator-iotdb with Apache License 2.0 5 votes vote down vote up
OpenIdAuthorizer(JSONObject jwk) throws AuthException {
    super(new LocalFileUserManager(config.getSystemDir() + File.separator + "users"),
            new LocalFileRoleManager(config.getSystemDir() + File.separator + "roles"));
    try {
        providerKey = RSAKey.parse(jwk).toRSAPublicKey();
    } catch (java.text.ParseException | JOSEException e) {
        throw new AuthException("Unable to get OIDC Provider Key from JWK " +  jwk.toString(), e);
    }
    logger.info("Initialized with providerKey: {}", providerKey);
}
 
Example #26
Source File: OpenIdConnector.java    From onedev with MIT License 4 votes vote down vote up
@Override
public SsoAuthenticated processLoginResponse() {
	HttpServletRequest request = (HttpServletRequest) RequestCycle.get().getRequest().getContainerRequest();
	try {
		AuthenticationResponse authenticationResponse = AuthenticationResponseParser.parse(
				new URI(request.getRequestURI() + "?" + request.getQueryString()));
		if (authenticationResponse instanceof AuthenticationErrorResponse) {
			throw buildException(((AuthenticationErrorResponse)authenticationResponse).getErrorObject()); 
		} else {
			AuthenticationSuccessResponse authenticationSuccessResponse = 
					(AuthenticationSuccessResponse)authenticationResponse;
			
			String state = (String) Session.get().getAttribute(SESSION_ATTR_STATE);
			
			if (state == null || !state.equals(authenticationSuccessResponse.getState().getValue()))
				throw new AuthenticationException("Unsolicited OIDC authentication response");
			
			AuthorizationGrant codeGrant = new AuthorizationCodeGrant(
					authenticationSuccessResponse.getAuthorizationCode(), getCallbackUri());

			ClientID clientID = new ClientID(getClientId());
			Secret clientSecret = new Secret(getClientSecret());
			ClientAuthentication clientAuth = new ClientSecretBasic(clientID, clientSecret);
			TokenRequest tokenRequest = new TokenRequest(
					new URI(getCachedProviderMetadata().getTokenEndpoint()), clientAuth, codeGrant);
			HTTPResponse httpResponse = tokenRequest.toHTTPRequest().send();
			if (httpResponse.getStatusCode() == HTTPResponse.SC_OK) {
				JSONObject jsonObject = httpResponse.getContentAsJSONObject();
				if (jsonObject.get("error") != null) 
					throw buildException(TokenErrorResponse.parse(jsonObject).getErrorObject());
				else 
					return processTokenResponse(OIDCAccessTokenResponse.parse(jsonObject));
			} else {
				ErrorObject error = TokenErrorResponse.parse(httpResponse).getErrorObject();
				if (error != null) {
					throw buildException(error);
				} else {
					String message = String.format("Error requesting OIDC token: http status: %d", 
							httpResponse.getStatusCode());
					throw new AuthenticationException(message);
				}
			}
		}
	} catch (ParseException | URISyntaxException|SerializeException|IOException e) {
		throw new RuntimeException(e);
	}
}
 
Example #27
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 #28
Source File: OpenIdAuthorizer.java    From incubator-iotdb with Apache License 2.0 4 votes vote down vote up
OpenIdAuthorizer(String providerUrl) throws AuthException, URISyntaxException, ParseException, IOException {
    this(getJWKfromProvider(providerUrl));
}
 
Example #29
Source File: OpenIdAuthorizer.java    From incubator-iotdb with Apache License 2.0 4 votes vote down vote up
public OpenIdAuthorizer() throws AuthException, ParseException, IOException, URISyntaxException {
    this(config.getOpenIdProviderUrl());
}
 
Example #30
Source File: HTTPRequest.java    From onedev with MIT License 3 votes vote down vote up
/**
 * Ensures this HTTP response has a specified query string or entity
 * body.
 *
 * @throws ParseException If the query string or entity body is missing
 *                        or empty.
 */
private void ensureQuery()
	throws ParseException {
	
	if (query == null || query.trim().isEmpty())
		throw new ParseException("Missing or empty HTTP query string / entity body");
}