Search in sources :

Example 1 with Consumer

use of com.sun.identity.oauth.service.models.Consumer in project OpenAM by OpenRock.

the class OAuthResourceManager method searchConsumers.

/**
     * Searches for consumer entities from the data store.
     *
     * @param attributes the attribute-value pairs used for the search
     *
     * @return a list of consumers that satisfy the search criteria
     * @throws OAuthServiceException if an error condition occurs
     */
public List<Consumer> searchConsumers(Map<String, String> attributes) throws OAuthServiceException {
    if ((attributes == null) || (attributes.isEmpty())) {
        return null;
    }
    List<String> ids = em.searchEntity(CONSUMER_TYPE, attributes);
    if ((ids == null) || (ids.isEmpty())) {
        return null;
    }
    List<Consumer> consumers = new ArrayList<Consumer>();
    Iterator<String> iter = ids.iterator();
    while (iter.hasNext()) {
        String id = iter.next();
        Consumer consumer = readConsumer(id);
        if (consumer != null) {
            consumers.add(consumer);
        }
    }
    return consumers;
}
Also used : Consumer(com.sun.identity.oauth.service.models.Consumer) ArrayList(java.util.ArrayList)

Example 2 with Consumer

use of com.sun.identity.oauth.service.models.Consumer 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 3 with Consumer

use of com.sun.identity.oauth.service.models.Consumer 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)

Example 4 with Consumer

use of com.sun.identity.oauth.service.models.Consumer in project OpenAM by OpenRock.

the class ConsumerResource method getRegistration.

/**
     * GET method for retrieving a specific Service Consumer instance
     * and obtaining corresponding metadata (consumer name, URI, secret).
     *
     * @param consID The comsumer ID 
     * @param sigmethod {@link String} to choose the signature algorithm
     * of interest (e.g. <PRE>?signature_method=RSA-SHA1</PRE> will return
     * the RSA public key of the service consumer).
     *
     * @return an HTTP response with URL encoded value of the service metadata.
     */
@GET
@Consumes(MediaType.TEXT_PLAIN)
public Response getRegistration(@PathParam(C_ID) String consID, @QueryParam(C_SIGNATURE_METHOD) String sigmethod) {
    OAuthResourceManager oauthResMgr = OAuthResourceManager.getInstance();
    try {
        String name = null;
        String icon = null;
        String ckey = context.getAbsolutePath().toString();
        Map<String, String> searchMap = new HashMap<String, String>();
        searchMap.put(CONSUMER_KEY, ckey);
        List<Consumer> consumers = oauthResMgr.searchConsumers(searchMap);
        if ((consumers == null) || consumers.isEmpty()) {
            throw new WebApplicationException(new Throwable("Consumer key is missing."), BAD_REQUEST);
        }
        Consumer consumer = consumers.get(0);
        String cs = null;
        if (sigmethod != null) {
            if (sigmethod.equalsIgnoreCase(RSA_SHA1.NAME)) {
                cs = URLEncoder.encode(consumer.getConsRsakey());
            } else {
                cs = URLEncoder.encode(consumer.getConsSecret());
            }
        }
        if (consumer.getConsName() != null) {
            name = URLEncoder.encode(consumer.getConsName());
        }
        String resp = C_KEY + "=" + URLEncoder.encode(ckey);
        if (name != null) {
            resp += "&" + C_NAME + "=" + name;
        }
        if (cs != null) {
            resp += "&" + C_SECRET + "=" + cs;
        }
        return Response.ok(resp, MediaType.TEXT_PLAIN).build();
    } catch (OAuthServiceException e) {
        Logger.getLogger(ConsumerResource.class.getName()).log(Level.SEVERE, null, e);
        throw new WebApplicationException(e);
    }
}
Also used : Consumer(com.sun.identity.oauth.service.models.Consumer) WebApplicationException(javax.ws.rs.WebApplicationException) HashMap(java.util.HashMap) Consumes(javax.ws.rs.Consumes) GET(javax.ws.rs.GET)

Example 5 with Consumer

use of com.sun.identity.oauth.service.models.Consumer in project OpenAM by OpenRock.

the class AccessTokenRequest method postAccessTokenRequest.

/**
     * POST method for creating a request for Rquest 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")
public Response postAccessTokenRequest(@Context HttpContext hc, @Context Request req, String content) {
    boolean sigIsOk = false;
    OAuthResourceManager oauthResMgr = OAuthResourceManager.getInstance();
    try {
        Consumer cons = null;
        OAuthServerRequest request = new OAuthServerRequest(hc.getRequest());
        OAuthParameters params = new OAuthParameters();
        params.readRequest(request);
        if (params.getToken() == null)
            throw new WebApplicationException(new Throwable(OAUTH_TOKEN + " MUST be present."), BAD_REQUEST);
        // Check the existence of oauth verifier
        String requestVerifier = params.get(OAUTH_VERIFIER);
        if ((requestVerifier == null) || (requestVerifier.isEmpty())) {
            throw new WebApplicationException(new Throwable(OAUTH_VERIFIER + " MUST be present."), BAD_REQUEST);
        }
        Map<String, String> searchMap = new HashMap<String, String>();
        searchMap.put(REQUEST_TOKEN_URI, params.getToken());
        List<RequestToken> reqTokens = oauthResMgr.searchRequestTokens(searchMap);
        RequestToken rt = null;
        if ((reqTokens != null) && (!reqTokens.isEmpty())) {
            rt = reqTokens.get(0);
        }
        if (rt == null) {
            throw new WebApplicationException(new Throwable("Token invalid."), 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);
        }
        // Check that the verifiers match
        String reqTokenVerifier = rt.getVerifier();
        if (!requestVerifier.equals(reqTokenVerifier)) {
            throw new WebApplicationException(new Throwable("The oauth_verifier parameter is not valid."), BAD_REQUEST);
        }
        cons = rt.getConsumerId();
        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(rt.getReqtSecret());
        try {
            sigIsOk = OAuthSignature.verify(request, params, secrets);
        } catch (OAuthSignatureException ex) {
            Logger.getLogger(AccessTokenRequest.class.getName()).log(Level.SEVERE, null, ex);
        }
        if (!sigIsOk) {
            throw new WebApplicationException(new Throwable("Signature invalid."), BAD_REQUEST);
        }
        // We're good to go.
        AccessToken newtok = new AccessToken();
        newtok.setAcctOnetime((short) 1);
        newtok.setAcctPpalid(rt.getReqtPpalid());
        String baseUri = context.getBaseUri().toString();
        if (baseUri.endsWith("/")) {
            baseUri = baseUri.substring(0, baseUri.length() - 1);
        }
        URI loc = URI.create(baseUri + PathDefs.ACCESS_TOKENS_PATH + "/" + new UniqueRandomString().getString());
        newtok.setAcctUri(loc.toString());
        newtok.setAcctSecret(new UniqueRandomString().getString());
        newtok.setConsumerId(rt.getConsumerId());
        // for now val = uri
        newtok.setAcctVal(newtok.getAcctUri());
        oauthResMgr.createAccessToken(null, newtok);
        oauthResMgr.deleteRequestToken(rt);
        // Preparing the response.
        String resp = OAUTH_TOKEN + "=" + newtok.getAcctVal() + "&" + OAUTH_TOKEN_SECRET + "=" + newtok.getAcctSecret();
        return Response.created(loc).entity(resp).type(MediaType.APPLICATION_FORM_URLENCODED).build();
    } catch (OAuthServiceException e) {
        Logger.getLogger(AccessTokenRequest.class.getName()).log(Level.SEVERE, null, e);
        // 500 error
        throw new WebApplicationException(e);
    }
}
Also used : 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) OAuthServerRequest(com.sun.jersey.oauth.server.OAuthServerRequest) Consumer(com.sun.identity.oauth.service.models.Consumer) RequestToken(com.sun.identity.oauth.service.models.RequestToken) AccessToken(com.sun.identity.oauth.service.models.AccessToken) 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)

Aggregations

Consumer (com.sun.identity.oauth.service.models.Consumer)9 HashMap (java.util.HashMap)5 Consumes (javax.ws.rs.Consumes)5 WebApplicationException (javax.ws.rs.WebApplicationException)5 RequestToken (com.sun.identity.oauth.service.models.RequestToken)3 UniqueRandomString (com.sun.identity.oauth.service.util.UniqueRandomString)3 URI (java.net.URI)3 POST (javax.ws.rs.POST)3 AccessToken (com.sun.identity.oauth.service.models.AccessToken)2 OAuthServerRequest (com.sun.jersey.oauth.server.OAuthServerRequest)2 OAuthParameters (com.sun.jersey.oauth.signature.OAuthParameters)2 OAuthSecrets (com.sun.jersey.oauth.signature.OAuthSecrets)2 OAuthSignatureException (com.sun.jersey.oauth.signature.OAuthSignatureException)2 ParseException (java.text.ParseException)2 Date (java.util.Date)2 MalformedURLException (java.net.MalformedURLException)1 URL (java.net.URL)1 URLEncoder (java.net.URLEncoder)1 ArrayList (java.util.ArrayList)1 List (java.util.List)1