Search in sources :

Example 1 with AbstractToken

use of org.gluu.oxauth.model.common.AbstractToken in project oxAuth by GluuFederation.

the class IntrospectionWebService method introspect.

private Response introspect(String p_authorization, String p_token, String tokenTypeHint, String responseAsJwt, HttpServletRequest httpRequest, HttpServletResponse httpResponse) {
    try {
        log.trace("Introspect token, authorization: {}, token to introspect: {}, tokenTypeHint: {}", p_authorization, p_token, tokenTypeHint);
        AuthorizationGrant authorizationGrant = validateAuthorization(p_authorization, p_token);
        if (StringUtils.isBlank(p_token)) {
            log.trace("Bad request: Token is blank.");
            return Response.status(Response.Status.BAD_REQUEST).type(MediaType.APPLICATION_JSON_TYPE).entity(errorResponseFactory.errorAsJson(AuthorizeErrorResponseType.INVALID_REQUEST, "")).build();
        }
        final IntrospectionResponse response = new IntrospectionResponse(false);
        final AuthorizationGrant grantOfIntrospectionToken = authorizationGrantList.getAuthorizationGrantByAccessToken(p_token);
        AbstractToken tokenToIntrospect = null;
        if (grantOfIntrospectionToken != null) {
            tokenToIntrospect = grantOfIntrospectionToken.getAccessToken(p_token);
            response.setActive(tokenToIntrospect.isValid());
            response.setExpiresAt(ServerUtil.dateToSeconds(tokenToIntrospect.getExpirationDate()));
            response.setIssuedAt(ServerUtil.dateToSeconds(tokenToIntrospect.getCreationDate()));
            response.setAcrValues(grantOfIntrospectionToken.getAcrValues());
            // #433
            response.setScope(grantOfIntrospectionToken.getScopes() != null ? grantOfIntrospectionToken.getScopes() : Lists.newArrayList());
            response.setClientId(grantOfIntrospectionToken.getClientId());
            response.setSub(grantOfIntrospectionToken.getSub());
            response.setUsername(grantOfIntrospectionToken.getUserId());
            response.setIssuer(appConfiguration.getIssuer());
            response.setAudience(grantOfIntrospectionToken.getClientId());
            if (tokenToIntrospect instanceof AccessToken) {
                AccessToken accessToken = (AccessToken) tokenToIntrospect;
                response.setTokenType(accessToken.getTokenType() != null ? accessToken.getTokenType().getName() : TokenType.BEARER.getName());
            }
        } else {
            log.debug("Failed to find grant for access_token: " + p_token + ". Return 200 with active=false.");
        }
        JSONObject responseAsJsonObject = createResponseAsJsonObject(response, tokenToIntrospect);
        ExternalIntrospectionContext context = new ExternalIntrospectionContext(authorizationGrant, httpRequest, httpResponse, appConfiguration, attributeService);
        context.setGrantOfIntrospectionToken(grantOfIntrospectionToken);
        if (externalIntrospectionService.executeExternalModifyResponse(responseAsJsonObject, context)) {
            log.trace("Successfully run extenal introspection scripts.");
        } else {
            responseAsJsonObject = createResponseAsJsonObject(response, tokenToIntrospect);
            log.trace("Canceled changes made by external introspection script since method returned `false`.");
        }
        // Make scopes conform as required by spec, see #1499
        if (response.getScope() != null && !appConfiguration.getIntrospectionResponseScopesBackwardCompatibility()) {
            String scopes = StringUtils.join(response.getScope().toArray(), " ");
            responseAsJsonObject.put("scope", scopes);
        }
        if (Boolean.TRUE.toString().equalsIgnoreCase(responseAsJwt)) {
            return Response.status(Response.Status.OK).entity(createResponseAsJwt(responseAsJsonObject, grantOfIntrospectionToken)).build();
        }
        return Response.status(Response.Status.OK).entity(responseAsJsonObject.toString()).type(MediaType.APPLICATION_JSON_TYPE).build();
    } catch (WebApplicationException e) {
        log.error(e.getMessage(), e);
        throw e;
    } catch (Exception e) {
        log.error(e.getMessage(), e);
        return Response.status(Response.Status.INTERNAL_SERVER_ERROR).type(MediaType.APPLICATION_JSON_TYPE).build();
    }
}
Also used : AbstractToken(org.gluu.oxauth.model.common.AbstractToken) JSONObject(org.json.JSONObject) WebApplicationException(javax.ws.rs.WebApplicationException) IntrospectionResponse(org.gluu.oxauth.model.common.IntrospectionResponse) AccessToken(org.gluu.oxauth.model.common.AccessToken) ExternalIntrospectionContext(org.gluu.oxauth.service.external.context.ExternalIntrospectionContext) AuthorizationGrant(org.gluu.oxauth.model.common.AuthorizationGrant) JSONException(org.json.JSONException) IOException(java.io.IOException) WebApplicationException(javax.ws.rs.WebApplicationException) UnsupportedEncodingException(java.io.UnsupportedEncodingException)

Example 2 with AbstractToken

use of org.gluu.oxauth.model.common.AbstractToken in project oxAuth by GluuFederation.

the class IntrospectionWebService method validateAuthorization.

private AuthorizationGrant validateAuthorization(String p_authorization, String p_token) throws UnsupportedEncodingException {
    final boolean skipAuthorization = ServerUtil.isTrue(appConfiguration.getIntrospectionSkipAuthorization());
    log.trace("skipAuthorization: {}", skipAuthorization);
    if (skipAuthorization) {
        return null;
    }
    if (StringUtils.isBlank(p_authorization)) {
        log.trace("Bad request: Authorization header or token is blank.");
        throw new WebApplicationException(Response.status(Response.Status.BAD_REQUEST).type(MediaType.APPLICATION_JSON_TYPE).entity(errorResponseFactory.errorAsJson(AuthorizeErrorResponseType.INVALID_REQUEST, "")).build());
    }
    final Pair<AuthorizationGrant, Boolean> pair = getAuthorizationGrant(p_authorization, p_token);
    final AuthorizationGrant authorizationGrant = pair.getFirst();
    if (authorizationGrant == null) {
        log.error("Authorization grant is null.");
        throw new WebApplicationException(Response.status(Response.Status.UNAUTHORIZED).type(MediaType.APPLICATION_JSON_TYPE).entity(errorResponseFactory.errorAsJson(AuthorizeErrorResponseType.ACCESS_DENIED, "Authorization grant is null.")).build());
    }
    final AbstractToken authorizationAccessToken = authorizationGrant.getAccessToken(tokenService.getToken(p_authorization));
    if ((authorizationAccessToken == null || !authorizationAccessToken.isValid()) && !pair.getSecond()) {
        log.error("Access token is not valid. Valid: " + (authorizationAccessToken != null && authorizationAccessToken.isValid()) + ", basicClientAuthentication: " + pair.getSecond());
        throw new WebApplicationException(Response.status(Response.Status.UNAUTHORIZED).type(MediaType.APPLICATION_JSON_TYPE).entity(errorResponseFactory.errorAsJson(AuthorizeErrorResponseType.ACCESS_DENIED, "Access token is not valid")).build());
    }
    if (ServerUtil.isTrue(appConfiguration.getIntrospectionAccessTokenMustHaveUmaProtectionScope()) && !authorizationGrant.getScopesAsString().contains(UmaScopeType.PROTECTION.getValue())) {
        // #562 - make uma_protection optional
        final String reason = "access_token used to access introspection endpoint does not have uma_protection scope, however in oxauth configuration `checkUmaProtectionScopePresenceDuringIntrospection` is true";
        log.trace(reason);
        throw new WebApplicationException(Response.status(Response.Status.UNAUTHORIZED).entity(errorResponseFactory.errorAsJson(AuthorizeErrorResponseType.ACCESS_DENIED, reason)).type(MediaType.APPLICATION_JSON_TYPE).build());
    }
    return authorizationGrant;
}
Also used : WebApplicationException(javax.ws.rs.WebApplicationException) AbstractToken(org.gluu.oxauth.model.common.AbstractToken) AuthorizationGrant(org.gluu.oxauth.model.common.AuthorizationGrant)

Example 3 with AbstractToken

use of org.gluu.oxauth.model.common.AbstractToken in project oxAuth by GluuFederation.

the class StatWS method validateAuthorization.

private void validateAuthorization(String authorization) {
    log.trace("Validating authorization: " + authorization);
    AuthorizationGrant grant = tokenService.getAuthorizationGrant(authorization);
    if (grant == null) {
        log.trace("Unable to find token by authorization: " + authorization);
        throw errorResponseFactory.createWebApplicationException(Response.Status.UNAUTHORIZED, TokenErrorResponseType.ACCESS_DENIED, "Can't find grant for authorization.");
    }
    final AbstractToken accessToken = grant.getAccessToken(tokenService.getToken(authorization));
    if (accessToken == null) {
        log.trace("Unable to find token by authorization: " + authorization);
        throw errorResponseFactory.createWebApplicationException(Response.Status.UNAUTHORIZED, TokenErrorResponseType.ACCESS_DENIED, "Can't find access token.");
    }
    if (accessToken.isExpired()) {
        log.trace("Access Token is expired: " + accessToken.getCode());
        throw errorResponseFactory.createWebApplicationException(Response.Status.UNAUTHORIZED, TokenErrorResponseType.ACCESS_DENIED, "Token expired.");
    }
    if (!grant.getScopesAsString().contains(appConfiguration.getStatAuthorizationScope())) {
        log.trace("Access Token does NOT have '" + appConfiguration.getStatAuthorizationScope() + "' scope which is required to call Statistic Endpoint.");
        throw errorResponseFactory.createWebApplicationException(Response.Status.UNAUTHORIZED, TokenErrorResponseType.ACCESS_DENIED, appConfiguration.getStatAuthorizationScope() + " scope is required for token.");
    }
}
Also used : AbstractToken(org.gluu.oxauth.model.common.AbstractToken) AuthorizationGrant(org.gluu.oxauth.model.common.AuthorizationGrant)

Example 4 with AbstractToken

use of org.gluu.oxauth.model.common.AbstractToken in project oxAuth by GluuFederation.

the class ClientInfoRestWebServiceImpl method requestClientInfo.

public Response requestClientInfo(String accessToken, String authorization, SecurityContext securityContext) {
    if (tokenService.isBearerAuthToken(authorization)) {
        accessToken = tokenService.getBearerToken(authorization);
    }
    log.debug("Attempting to request Client Info, Access token = {}, Is Secure = {}", new Object[] { accessToken, securityContext.isSecure() });
    Response.ResponseBuilder builder = Response.ok();
    if (!ClientInfoParamsValidator.validateParams(accessToken)) {
        builder = Response.status(400);
        builder.entity(errorResponseFactory.errorAsJson(ClientInfoErrorResponseType.INVALID_REQUEST, "Failed to validate access token."));
    } else {
        AuthorizationGrant authorizationGrant = authorizationGrantList.getAuthorizationGrantByAccessToken(accessToken);
        if (authorizationGrant == null) {
            log.trace("Failed to find authorization grant for access token.");
            return Response.status(400).entity(errorResponseFactory.getErrorAsJson(ClientInfoErrorResponseType.INVALID_TOKEN, "", "Unable to find grant object associated with access token.")).build();
        }
        final AbstractToken token = authorizationGrant.getAccessToken(accessToken);
        if (token == null || !token.isValid()) {
            log.trace("Invalid access token.");
            return Response.status(400).entity(errorResponseFactory.getErrorAsJson(ClientInfoErrorResponseType.INVALID_TOKEN, "", "Invalid access token.")).build();
        }
        builder.cacheControl(ServerUtil.cacheControlWithNoStoreTransformAndPrivate());
        builder.header("Pragma", "no-cache");
        builder.entity(getJSonResponse(authorizationGrant.getClient(), authorizationGrant.getScopes()));
    }
    return builder.build();
}
Also used : Response(javax.ws.rs.core.Response) AbstractToken(org.gluu.oxauth.model.common.AbstractToken) AuthorizationGrant(org.gluu.oxauth.model.common.AuthorizationGrant)

Example 5 with AbstractToken

use of org.gluu.oxauth.model.common.AbstractToken in project oxAuth by GluuFederation.

the class IntrospectionWebService method getAuthorizationGrant.

/**
 * @return we return pair of authorization grant or otherwise true - if it's basic client authentication or false if it is not
 * @throws UnsupportedEncodingException when encoding is not supported
 */
private Pair<AuthorizationGrant, Boolean> getAuthorizationGrant(String authorization, String accessToken) throws UnsupportedEncodingException {
    AuthorizationGrant grant = tokenService.getBearerAuthorizationGrant(authorization);
    if (grant != null) {
        final String authorizationAccessToken = tokenService.getBearerToken(authorization);
        final AbstractToken accessTokenObject = grant.getAccessToken(authorizationAccessToken);
        if (accessTokenObject != null && accessTokenObject.isValid()) {
            return new Pair<>(grant, false);
        } else {
            log.error("Access token is not valid: " + authorizationAccessToken);
            return EMPTY;
        }
    }
    grant = tokenService.getBasicAuthorizationGrant(authorization);
    if (grant != null) {
        return new Pair<>(grant, false);
    }
    if (tokenService.isBasicAuthToken(authorization)) {
        String encodedCredentials = tokenService.getBasicToken(authorization);
        String token = new String(Base64.decodeBase64(encodedCredentials), StandardCharsets.UTF_8);
        int delim = token.indexOf(":");
        if (delim != -1) {
            String clientId = URLDecoder.decode(token.substring(0, delim), Util.UTF8_STRING_ENCODING);
            String password = URLDecoder.decode(token.substring(delim + 1), Util.UTF8_STRING_ENCODING);
            if (clientService.authenticate(clientId, password)) {
                grant = authorizationGrantList.getAuthorizationGrantByAccessToken(accessToken);
                if (grant != null && !grant.getClientId().equals(clientId)) {
                    log.trace("Failed to match grant object clientId and client id provided during authentication.");
                    return EMPTY;
                }
                return new Pair<>(grant, true);
            } else {
                log.trace("Failed to perform basic authentication for client: " + clientId);
            }
        }
    }
    return EMPTY;
}
Also used : AbstractToken(org.gluu.oxauth.model.common.AbstractToken) AuthorizationGrant(org.gluu.oxauth.model.common.AuthorizationGrant) Pair(org.gluu.util.Pair)

Aggregations

AbstractToken (org.gluu.oxauth.model.common.AbstractToken)5 AuthorizationGrant (org.gluu.oxauth.model.common.AuthorizationGrant)5 WebApplicationException (javax.ws.rs.WebApplicationException)2 IOException (java.io.IOException)1 UnsupportedEncodingException (java.io.UnsupportedEncodingException)1 Response (javax.ws.rs.core.Response)1 AccessToken (org.gluu.oxauth.model.common.AccessToken)1 IntrospectionResponse (org.gluu.oxauth.model.common.IntrospectionResponse)1 ExternalIntrospectionContext (org.gluu.oxauth.service.external.context.ExternalIntrospectionContext)1 Pair (org.gluu.util.Pair)1 JSONException (org.json.JSONException)1 JSONObject (org.json.JSONObject)1