Search in sources :

Example 1 with TokenIntrospectionRequest

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;
}
Also used : TypelessAccessToken(com.nimbusds.oauth2.sdk.token.TypelessAccessToken) AuthenticationException(org.apache.shiro.authc.AuthenticationException) TokenIntrospectionRequest(com.nimbusds.oauth2.sdk.TokenIntrospectionRequest) HTTPResponse(com.nimbusds.oauth2.sdk.http.HTTPResponse) TokenIntrospectionSuccessResponse(com.nimbusds.oauth2.sdk.TokenIntrospectionSuccessResponse) TokenIntrospectionResponse(com.nimbusds.oauth2.sdk.TokenIntrospectionResponse) ExpiredCredentialsException(org.apache.shiro.authc.ExpiredCredentialsException)

Example 2 with TokenIntrospectionRequest

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);
}
Also used : TokenIntrospectionRequest(com.nimbusds.oauth2.sdk.TokenIntrospectionRequest) HTTPResponse(com.nimbusds.oauth2.sdk.http.HTTPResponse) BearerAccessToken(com.nimbusds.oauth2.sdk.token.BearerAccessToken) URI(java.net.URI)

Example 3 with TokenIntrospectionRequest

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();
    }
}
Also used : HTTPResponse(com.nimbusds.oauth2.sdk.http.HTTPResponse) TokenIntrospectionRequest(com.nimbusds.oauth2.sdk.TokenIntrospectionRequest) ResourceOwnerPasswordCredentialsGrant(com.nimbusds.oauth2.sdk.ResourceOwnerPasswordCredentialsGrant) URI(java.net.URI) ClientSecretBasic(com.nimbusds.oauth2.sdk.auth.ClientSecretBasic) Secret(com.nimbusds.oauth2.sdk.auth.Secret) AccessToken(com.nimbusds.oauth2.sdk.token.AccessToken) BearerAccessToken(com.nimbusds.oauth2.sdk.token.BearerAccessToken) TokenRequest(com.nimbusds.oauth2.sdk.TokenRequest) ClientID(com.nimbusds.oauth2.sdk.id.ClientID) BearerAccessToken(com.nimbusds.oauth2.sdk.token.BearerAccessToken) TokenIntrospectionResponse(com.nimbusds.oauth2.sdk.TokenIntrospectionResponse) AuthorizationGrant(com.nimbusds.oauth2.sdk.AuthorizationGrant) ClientAuthentication(com.nimbusds.oauth2.sdk.auth.ClientAuthentication) AccessTokenResponse(com.nimbusds.oauth2.sdk.AccessTokenResponse)

Example 4 with TokenIntrospectionRequest

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);
}
Also used : HTTPRequest(com.nimbusds.oauth2.sdk.http.HTTPRequest) User(oidc.model.User) UnknownClientException(oidc.exceptions.UnknownClientException) OpenIDClient(oidc.model.OpenIDClient) TokenIntrospectionRequest(com.nimbusds.oauth2.sdk.TokenIntrospectionRequest) SignedJWT(com.nimbusds.jwt.SignedJWT) TreeMap(java.util.TreeMap) PlainClientSecret(com.nimbusds.oauth2.sdk.auth.PlainClientSecret) AccessToken(oidc.model.AccessToken) UnauthorizedException(oidc.exceptions.UnauthorizedException) ClientAuthentication(com.nimbusds.oauth2.sdk.auth.ClientAuthentication) PostMapping(org.springframework.web.bind.annotation.PostMapping)

Example 5 with TokenIntrospectionRequest

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);
}
Also used : TokenIntrospectionRequest(com.nimbusds.oauth2.sdk.TokenIntrospectionRequest) HTTPResponse(com.nimbusds.oauth2.sdk.http.HTTPResponse) URI(java.net.URI)

Aggregations

TokenIntrospectionRequest (com.nimbusds.oauth2.sdk.TokenIntrospectionRequest)6 HTTPResponse (com.nimbusds.oauth2.sdk.http.HTTPResponse)5 URI (java.net.URI)4 BearerAccessToken (com.nimbusds.oauth2.sdk.token.BearerAccessToken)3 TokenIntrospectionResponse (com.nimbusds.oauth2.sdk.TokenIntrospectionResponse)2 ClientAuthentication (com.nimbusds.oauth2.sdk.auth.ClientAuthentication)2 ClientSecretBasic (com.nimbusds.oauth2.sdk.auth.ClientSecretBasic)2 Secret (com.nimbusds.oauth2.sdk.auth.Secret)2 HTTPRequest (com.nimbusds.oauth2.sdk.http.HTTPRequest)2 ClientID (com.nimbusds.oauth2.sdk.id.ClientID)2 SignedJWT (com.nimbusds.jwt.SignedJWT)1 AccessTokenResponse (com.nimbusds.oauth2.sdk.AccessTokenResponse)1 AuthorizationGrant (com.nimbusds.oauth2.sdk.AuthorizationGrant)1 ResourceOwnerPasswordCredentialsGrant (com.nimbusds.oauth2.sdk.ResourceOwnerPasswordCredentialsGrant)1 TokenIntrospectionSuccessResponse (com.nimbusds.oauth2.sdk.TokenIntrospectionSuccessResponse)1 TokenRequest (com.nimbusds.oauth2.sdk.TokenRequest)1 PlainClientSecret (com.nimbusds.oauth2.sdk.auth.PlainClientSecret)1 AccessToken (com.nimbusds.oauth2.sdk.token.AccessToken)1 TypelessAccessToken (com.nimbusds.oauth2.sdk.token.TypelessAccessToken)1 TreeMap (java.util.TreeMap)1