com.nimbusds.oauth2.sdk.token.BearerAccessToken Java Examples

The following examples show how to use com.nimbusds.oauth2.sdk.token.BearerAccessToken. 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: DefaultJsonConverter.java    From vertx-pac4j with Apache License 2.0 5 votes vote down vote up
public DefaultJsonConverter() {
    mapper.setVisibility(PropertyAccessor.FIELD, JsonAutoDetect.Visibility.ANY);
    mapper.setVisibility(PropertyAccessor.GETTER, JsonAutoDetect.Visibility.NONE);
    mapper.setVisibility(PropertyAccessor.IS_GETTER, JsonAutoDetect.Visibility.NONE);

    mapper.addMixIn(OAuth1RequestToken.class, OAuth1RequestTokenMixin.class)
        .addMixIn(BearerAccessToken.class, BearerAccessTokenMixin.class)
        .addMixIn(Scope.Value.class, ValueMixin.class)
        .addMixIn(Token.class, TokenMixin.class);
}
 
Example #3
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 #4
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 #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);
	}
}