Search in sources :

Example 81 with Consumes

use of javax.ws.rs.Consumes in project OpenAM by OpenRock.

the class RequestTokenRequest method postReqTokenRequest.

/**
     * POST method for creating a request for a Request Token
     * @param content representation for the resource
     * @return an HTTP response with content of the updated or created resource.
     */
@POST
@Consumes("application/x-www-form-urlencoded")
@Produces("application/x-www-form-urlencoded")
public Response postReqTokenRequest(@Context HttpContext hc, String content) {
    boolean sigIsOk = false;
    OAuthResourceManager oauthResMgr = OAuthResourceManager.getInstance();
    try {
        OAuthServerRequest request = new OAuthServerRequest(hc.getRequest());
        OAuthParameters params = new OAuthParameters();
        params.readRequest(request);
        String tok = params.getToken();
        if ((tok != null) && (!tok.contentEquals("")))
            throw new WebApplicationException(new Throwable(OAUTH_TOKEN + " MUST not be present."), BAD_REQUEST);
        String conskey = params.getConsumerKey();
        if (conskey == null) {
            throw new WebApplicationException(new Throwable("Consumer key is missing."), BAD_REQUEST);
        }
        String signatureMethod = params.getSignatureMethod();
        if (signatureMethod == null) {
            throw new WebApplicationException(new Throwable("Signature Method is missing."), BAD_REQUEST);
        }
        String callback = params.get(OAUTH_CALLBACK);
        if ((callback == null) || (callback.isEmpty())) {
            throw new WebApplicationException(new Throwable("Callback URL is missing."), BAD_REQUEST);
        }
        if (!callback.equals(OAUTH_OOB)) {
            try {
                URL url = new URL(callback);
            } catch (MalformedURLException me) {
                throw new WebApplicationException(new Throwable("Callback URL is not valid."), BAD_REQUEST);
            }
        }
        Map<String, String> searchMap = new HashMap<String, String>();
        searchMap.put(CONSUMER_KEY, conskey);
        List<Consumer> consumers = oauthResMgr.searchConsumers(searchMap);
        if ((consumers != null) && (!consumers.isEmpty())) {
            cons = consumers.get(0);
        }
        if (cons == null) {
            throw new WebApplicationException(new Throwable("Consumer key invalid or service not registered"), BAD_REQUEST);
        }
        String secret = null;
        if (signatureMethod.equalsIgnoreCase(RSA_SHA1.NAME)) {
            secret = cons.getConsRsakey();
        } else {
            secret = cons.getConsSecret();
        }
        OAuthSecrets secrets = new OAuthSecrets().consumerSecret(secret).tokenSecret("");
        try {
            sigIsOk = OAuthSignature.verify(request, params, secrets);
        } catch (OAuthSignatureException ex) {
            Logger.getLogger(RequestTokenRequest.class.getName()).log(Level.SEVERE, null, ex);
        }
        if (!sigIsOk)
            throw new WebApplicationException(new Throwable("Signature invalid."), BAD_REQUEST);
        // We're good to go.
        RequestToken rt = new RequestToken();
        rt.setConsumerId(cons);
        String baseUri = context.getBaseUri().toString();
        if (baseUri.endsWith("/")) {
            baseUri = baseUri.substring(0, baseUri.length() - 1);
        }
        URI loc = URI.create(baseUri + PathDefs.REQUEST_TOKENS_PATH + "/" + new UniqueRandomString().getString());
        rt.setReqtUri(loc.toString());
        rt.setReqtSecret(new UniqueRandomString().getString());
        // Same value for now
        rt.setReqtVal(loc.toString());
        // Set the callback URL
        rt.setCallback(callback);
        //oauthResMgr.createConsumer(null, cons);
        oauthResMgr.createRequestToken(null, rt);
        String resp = OAUTH_TOKEN + "=" + rt.getReqtVal() + "&" + OAUTH_TOKEN_SECRET + "=" + rt.getReqtSecret() + "&" + OAUTH_CALLBACK_CONFIRMED + "=true";
        return Response.created(loc).entity(resp).type(MediaType.APPLICATION_FORM_URLENCODED).build();
    } catch (OAuthServiceException e) {
        Logger.getLogger(RequestTokenRequest.class.getName()).log(Level.SEVERE, null, e);
        throw new WebApplicationException(e);
    }
}
Also used : MalformedURLException(java.net.MalformedURLException) UniqueRandomString(com.sun.identity.oauth.service.util.UniqueRandomString) WebApplicationException(javax.ws.rs.WebApplicationException) HashMap(java.util.HashMap) UniqueRandomString(com.sun.identity.oauth.service.util.UniqueRandomString) URI(java.net.URI) URL(java.net.URL) OAuthServerRequest(com.sun.jersey.oauth.server.OAuthServerRequest) Consumer(com.sun.identity.oauth.service.models.Consumer) RequestToken(com.sun.identity.oauth.service.models.RequestToken) OAuthParameters(com.sun.jersey.oauth.signature.OAuthParameters) OAuthSignatureException(com.sun.jersey.oauth.signature.OAuthSignatureException) OAuthSecrets(com.sun.jersey.oauth.signature.OAuthSecrets) POST(javax.ws.rs.POST) Consumes(javax.ws.rs.Consumes) Produces(javax.ws.rs.Produces)

Example 82 with Consumes

use of javax.ws.rs.Consumes in project OpenAM by OpenRock.

the class RequestTokenResource method deleteReqtoken.

@DELETE
@Consumes(MediaType.TEXT_PLAIN)
public Response deleteReqtoken() {
    OAuthResourceManager oauthResMgr = OAuthResourceManager.getInstance();
    try {
        String tokenuri = context.getAbsolutePath().toString();
        Map<String, String> searchMap = new HashMap<String, String>();
        searchMap.put(REQUEST_TOKEN_URI, tokenuri);
        List<RequestToken> reqTokens = oauthResMgr.searchRequestTokens(searchMap);
        RequestToken token = null;
        if ((reqTokens != null) && (!reqTokens.isEmpty())) {
            token = reqTokens.get(0);
        }
        if (token == null) {
            return Response.status(UNAUTHORIZED).build();
        }
        oauthResMgr.deleteRequestToken(token);
        return Response.ok().build();
    } catch (OAuthServiceException e) {
        Logger.getLogger(RequestTokenResource.class.getName()).log(Level.SEVERE, null, e);
        throw new WebApplicationException(e);
    }
}
Also used : WebApplicationException(javax.ws.rs.WebApplicationException) HashMap(java.util.HashMap) RequestToken(com.sun.identity.oauth.service.models.RequestToken) DELETE(javax.ws.rs.DELETE) Consumes(javax.ws.rs.Consumes)

Example 83 with Consumes

use of javax.ws.rs.Consumes in project OpenAM by OpenRock.

the class CoreTokenResource method createToken.

/**
     * Creates a token.
     *
     * @param headers HTTPHeaders object of the request.
     * @param request HTTPServletRequest object of the request.
     * @param msgBody Message body containing the JSON-encoded token attributes.
     * @return JSON-encoded token.id attribute of the new token.
     */
@POST
@Consumes("application/json")
@Produces("application/json")
public Response createToken(@Context HttpHeaders headers, @Context HttpServletRequest request, String msgBody) {
    String newTokenId = null;
    JSONObject json = null;
    try {
        json = new JSONObject(msgBody);
        String tokenVal = CoreTokenStoreFactory.getInstance().createToken(CoreTokenUtils.getAdminSubject(), json);
        // retrieve token.id attribute and set as part of Location header
        JSONObject jObj = new JSONObject(tokenVal);
        newTokenId = jObj.getJSONArray(CoreTokenConstants.TOKEN_ID).getString(0);
        Response.ResponseBuilder builder = Response.status(201);
        builder.entity(tokenVal);
        builder.type("application/json");
        builder.header("Location", request.getRequestURL() + "/" + newTokenId);
        Response retResponse = builder.build();
        // logging
        // TODO : get the request session and used in login field
        String[] data = new String[] { json.getJSONArray(CoreTokenConstants.TOKEN_TYPE).toString(), json.getJSONArray(CoreTokenConstants.TOKEN_SUBJECT).toString(), json.names().toString() };
        TokenLogUtils.access(Level.INFO, TokenLogUtils.TOKEN_CREATE_SUCCESS, data, null, newTokenId);
        return retResponse;
    } catch (JSONException ex) {
        CoreTokenUtils.debug.error("CoreTokenResource.createToken", ex);
        String[] data = null;
        if (json != null) {
            try {
                data = new String[] { ex.getLocalizedMessage(), json.getJSONArray(CoreTokenConstants.TOKEN_TYPE).toString(), json.getJSONArray(CoreTokenConstants.TOKEN_SUBJECT).toString(), json.names().toString() };
            } catch (JSONException ex1) {
            }
        } else {
            data = new String[] { ex.getLocalizedMessage(), "", "", "" };
        }
        TokenLogUtils.error(Level.INFO, TokenLogUtils.UNABLE_TO_CREATE_TOKEN, data, null, newTokenId);
        throw getWebApplicationException(ex, MimeType.PLAIN);
    } catch (CoreTokenException ce) {
        CoreTokenUtils.debug.error("CoreTokenResource.createToken", ce);
        String[] data = null;
        if (json != null) {
            try {
                data = new String[] { ce.getLocalizedMessage(), json.getJSONArray(CoreTokenConstants.TOKEN_TYPE).toString(), json.getJSONArray(CoreTokenConstants.TOKEN_SUBJECT).toString(), json.names().toString() };
            } catch (JSONException ex1) {
            }
        } else {
            data = new String[] { ce.getLocalizedMessage(), "", "", "" };
        }
        TokenLogUtils.error(Level.INFO, TokenLogUtils.UNABLE_TO_CREATE_TOKEN, data, null, newTokenId);
        throw getWebApplicationException(headers, ce);
    }
}
Also used : Response(javax.ws.rs.core.Response) JSONObject(org.json.JSONObject) JSONException(org.json.JSONException) CoreTokenException(com.sun.identity.coretoken.CoreTokenException) POST(javax.ws.rs.POST) Consumes(javax.ws.rs.Consumes) Produces(javax.ws.rs.Produces)

Example 84 with Consumes

use of javax.ws.rs.Consumes in project OpenAM by OpenRock.

the class CoreTokenResource method updateToken.

/**
     * Updates a token.
     *
     * @param headers HTTPHeaders object of the request.
     * @param request HTTPServletRequest object of the request.
     * @param tokenId value of token.id in the request path parameter.
     * @param eTag value of the If-Match header in the request.
     * @param msgBody Message body containing the JSON-encoded token attributes.
     */
@PUT
@Consumes("application/json")
@Path("{token.id}")
public void updateToken(@Context HttpHeaders headers, @Context HttpServletRequest request, @PathParam("token.id") String tokenId, @HeaderParam("If-Match") String eTag, String msgBody) {
    try {
        JSONObject jObj = new JSONObject(msgBody);
        CoreTokenStoreFactory.getInstance().updateToken(CoreTokenUtils.getAdminSubject(), tokenId, eTag, jObj);
        // logging
        String[] data = new String[] { jObj.names().toString() };
        TokenLogUtils.access(Level.INFO, TokenLogUtils.TOKEN_UPDATE_SUCCESS, data, null, tokenId);
    } catch (CoreTokenException ce) {
        CoreTokenUtils.debug.error("CoreTokenResource.updateToken", ce);
        String[] data = new String[] { ce.getLocalizedMessage() };
        TokenLogUtils.error(Level.INFO, TokenLogUtils.UNABLE_TO_UPDATE_TOKEN, data, null, tokenId);
        throw getWebApplicationException(headers, ce);
    } catch (JSONException je) {
        CoreTokenUtils.debug.error("CoreTokenResource.updateToken", je);
        String[] data = new String[] { je.getLocalizedMessage() };
        TokenLogUtils.error(Level.INFO, TokenLogUtils.UNABLE_TO_UPDATE_TOKEN, data, null, tokenId);
        throw getWebApplicationException(je, MimeType.PLAIN);
    }
}
Also used : JSONObject(org.json.JSONObject) CoreTokenException(com.sun.identity.coretoken.CoreTokenException) JSONException(org.json.JSONException) Path(javax.ws.rs.Path) Consumes(javax.ws.rs.Consumes) PUT(javax.ws.rs.PUT)

Example 85 with Consumes

use of javax.ws.rs.Consumes in project OpenAM by OpenRock.

the class ConsumerRequest method postConsumerRegistrations.

/**
     * POST method for registering a Service Consumer
     * and obtaining corresponding consumer key & secret.
     *
     * @param formParams {@link String} containing the service 
     * consumer's description.
     * This description takes the form of name=value pairs separated by &.
     * The following parameters are supported:
     * <OL>
     * <LI>name - the service consumer's name.</LI>
     * <LI>icon - the service consumer's URI for its icon (MUST be unique).</LI>
     * <LI>service - the service consumer's URI for its service</LI>
     * <LI>rsapublickey - (optional) the RSA public key of the Service Consumer.</LI>
     * </OL>
     * <p>
     *
     * Example of string:
     * <pre>
     *  name=Service XYZ&icon=http://www.example.com/icon.jpg&service=http://www.example.com
     * </pre>
     *
     *
     * @return an HTTP response with content of the created resource.
     * The location URI is set to the newly created OAuth consumer key.
     * The body of the response is of the form:
     * <pre>
     * consumer_key=http://serviceprovider/0123456762121
     * consumer_secret=12345633
     * </pre>
     * Both values are URL encoded.
     */
@POST
@Consumes("application/x-www-form-urlencoded")
public Response postConsumerRegistrations(MultivaluedMap<String, String> formParams) {
    OAuthResourceManager oauthResMgr = OAuthResourceManager.getInstance();
    try {
        Consumer cons = new Consumer();
        String cert = null;
        String tmpsecret = null;
        Boolean keyed = false;
        Set<String> pnames = formParams.keySet();
        Iterator<String> iter = pnames.iterator();
        Encoder enc = ESAPI.encoder();
        Validator validator = ESAPI.validator();
        while (iter.hasNext()) {
            String key = iter.next();
            String val = formParams.getFirst(key);
            if (key.equalsIgnoreCase(C_NAME)) {
                String consumerName = enc.canonicalize(val);
                if (!validator.isValidInput(C_NAME, consumerName, "HTTPParameterValue", 512, true)) {
                    String resp = "Invalid name entered entered. Please try again.";
                    return Response.ok().entity(resp).type(MediaType.APPLICATION_FORM_URLENCODED).build();
                }
                // Check if a consumer with the same name is already registered,
                // if so, will not do the registration again.
                Map<String, String> searchMap = new HashMap<String, String>();
                searchMap.put(CONSUMER_NAME, consumerName);
                List<Consumer> consumers = oauthResMgr.searchConsumers(searchMap);
                if ((consumers != null) && (!consumers.isEmpty())) {
                    String resp = "A consumer is already registered with name " + enc.encodeForHTML(consumerName) + ".";
                    return Response.ok().entity(resp).type(MediaType.APPLICATION_FORM_URLENCODED).build();
                }
                cons.setConsName(consumerName);
            } else if (key.equalsIgnoreCase(C_CERT)) {
                // The cert is in PEM format (no URL decode needed)
                cert = val;
            } else if (key.equalsIgnoreCase(C_SECRET)) {
                tmpsecret = URLDecoder.decode(val);
            } else if (key.equalsIgnoreCase(C_KEY)) {
                keyed = true;
                String consumerKey = enc.canonicalize(val);
                if (!validator.isValidInput(C_KEY, consumerKey, "HTTPParameterValue", 512, true)) {
                    String resp = "Invalid key entered entered. Please try again.";
                    return Response.ok().entity(resp).type(MediaType.APPLICATION_FORM_URLENCODED).build();
                }
                // Check if a consumer with the same key is already registered,
                // if so, will not do the registration again.
                cons.setConsKey(consumerKey);
                Map<String, String> searchMap = new HashMap<String, String>();
                searchMap.put(CONSUMER_KEY, consumerKey);
                List<Consumer> consumers = oauthResMgr.searchConsumers(searchMap);
                if ((consumers != null) && (!consumers.isEmpty())) {
                    String resp = "A consumer is already registered with key " + enc.encodeForHTML(consumerKey) + ".";
                    return Response.ok().entity(resp).type(MediaType.APPLICATION_FORM_URLENCODED).build();
                }
            } else {
            // anything else is ignored for the time being
            }
        }
        if (cert != null) {
            cons.setConsRsakey(cert);
        }
        if (tmpsecret != null) {
            cons.setConsSecret(tmpsecret);
        } else {
            cons.setConsSecret(new UniqueRandomString().getString());
        }
        if (!keyed) {
            String baseUri = context.getBaseUri().toString();
            if (baseUri.endsWith("/"))
                baseUri = baseUri.substring(0, baseUri.length() - 1);
            URI loc = URI.create(baseUri + PathDefs.CONSUMERS_PATH + "/" + new UniqueRandomString().getString());
            String consKey = loc.toString();
            cons.setConsKey(consKey);
        }
        oauthResMgr.createConsumer(null, cons);
        String resp = "consumer_key=" + URLEncoder.encode(cons.getConsKey()) + "&consumer_secret=" + URLEncoder.encode(cons.getConsSecret());
        return Response.created(URI.create(cons.getConsKey())).entity(resp).type(MediaType.APPLICATION_FORM_URLENCODED).build();
    } catch (OAuthServiceException e) {
        Logger.getLogger(ConsumerRequest.class.getName()).log(Level.SEVERE, null, e);
        throw new WebApplicationException(e);
    } catch (IntrusionException e) {
        Logger.getLogger(ConsumerRequest.class.getName()).log(Level.SEVERE, null, e);
        throw new WebApplicationException(e);
    } catch (EncodingException e) {
        Logger.getLogger(ConsumerRequest.class.getName()).log(Level.SEVERE, null, e);
        throw new WebApplicationException(e);
    }
}
Also used : UniqueRandomString(com.sun.identity.oauth.service.util.UniqueRandomString) WebApplicationException(javax.ws.rs.WebApplicationException) HashMap(java.util.HashMap) EncodingException(org.owasp.esapi.errors.EncodingException) UniqueRandomString(com.sun.identity.oauth.service.util.UniqueRandomString) URI(java.net.URI) Consumer(com.sun.identity.oauth.service.models.Consumer) Encoder(org.owasp.esapi.Encoder) URLEncoder(java.net.URLEncoder) List(java.util.List) IntrusionException(org.owasp.esapi.errors.IntrusionException) HashMap(java.util.HashMap) Map(java.util.Map) MultivaluedMap(javax.ws.rs.core.MultivaluedMap) Validator(org.owasp.esapi.Validator) POST(javax.ws.rs.POST) Consumes(javax.ws.rs.Consumes)

Aggregations

Consumes (javax.ws.rs.Consumes)1610 Path (javax.ws.rs.Path)1243 Produces (javax.ws.rs.Produces)1233 POST (javax.ws.rs.POST)917 ApiOperation (io.swagger.annotations.ApiOperation)508 ApiResponses (io.swagger.annotations.ApiResponses)445 PUT (javax.ws.rs.PUT)439 GET (javax.ws.rs.GET)224 CheckPermission (com.emc.storageos.security.authorization.CheckPermission)215 URI (java.net.URI)207 IOException (java.io.IOException)160 ArrayList (java.util.ArrayList)142 WebApplicationException (javax.ws.rs.WebApplicationException)142 Response (javax.ws.rs.core.Response)140 Authorizable (org.apache.nifi.authorization.resource.Authorizable)100 DELETE (javax.ws.rs.DELETE)87 TimedResource (org.killbill.commons.metrics.TimedResource)84 CallContext (org.killbill.billing.util.callcontext.CallContext)83 Timed (com.codahale.metrics.annotation.Timed)78 HashMap (java.util.HashMap)78