use of com.nimbusds.oauth2.sdk.TokenIntrospectionRequest in project conquery by bakdata.
the class IntrospectionDelegatingRealm method validateToken.
/**
* Is called by the CacheLoader, so the Token is not validated on every request.
*/
private TokenIntrospectionSuccessResponse validateToken(AuthenticationToken token) throws ParseException, IOException {
TokenIntrospectionRequest request = new TokenIntrospectionRequest(URI.create(authProviderConf.getIntrospectionEndpoint()), authProviderConf.getClientAuthentication(), new TypelessAccessToken((String) token.getCredentials()));
TokenIntrospectionResponse response = TokenIntrospectionResponse.parse(request.toHTTPRequest().send());
log.trace("Retrieved token introspection response.");
if (!response.indicatesSuccess()) {
HTTPResponse httpResponse = response.toHTTPResponse();
log.error("Received the following error from the auth server while validating a token: {} {} {}", httpResponse.getStatusCode(), httpResponse.getStatusMessage(), httpResponse.getContent());
throw new AuthenticationException("Unable to retrieve access token from auth server.");
} else if (!(response instanceof TokenIntrospectionSuccessResponse)) {
log.error("Unknown token response {}.", response.getClass().getName());
throw new AuthenticationException("Unknown token response. See log.");
}
TokenIntrospectionSuccessResponse successResponse = response.toSuccessResponse();
if (log.isTraceEnabled()) {
log.trace("Token introspection: {}", successResponse.toJSONObject());
}
if (!successResponse.isActive()) {
log.trace("Token was not active");
throw new ExpiredCredentialsException();
}
return successResponse;
}
use of com.nimbusds.oauth2.sdk.TokenIntrospectionRequest in project product-is by wso2.
the class OAuth2TokenRevocationWithRevokedAccessToken method introspectAccessToken.
private TokenIntrospectionResponse introspectAccessToken(AccessToken accessToken, AccessToken privilegedAccessToken) throws Exception {
URI introSpecEndpoint;
if (TENANT_DOMAIN.equals(activeTenant)) {
introSpecEndpoint = new URI(OAuth2Constant.TENANT_INTRO_SPEC_ENDPOINT);
} else {
introSpecEndpoint = new URI(OAuth2Constant.INTRO_SPEC_ENDPOINT);
}
BearerAccessToken bearerAccessToken = new BearerAccessToken(privilegedAccessToken.getValue());
TokenIntrospectionRequest TokenIntroRequest = new TokenIntrospectionRequest(introSpecEndpoint, bearerAccessToken, accessToken);
HTTPResponse introspectionHTTPResp = TokenIntroRequest.toHTTPRequest().send();
Assert.assertNotNull(introspectionHTTPResp, "Introspection http response is null.");
return TokenIntrospectionResponse.parse(introspectionHTTPResp);
}
use of com.nimbusds.oauth2.sdk.TokenIntrospectionRequest in project product-is by wso2.
the class OAuth2XACMLScopeValidatorTestCase method getTokenAndValidate.
/**
* Request access token with the scope and validate the token.
*
* @param scope scope
* @return whether validation success or not
* @throws Exception exception
*/
private boolean getTokenAndValidate(Scope scope) throws Exception {
client = HttpClientBuilder.create().disableRedirectHandling().build();
try {
Secret password = new Secret(userInfo.getPassword());
AuthorizationGrant passwordGrant = new ResourceOwnerPasswordCredentialsGrant(userInfo.getUserName(), password);
ClientID clientID = new ClientID(consumerKey);
Secret clientSecret = new Secret(consumerSecret);
ClientAuthentication clientAuth = new ClientSecretBasic(clientID, clientSecret);
URI tokenEndpoint = new URI(OAuth2Constant.ACCESS_TOKEN_ENDPOINT);
TokenRequest request = new TokenRequest(tokenEndpoint, clientAuth, passwordGrant, scope);
HTTPResponse tokenHTTPResp = request.toHTTPRequest().send();
Assert.assertNotNull(tokenHTTPResp, "Access token http response is null.");
AccessTokenResponse tokenResponse = AccessTokenResponse.parse(tokenHTTPResp);
Assert.assertNotNull(tokenResponse, "Access token response is null.");
AccessToken accessToken = tokenResponse.getTokens().getAccessToken();
URI introSpecEndpoint = new URI(OAuth2Constant.INTRO_SPEC_ENDPOINT);
BearerAccessToken bearerAccessToken = new BearerAccessToken(accessToken.getValue());
TokenIntrospectionRequest TokenIntroRequest = new TokenIntrospectionRequest(introSpecEndpoint, bearerAccessToken, accessToken);
HTTPResponse introspectionHTTPResp = TokenIntroRequest.toHTTPRequest().send();
Assert.assertNotNull(introspectionHTTPResp, "Introspection http response is null.");
TokenIntrospectionResponse introspectionResponse = TokenIntrospectionResponse.parse(introspectionHTTPResp);
Assert.assertNotNull(introspectionResponse, "Introspection response is null.");
return introspectionResponse.indicatesSuccess();
} finally {
client.close();
}
}
use of com.nimbusds.oauth2.sdk.TokenIntrospectionRequest in project OpenConext-oidcng by OpenConext.
the class IntrospectEndpoint method introspect.
@PostMapping(value = { "oidc/introspect" }, consumes = { MediaType.APPLICATION_FORM_URLENCODED_VALUE })
public ResponseEntity<Map<String, Object>> introspect(HttpServletRequest request) throws ParseException, IOException, java.text.ParseException {
HTTPRequest httpRequest = ServletUtils.createHTTPRequest(request);
TokenIntrospectionRequest tokenIntrospectionRequest = TokenIntrospectionRequest.parse(httpRequest);
ClientAuthentication clientAuthentication = tokenIntrospectionRequest.getClientAuthentication();
String accessTokenValue = tokenIntrospectionRequest.getToken().getValue();
// https://tools.ietf.org/html/rfc7662 is vague about the authorization requirements, but we enforce basic auth
if (!(clientAuthentication instanceof PlainClientSecret)) {
LOG.warn("No authentication present");
throw new UnauthorizedException("Invalid user / secret");
}
String clientId = clientAuthentication.getClientID().getValue();
OpenIDClient resourceServer = openIDClientRepository.findOptionalByClientId(clientId).orElseThrow(() -> new UnknownClientException(clientId));
MDCContext.mdcContext("action", "Introspect", "rp", resourceServer.getClientId(), "accessTokenValue", accessTokenValue);
if (!secretsMatch((PlainClientSecret) clientAuthentication, resourceServer)) {
LOG.warn("Secret does not match for RS " + resourceServer.getClientId());
throw new UnauthorizedException("Invalid user / secret");
}
if (!resourceServer.isResourceServer()) {
LOG.warn("RS required for not configured for RP " + resourceServer.getClientId());
throw new UnauthorizedException("Requires ResourceServer");
}
Optional<SignedJWT> optionalSignedJWT = tokenGenerator.parseAndValidateSignedJWT(accessTokenValue);
if (!optionalSignedJWT.isPresent()) {
LOG.warn("Invalid access_token " + accessTokenValue);
return ResponseEntity.ok(Collections.singletonMap("active", false));
}
SignedJWT signedJWT = optionalSignedJWT.get();
String jwtId = signedJWT.getJWTClaimsSet().getJWTID();
Optional<AccessToken> optionalAccessToken = accessTokenRepository.findByJwtId(jwtId);
if (!optionalAccessToken.isPresent()) {
LOG.warn("No access_token found " + accessTokenValue);
return ResponseEntity.ok(Collections.singletonMap("active", false));
}
AccessToken accessToken = optionalAccessToken.get();
if (accessToken.isExpired(Clock.systemDefaultZone())) {
LOG.warn("Access token is expired " + accessTokenValue);
return ResponseEntity.ok(Collections.singletonMap("active", false));
}
List<String> scopes = accessToken.getScopes();
Map<String, Object> result = new TreeMap<>();
boolean isUserAccessToken = !accessToken.isClientCredentials();
if (isUserAccessToken) {
OpenIDClient openIDClient = openIDClientRepository.findOptionalByClientId(accessToken.getClientId()).orElseThrow(() -> new UnknownClientException(accessToken.getClientId()));
if (!openIDClient.getClientId().equals(resourceServer.getClientId()) && !openIDClient.getAllowedResourceServers().contains(resourceServer.getClientId())) {
throw new UnauthorizedException(String.format("RP %s is not allowed to use the API of resource server %s. Allowed resource servers are %s", accessToken.getClientId(), resourceServer.getClientId(), openIDClient.getAllowedResourceServers()));
}
User user = tokenGenerator.decryptAccessTokenWithEmbeddedUserInfo(signedJWT);
result.put("updated_at", user.getUpdatedAt());
if (resourceServer.isIncludeUnspecifiedNameID()) {
result.put("unspecified_id", user.getUnspecifiedNameId());
}
result.put("authenticating_authority", user.getAuthenticatingAuthority());
result.put("sub", user.getSub());
result.putAll(user.getAttributes());
List<String> acrClaims = user.getAcrClaims();
if (!CollectionUtils.isEmpty(acrClaims)) {
result.put("acr", String.join(" ", acrClaims));
}
boolean validPseudonymisation = validPseudonymisation(result, resourceServer, openIDClient);
if (!validPseudonymisation && enforceEduidResourceServerLinkedAccount) {
LOG.warn(String.format("Pseudonymisation failed. No eduperson_principal_name for RS %s", resourceServer.getClientId()));
return ResponseEntity.ok(Collections.singletonMap("active", false));
}
}
// The following claims can not be overridden by the
result.put("active", true);
result.put("scope", String.join(" ", scopes));
result.put("client_id", accessToken.getClientId());
result.put("exp", accessToken.getExpiresIn().getTime() / 1000L);
result.put("sub", accessToken.getSub());
result.put("iss", issuer);
result.put("token_type", "Bearer");
LOG.debug(String.format("Returning introspect active %s for RS %s", true, resourceServer.getClientId()));
return ResponseEntity.ok(result);
}
use of com.nimbusds.oauth2.sdk.TokenIntrospectionRequest in project product-is by wso2.
the class PermissionBasedScopeValidatorTestCase method invokeIntrospectionService.
private TokenIntrospectionResponse invokeIntrospectionService(AccessToken accessToken, BearerAccessToken bearerAccessToken) throws URISyntaxException, IOException, ParseException {
URI introSpecEndpoint = new URI(OAuth2Constant.INTRO_SPEC_ENDPOINT);
TokenIntrospectionRequest TokenIntroRequest = new TokenIntrospectionRequest(introSpecEndpoint, bearerAccessToken, accessToken);
HTTPResponse introspectionHTTPResp = TokenIntroRequest.toHTTPRequest().send();
Assert.assertNotNull(introspectionHTTPResp, "Introspection http response is null.");
return TokenIntrospectionResponse.parse(introspectionHTTPResp);
}
Aggregations