Search in sources :

Example 26 with ResponseBuilder

use of javax.ws.rs.core.Response.ResponseBuilder in project OpenClinica by OpenClinica.

the class OpenRosaServices method getUserList.

/**
     * @api {get} /rest2/openrosa/:studyOID/downloadUsers Download users
     * @apiName getUserList
     * @apiPermission admin
     * @apiVersion 3.12.0
     * @apiParam {String} studyOID Study Oid.
     * @apiGroup Form
     * @apiDescription Downloads list of users for use with queries.
     */
@GET
@Path("/{studyOID}/downloadUsers")
public Response getUserList(@Context HttpServletRequest request, @Context HttpServletResponse response, @PathParam("studyOID") String studyOID, @RequestHeader("Authorization") String authorization, @Context ServletContext context) throws Exception {
    if (!mayProceedPreview(studyOID))
        return null;
    String userXml = getUserXml(context);
    ResponseBuilder builder = Response.ok(userXml);
    builder = builder.header("Content-Type", "text/xml");
    return builder.build();
}
Also used : ResponseBuilder(javax.ws.rs.core.Response.ResponseBuilder) Path(javax.ws.rs.Path) GET(javax.ws.rs.GET)

Example 27 with ResponseBuilder

use of javax.ws.rs.core.Response.ResponseBuilder in project oxAuth by GluuFederation.

the class RedirectUtil method getRedirectResponseBuilder.

public static ResponseBuilder getRedirectResponseBuilder(RedirectUri redirectUriResponse, HttpServletRequest httpRequest) {
    ResponseBuilder builder;
    if (httpRequest != null && httpRequest.getHeader(NO_REDIRECT_HEADER) != null) {
        try {
            URI redirectURI = URI.create(redirectUriResponse.toString());
            JSONObject jsonObject = new JSONObject();
            jsonObject.put(JSON_REDIRECT_PROPNAME, redirectURI.toURL());
            String jsonResp = jsonObject.toString();
            jsonResp = jsonResp.replace("\\/", "/");
            builder = Response.ok(new GenericEntity<String>(jsonResp, String.class), MediaType.APPLICATION_JSON_TYPE);
        } catch (MalformedURLException e) {
            builder = Response.serverError();
            log.debug(e.getMessage(), e);
        } catch (JSONException e) {
            builder = Response.serverError();
            log.debug(e.getMessage(), e);
        }
    } else if (redirectUriResponse.getResponseMode() != ResponseMode.FORM_POST) {
        URI redirectURI = URI.create(redirectUriResponse.toString());
        builder = new ResponseBuilderImpl();
        builder = Response.status(HTTP_REDIRECT);
        builder.location(redirectURI);
    } else {
        builder = new ResponseBuilderImpl();
        builder.status(Response.Status.OK);
        builder.type(MediaType.TEXT_HTML_TYPE);
        builder.cacheControl(CacheControl.valueOf("no-cache, no-store"));
        builder.header("Pragma", "no-cache");
        builder.entity(redirectUriResponse.toString());
    }
    return builder;
}
Also used : MalformedURLException(java.net.MalformedURLException) JSONObject(org.codehaus.jettison.json.JSONObject) GenericEntity(javax.ws.rs.core.GenericEntity) ResponseBuilderImpl(org.jboss.resteasy.specimpl.ResponseBuilderImpl) JSONException(org.codehaus.jettison.json.JSONException) ResponseBuilder(javax.ws.rs.core.Response.ResponseBuilder) URI(java.net.URI)

Example 28 with ResponseBuilder

use of javax.ws.rs.core.Response.ResponseBuilder in project oxAuth by GluuFederation.

the class ResourceSetRegistrationWS method getResourceSet.

@GET
@Path("{rsid}")
@Produces({ UmaConstants.JSON_MEDIA_TYPE })
@ApiOperation(value = "Reads a previously registered resource set description using the GET method.", notes = "Reads a previously registered resource set description using the GET method. If the request is successful, the authorization server MUST respond with a status message that includes a body containing the referenced resource set description, along with an \"_id\" property.", response = ResourceSet.class)
@ApiResponses(value = { @ApiResponse(code = 401, message = "Unauthorized") })
public Response getResourceSet(@HeaderParam("Authorization") String authorization, @PathParam("rsid") @ApiParam(value = "Resource set description object ID", required = true) String rsid) {
    try {
        umaValidationService.assertHasProtectionScope(authorization);
        log.debug("Getting resource set description: '{}'", rsid);
        final org.xdi.oxauth.model.uma.persistence.ResourceSet ldapResourceSet = resourceSetService.getResourceSetById(rsid);
        final ResourceSetWithId response = new ResourceSetWithId();
        response.setId(ldapResourceSet.getId());
        response.setName(ldapResourceSet.getName());
        response.setUri(ldapResourceSet.getUrl());
        response.setIconUri(ldapResourceSet.getIconUri());
        response.setScopes(umaScopeService.getScopeUrlsByDns(ldapResourceSet.getScopes()));
        final ResponseBuilder builder = Response.ok();
        // convert manually to avoid possible conflicts between resteasy providers, e.g. jettison, jackson
        builder.entity(ServerUtil.asJson(response));
        return builder.build();
    } catch (Exception ex) {
        log.error("Exception happened", ex);
        if (ex instanceof WebApplicationException) {
            throw (WebApplicationException) ex;
        }
        errorResponseFactory.throwUmaInternalErrorException();
        // redundant but required statement by java
        return null;
    }
}
Also used : ResourceSetWithId(org.xdi.oxauth.model.uma.ResourceSetWithId) WebApplicationException(javax.ws.rs.WebApplicationException) ResponseBuilder(javax.ws.rs.core.Response.ResponseBuilder) IOException(java.io.IOException) InvocationTargetException(java.lang.reflect.InvocationTargetException) WebApplicationException(javax.ws.rs.WebApplicationException) Path(javax.ws.rs.Path) Produces(javax.ws.rs.Produces) GET(javax.ws.rs.GET) ApiOperation(com.wordnik.swagger.annotations.ApiOperation) ApiResponses(com.wordnik.swagger.annotations.ApiResponses)

Example 29 with ResponseBuilder

use of javax.ws.rs.core.Response.ResponseBuilder in project oxAuth by GluuFederation.

the class TokenRestWebServiceImpl method requestAccessToken.

@Override
public Response requestAccessToken(String grantType, String code, String redirectUri, String username, String password, String scope, String assertion, String refreshToken, String oxAuthExchangeToken, String clientId, String clientSecret, String codeVerifier, HttpServletRequest request, SecurityContext sec) {
    log.debug("Attempting to request access token: grantType = {}, code = {}, redirectUri = {}, username = {}, refreshToken = {}, " + "clientId = {}, ExtraParams = {}, isSecure = {}, codeVerifier = {}", grantType, code, redirectUri, username, refreshToken, clientId, request.getParameterMap(), sec.isSecure(), codeVerifier);
    OAuth2AuditLog oAuth2AuditLog = new OAuth2AuditLog(ServerUtil.getIpAddress(request), Action.TOKEN_REQUEST);
    oAuth2AuditLog.setClientId(clientId);
    oAuth2AuditLog.setUsername(username);
    oAuth2AuditLog.setScope(scope);
    // it may be encoded in uma case
    scope = ServerUtil.urlDecode(scope);
    ResponseBuilder builder = Response.ok();
    try {
        log.debug("Starting to validate request parameters");
        if (!TokenParamsValidator.validateParams(grantType, code, redirectUri, username, password, scope, assertion, refreshToken, oxAuthExchangeToken)) {
            log.trace("Failed to validate request parameters");
            builder = error(400, TokenErrorResponseType.INVALID_REQUEST);
        } else {
            log.trace("Request parameters are right");
            GrantType gt = GrantType.fromString(grantType);
            log.debug("Grant type: '{}'", gt);
            SessionClient sessionClient = identity.getSetSessionClient();
            Client client = null;
            if (sessionClient != null) {
                client = sessionClient.getClient();
                log.debug("Get sessionClient: '{}'", sessionClient);
            }
            if (client != null) {
                log.debug("Get client from session: '{}'", client.getClientId());
            }
            if (gt == GrantType.AUTHORIZATION_CODE) {
                if (client == null) {
                    return response(error(400, TokenErrorResponseType.INVALID_GRANT));
                }
                log.debug("Attempting to find authorizationCodeGrant by clinetId: '{}', code: '{}'", client.getClientId(), code);
                AuthorizationCodeGrant authorizationCodeGrant = authorizationGrantList.getAuthorizationCodeGrant(client.getClientId(), code);
                log.trace("AuthorizationCodeGrant : '{}'", authorizationCodeGrant);
                if (authorizationCodeGrant != null) {
                    validatePKCE(authorizationCodeGrant, codeVerifier);
                    authorizationCodeGrant.setIsCachedWithNoPersistence(false);
                    authorizationCodeGrant.save();
                    AccessToken accToken = authorizationCodeGrant.createAccessToken();
                    log.debug("Issuing access token: {}", accToken.getCode());
                    RefreshToken reToken = authorizationCodeGrant.createRefreshToken();
                    if (scope != null && !scope.isEmpty()) {
                        scope = authorizationCodeGrant.checkScopesPolicy(scope);
                    }
                    IdToken idToken = null;
                    if (authorizationCodeGrant.getScopes().contains("openid")) {
                        String nonce = authorizationCodeGrant.getNonce();
                        boolean includeIdTokenClaims = Boolean.TRUE.equals(appConfiguration.getLegacyIdTokenClaims());
                        idToken = authorizationCodeGrant.createIdToken(nonce, null, accToken, authorizationCodeGrant, includeIdTokenClaims);
                    }
                    builder.entity(getJSonResponse(accToken, accToken.getTokenType(), accToken.getExpiresIn(), reToken, scope, idToken));
                    oAuth2AuditLog.updateOAuth2AuditLog(authorizationCodeGrant, true);
                    grantService.removeByCode(authorizationCodeGrant.getAuthorizationCode().getCode(), authorizationCodeGrant.getClientId());
                } else {
                    log.debug("AuthorizationCodeGrant is empty by clinetId: '{}', code: '{}'", client.getClientId(), code);
                    // if authorization code is not found then code was already used = remove all grants with this auth code
                    grantService.removeAllByAuthorizationCode(code);
                    builder = error(400, TokenErrorResponseType.INVALID_GRANT);
                }
            } else if (gt == GrantType.REFRESH_TOKEN) {
                if (client == null) {
                    return response(error(401, TokenErrorResponseType.INVALID_GRANT));
                }
                AuthorizationGrant authorizationGrant = authorizationGrantList.getAuthorizationGrantByRefreshToken(client.getClientId(), refreshToken);
                if (authorizationGrant != null) {
                    AccessToken accToken = authorizationGrant.createAccessToken();
                    /*
                        The authorization server MAY issue a new refresh token, in which case
                        the client MUST discard the old refresh token and replace it with the
                        new refresh token.
                        */
                    RefreshToken reToken = authorizationGrant.createRefreshToken();
                    grantService.removeByCode(refreshToken, client.getClientId());
                    if (scope != null && !scope.isEmpty()) {
                        scope = authorizationGrant.checkScopesPolicy(scope);
                    }
                    builder.entity(getJSonResponse(accToken, accToken.getTokenType(), accToken.getExpiresIn(), reToken, scope, null));
                    oAuth2AuditLog.updateOAuth2AuditLog(authorizationGrant, true);
                } else {
                    builder = error(401, TokenErrorResponseType.INVALID_GRANT);
                }
            } else if (gt == GrantType.CLIENT_CREDENTIALS) {
                if (client == null) {
                    return response(error(401, TokenErrorResponseType.INVALID_GRANT));
                }
                // TODO: fix the user arg
                ClientCredentialsGrant clientCredentialsGrant = authorizationGrantList.createClientCredentialsGrant(new User(), client);
                AccessToken accessToken = clientCredentialsGrant.createAccessToken();
                if (scope != null && !scope.isEmpty()) {
                    scope = clientCredentialsGrant.checkScopesPolicy(scope);
                }
                IdToken idToken = null;
                if (clientCredentialsGrant.getScopes().contains("openid")) {
                    boolean includeIdTokenClaims = Boolean.TRUE.equals(appConfiguration.getLegacyIdTokenClaims());
                    idToken = clientCredentialsGrant.createIdToken(null, null, null, clientCredentialsGrant, includeIdTokenClaims);
                }
                oAuth2AuditLog.updateOAuth2AuditLog(clientCredentialsGrant, true);
                builder.entity(getJSonResponse(accessToken, accessToken.getTokenType(), accessToken.getExpiresIn(), null, scope, idToken));
            } else if (gt == GrantType.RESOURCE_OWNER_PASSWORD_CREDENTIALS) {
                if (client == null) {
                    log.error("Invalid client", new RuntimeException("Client is empty"));
                    return response(error(401, TokenErrorResponseType.INVALID_CLIENT));
                }
                User user = null;
                if (authenticationFilterService.isEnabled()) {
                    String userDn = authenticationFilterService.processAuthenticationFilters(request.getParameterMap());
                    if (StringHelper.isNotEmpty(userDn)) {
                        user = userService.getUserByDn(userDn);
                    }
                }
                if (user == null) {
                    boolean authenticated = authenticationService.authenticate(username, password);
                    if (authenticated) {
                        user = authenticationService.getAuthenticatedUser();
                    }
                }
                if (user != null) {
                    ResourceOwnerPasswordCredentialsGrant resourceOwnerPasswordCredentialsGrant = authorizationGrantList.createResourceOwnerPasswordCredentialsGrant(user, client);
                    AccessToken accessToken = resourceOwnerPasswordCredentialsGrant.createAccessToken();
                    RefreshToken reToken = resourceOwnerPasswordCredentialsGrant.createRefreshToken();
                    if (scope != null && !scope.isEmpty()) {
                        scope = resourceOwnerPasswordCredentialsGrant.checkScopesPolicy(scope);
                    }
                    IdToken idToken = null;
                    if (resourceOwnerPasswordCredentialsGrant.getScopes().contains("openid")) {
                        boolean includeIdTokenClaims = Boolean.TRUE.equals(appConfiguration.getLegacyIdTokenClaims());
                        idToken = resourceOwnerPasswordCredentialsGrant.createIdToken(null, null, null, resourceOwnerPasswordCredentialsGrant, includeIdTokenClaims);
                    }
                    oAuth2AuditLog.updateOAuth2AuditLog(resourceOwnerPasswordCredentialsGrant, true);
                    builder.entity(getJSonResponse(accessToken, accessToken.getTokenType(), accessToken.getExpiresIn(), reToken, scope, idToken));
                } else {
                    log.error("Invalid user", new RuntimeException("User is empty"));
                    builder = error(401, TokenErrorResponseType.INVALID_CLIENT);
                }
            } else if (gt == GrantType.EXTENSION) {
                builder = error(501, TokenErrorResponseType.INVALID_GRANT);
            } else if (gt == GrantType.OXAUTH_EXCHANGE_TOKEN) {
                AuthorizationGrant authorizationGrant = authorizationGrantList.getAuthorizationGrantByAccessToken(oxAuthExchangeToken);
                if (authorizationGrant != null) {
                    final AccessToken accessToken = authorizationGrant.createLongLivedAccessToken();
                    oAuth2AuditLog.updateOAuth2AuditLog(authorizationGrant, true);
                    builder.entity(getJSonResponse(accessToken, accessToken.getTokenType(), accessToken.getExpiresIn(), null, null, null));
                } else {
                    builder = error(401, TokenErrorResponseType.INVALID_GRANT);
                }
            }
        }
    } catch (WebApplicationException e) {
        throw e;
    } catch (SignatureException e) {
        builder = Response.status(500);
        log.error(e.getMessage(), e);
    } catch (StringEncrypter.EncryptionException e) {
        builder = Response.status(500);
        log.error(e.getMessage(), e);
    } catch (InvalidJwtException e) {
        builder = Response.status(500);
        log.error(e.getMessage(), e);
    } catch (InvalidJweException e) {
        builder = Response.status(500);
        log.error(e.getMessage(), e);
    } catch (Exception e) {
        builder = Response.status(500);
        log.error(e.getMessage(), e);
    }
    applicationAuditLogger.sendMessage(oAuth2AuditLog);
    return response(builder);
}
Also used : InvalidJwtException(org.xdi.oxauth.model.exception.InvalidJwtException) IdToken(org.xdi.oxauth.model.common.IdToken) User(org.xdi.oxauth.model.common.User) WebApplicationException(javax.ws.rs.WebApplicationException) SessionClient(org.xdi.oxauth.model.session.SessionClient) OAuth2AuditLog(org.xdi.oxauth.model.audit.OAuth2AuditLog) ResourceOwnerPasswordCredentialsGrant(org.xdi.oxauth.model.common.ResourceOwnerPasswordCredentialsGrant) GrantType(org.xdi.oxauth.model.common.GrantType) SignatureException(java.security.SignatureException) StringEncrypter(org.xdi.util.security.StringEncrypter) InvalidJwtException(org.xdi.oxauth.model.exception.InvalidJwtException) SignatureException(java.security.SignatureException) JSONException(org.codehaus.jettison.json.JSONException) WebApplicationException(javax.ws.rs.WebApplicationException) InvalidJweException(org.xdi.oxauth.model.exception.InvalidJweException) RefreshToken(org.xdi.oxauth.model.common.RefreshToken) AuthorizationCodeGrant(org.xdi.oxauth.model.common.AuthorizationCodeGrant) AccessToken(org.xdi.oxauth.model.common.AccessToken) ClientCredentialsGrant(org.xdi.oxauth.model.common.ClientCredentialsGrant) ResponseBuilder(javax.ws.rs.core.Response.ResponseBuilder) Client(org.xdi.oxauth.model.registration.Client) SessionClient(org.xdi.oxauth.model.session.SessionClient) AuthorizationGrant(org.xdi.oxauth.model.common.AuthorizationGrant) InvalidJweException(org.xdi.oxauth.model.exception.InvalidJweException)

Example 30 with ResponseBuilder

use of javax.ws.rs.core.Response.ResponseBuilder in project indy by Commonjava.

the class ResponseUtils method formatBadRequestResponse.

public static Response formatBadRequestResponse(final String error, final Consumer<ResponseBuilder> builderModifier) {
    final String msg = "{\"error\": \"" + error + "\"}\n";
    ResponseBuilder builder = Response.status(Status.BAD_REQUEST).type(MediaType.APPLICATION_JSON).entity(msg);
    if (builderModifier != null) {
        builderModifier.accept(builder);
    }
    return builder.build();
}
Also used : ResponseBuilder(javax.ws.rs.core.Response.ResponseBuilder)

Aggregations

ResponseBuilder (javax.ws.rs.core.Response.ResponseBuilder)175 GET (javax.ws.rs.GET)84 Produces (javax.ws.rs.Produces)81 Path (javax.ws.rs.Path)69 WebApplicationException (javax.ws.rs.WebApplicationException)47 Viewable (org.apache.stanbol.commons.web.viewable.Viewable)40 IOException (java.io.IOException)30 MediaType (javax.ws.rs.core.MediaType)29 POST (javax.ws.rs.POST)23 IRI (org.semanticweb.owlapi.model.IRI)22 EntityhubLDPath (org.apache.stanbol.entityhub.ldpath.EntityhubLDPath)21 Response (javax.ws.rs.core.Response)20 MediaTypeUtil.getAcceptableMediaType (org.apache.stanbol.commons.web.base.utils.MediaTypeUtil.getAcceptableMediaType)19 URI (java.net.URI)18 Consumes (javax.ws.rs.Consumes)18 OWLOntology (org.semanticweb.owlapi.model.OWLOntology)18 ByteArrayInputStream (java.io.ByteArrayInputStream)16 OWLOntologyID (org.semanticweb.owlapi.model.OWLOntologyID)16 HashSet (java.util.HashSet)14 ImmutableGraph (org.apache.clerezza.commons.rdf.ImmutableGraph)12