Search in sources :

Example 1 with AuthorizationGrant

use of org.gluu.oxauth.model.common.AuthorizationGrant 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 AuthorizationGrant

use of org.gluu.oxauth.model.common.AuthorizationGrant 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 AuthorizationGrant

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

the class BackchannelDeviceRegistrationRestWebServiceImpl method requestBackchannelDeviceRegistrationPost.

@Override
public Response requestBackchannelDeviceRegistrationPost(String idTokenHint, String deviceRegistrationToken, HttpServletRequest httpRequest, HttpServletResponse httpResponse, SecurityContext securityContext) {
    OAuth2AuditLog oAuth2AuditLog = new OAuth2AuditLog(ServerUtil.getIpAddress(httpRequest), Action.BACKCHANNEL_DEVICE_REGISTRATION);
    // ATTENTION : please do not add more parameter in this debug method because it will not work with Seam 2.2.2.Final,
    // there is limit of 10 parameters (hardcoded), see: org.jboss.seam.core.Interpolator#interpolate
    log.debug("Attempting to request backchannel device registration: " + "idTokenHint = {}, deviceRegistrationToken = {}, isSecure = {}", idTokenHint, deviceRegistrationToken, securityContext.isSecure());
    Response.ResponseBuilder builder = Response.ok();
    if (!appConfiguration.getCibaEnabled()) {
        log.warn("Trying to register a CIBA device, however CIBA config is disabled.");
        builder = Response.status(Response.Status.BAD_REQUEST.getStatusCode());
        builder.entity(errorResponseFactory.getErrorAsJson(INVALID_REQUEST));
        return builder.build();
    }
    DefaultErrorResponse cibaDeviceRegistrationValidation = cibaDeviceRegistrationValidatorService.validateParams(idTokenHint, deviceRegistrationToken);
    if (cibaDeviceRegistrationValidation != null) {
        builder = Response.status(cibaDeviceRegistrationValidation.getStatus());
        builder.entity(errorResponseFactory.errorAsJson(cibaDeviceRegistrationValidation.getType(), cibaDeviceRegistrationValidation.getReason()));
        return builder.build();
    }
    User user = null;
    AuthorizationGrant authorizationGrant = authorizationGrantList.getAuthorizationGrantByIdToken(idTokenHint);
    if (authorizationGrant == null) {
        // 400
        builder = Response.status(Response.Status.BAD_REQUEST.getStatusCode());
        builder.entity(errorResponseFactory.getErrorAsJson(BackchannelAuthenticationErrorResponseType.UNKNOWN_USER_ID));
        return builder.build();
    }
    user = authorizationGrant.getUser();
    if (user == null) {
        // 400
        builder = Response.status(Response.Status.BAD_REQUEST.getStatusCode());
        builder.entity(errorResponseFactory.getErrorAsJson(UNKNOWN_USER_ID));
        return builder.build();
    }
    userService.setCustomAttribute(user, "oxAuthBackchannelDeviceRegistrationToken", deviceRegistrationToken);
    userService.updateUser(user);
    applicationAuditLogger.sendMessage(oAuth2AuditLog);
    return builder.build();
}
Also used : DefaultErrorResponse(org.gluu.oxauth.model.error.DefaultErrorResponse) HttpServletResponse(javax.servlet.http.HttpServletResponse) Response(javax.ws.rs.core.Response) User(org.gluu.oxauth.model.common.User) OAuth2AuditLog(org.gluu.oxauth.model.audit.OAuth2AuditLog) DefaultErrorResponse(org.gluu.oxauth.model.error.DefaultErrorResponse) AuthorizationGrant(org.gluu.oxauth.model.common.AuthorizationGrant)

Example 4 with AuthorizationGrant

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

the class EndSessionRestWebServiceImpl method getTokenHintGrant.

private AuthorizationGrant getTokenHintGrant(String idTokenHint) {
    if (StringUtils.isBlank(idTokenHint)) {
        return null;
    }
    AuthorizationGrant authorizationGrant = authorizationGrantList.getAuthorizationGrantByIdToken(idTokenHint);
    if (authorizationGrant != null) {
        return authorizationGrant;
    }
    Boolean endSessionWithAccessToken = appConfiguration.getEndSessionWithAccessToken();
    if ((endSessionWithAccessToken != null) && endSessionWithAccessToken) {
        return authorizationGrantList.getAuthorizationGrantByAccessToken(idTokenHint);
    }
    return null;
}
Also used : AuthorizationGrant(org.gluu.oxauth.model.common.AuthorizationGrant)

Example 5 with AuthorizationGrant

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

the class UmaResourceRegistrationWS method getResourceList.

/**
 * Gets resource set lists.
 * ATTENTION: "scope" is parameter added by gluu to have additional filtering.
 * There is no such parameter in UMA specification.
 *
 * @param authorization authorization
 * @param scope         scope of resource set for additional filtering, can blank string.
 * @return resource set ids.
 */
@GET
@Produces({ UmaConstants.JSON_MEDIA_TYPE })
public List<String> getResourceList(@HeaderParam("Authorization") String authorization, @QueryParam("scope") String scope) {
    try {
        log.trace("Getting list of resource descriptions.");
        final AuthorizationGrant authorizationGrant = umaValidationService.assertHasProtectionScope(authorization);
        final String clientDn = authorizationGrant.getClientDn();
        final List<org.gluu.oxauth.model.uma.persistence.UmaResource> ldapResources = resourceService.getResourcesByAssociatedClient(clientDn);
        final List<String> result = new ArrayList<String>(ldapResources.size());
        for (org.gluu.oxauth.model.uma.persistence.UmaResource ldapResource : ldapResources) {
            // if scope parameter is not null then filter by it, otherwise just add to result
            if (StringUtils.isNotBlank(scope)) {
                final List<String> scopeUrlsByDns = umaScopeService.getScopeIdsByDns(ldapResource.getScopes());
                if (scopeUrlsByDns != null && scopeUrlsByDns.contains(scope)) {
                    result.add(ldapResource.getId());
                }
            } else {
                result.add(ldapResource.getId());
            }
        }
        return result;
    } catch (Exception ex) {
        log.error("Exception happened on getResourceList()", ex);
        if (ex instanceof WebApplicationException) {
            throw (WebApplicationException) ex;
        } else {
            throw errorResponseFactory.createWebApplicationException(Response.Status.INTERNAL_SERVER_ERROR, UmaErrorResponseType.SERVER_ERROR, ex.getMessage());
        }
    }
}
Also used : org.gluu.oxauth.model.uma(org.gluu.oxauth.model.uma) IOException(java.io.IOException) AuthorizationGrant(org.gluu.oxauth.model.common.AuthorizationGrant)

Aggregations

AuthorizationGrant (org.gluu.oxauth.model.common.AuthorizationGrant)20 IOException (java.io.IOException)6 WebApplicationException (javax.ws.rs.WebApplicationException)5 AbstractToken (org.gluu.oxauth.model.common.AbstractToken)5 SessionId (org.gluu.oxauth.model.common.SessionId)4 Response (javax.ws.rs.core.Response)3 OAuth2AuditLog (org.gluu.oxauth.model.audit.OAuth2AuditLog)3 InvalidJwtException (org.gluu.oxauth.model.exception.InvalidJwtException)3 Client (org.gluu.oxauth.model.registration.Client)3 URISyntaxException (java.net.URISyntaxException)2 HttpServletResponse (javax.servlet.http.HttpServletResponse)2 Pair (org.gluu.util.Pair)2 UnsupportedEncodingException (java.io.UnsupportedEncodingException)1 URI (java.net.URI)1 ResponseBuilder (javax.ws.rs.core.Response.ResponseBuilder)1 CustomScriptConfiguration (org.gluu.model.custom.script.conf.CustomScriptConfiguration)1 AccessToken (org.gluu.oxauth.model.common.AccessToken)1 IntrospectionResponse (org.gluu.oxauth.model.common.IntrospectionResponse)1 TokenTypeHint (org.gluu.oxauth.model.common.TokenTypeHint)1 User (org.gluu.oxauth.model.common.User)1