com.nimbusds.openid.connect.sdk.UserInfoErrorResponse Java Examples

The following examples show how to use com.nimbusds.openid.connect.sdk.UserInfoErrorResponse. 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: 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 #2
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 #3
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 #4
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 #5
Source File: OpenIdConnector.java    From onedev with MIT License 4 votes vote down vote up
protected SsoAuthenticated processTokenResponse(OIDCAccessTokenResponse tokenSuccessResponse) {
	try {
		JWT idToken = tokenSuccessResponse.getIDToken();
		ReadOnlyJWTClaimsSet claims = idToken.getJWTClaimsSet();
		
		if (!claims.getIssuer().equals(getCachedProviderMetadata().getIssuer()))
			throw new AuthenticationException("Inconsistent issuer in provider metadata and ID token");
		
		DateTime now = new DateTime();
		
		if (claims.getIssueTime() != null && claims.getIssueTime().after(now.plusSeconds(10).toDate()))
			throw new AuthenticationException("Invalid issue date of ID token");
		
		if (claims.getExpirationTime() != null && now.toDate().after(claims.getExpirationTime()))
			throw new AuthenticationException("ID token was expired");

		String subject = claims.getSubject();
		
		BearerAccessToken accessToken = (BearerAccessToken) tokenSuccessResponse.getAccessToken();

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

		if (httpResponse.getStatusCode() == HTTPResponse.SC_OK) {
			JSONObject json = httpResponse.getContentAsJSONObject();
			if (!subject.equals(json.get("sub")))
				throw new AuthenticationException("OIDC error: Inconsistent sub in ID token and userinfo");
			String email = (String) json.get("email");
			if (StringUtils.isBlank(email))
				throw new AuthenticationException("OIDC error: No email claim returned");
			String userName = (String) json.get("preferred_username");
			if (StringUtils.isBlank(userName))
				userName = email;
			userName = StringUtils.substringBefore(userName, "@");
			
			String fullName = (String) json.get("name");

			List<String> groupNames;
			if (getGroupsClaim() != null) {
				groupNames = new ArrayList<>();
				JSONArray jsonArray = (JSONArray) json.get(getGroupsClaim());
				if (jsonArray != null) {
					for (Object group: jsonArray)
						groupNames.add((String) group);
				}
			} else {
				groupNames = null;
			}
			
			return new SsoAuthenticated(claims.getSubject(), userName, email, fullName, groupNames, null, this);
		} else {
			throw buildException(UserInfoErrorResponse.parse(httpResponse).getErrorObject());
		}
	} catch (Exception e) {
		throw ExceptionUtils.unchecked(e);
	}
}