Welcome!

Welcome to the official BlackBerry Support Community Forums.

This is your resource to discuss support topics with your peers, and learn from each other.

inside custom component

Java Development

Reply
Developer
amsiddh
Posts: 142
Registered: ‎06-26-2009
My Device: Not Specified

Re: OAuth / OAuth workaround?

 Hi,

 

In order to process any url request you have to encode according to its standards like space should be replaced with %20.

 

In public static String encode(String s) method of URLUTF8Encoder class comment the else part and try

 

/*else if (ch == ' ') {                   // space
               sbuf.append('+');

}*/

 

Thanks

Please use plain text.
Developer
dev2011
Posts: 17
Registered: ‎08-14-2009
My Device: Not Specified

Re: OAuth / OAuth workaround?

Some more changes to URLUTF8Encoder for Twitter:

 

 

 

      } else if (ch == ' ') {			// space
	      //sbuf.append('+');
	      sbuf.append("%20");
      } else if (ch == '!') {
    	  sbuf.append("%21");
      } else if (ch == '*') {
    	  sbuf.append("%2A");
      } else if (ch == '(') {
    	  sbuf.append("%28");
      } else if (ch == ')') {
    	  sbuf.append("%29");
      } else if (ch == '\'') {
    	  sbuf.append("%27");    	  
      } else if (ch == '-' || ch == '_'		// unreserved
          || ch == '.' 
          || ch == '~' || ch == '*'
          || ch == '\'') {
        sbuf.append((char)ch);

 

 

Please use plain text.
Developer
klerisson
Posts: 78
Registered: ‎12-03-2009
My Device: Not Specified

Re: OAuth / OAuth workaround?

[ Edited ]

Hey again!

 

I really do not understand why some people still embedding those codes we had made up on their projects... I already wrote on this thread that it was just to check the bottlenecks to implement OAuth and to understand the process.

 

My intention was just to give an big picture of the whole process and to proof that is feasible, since a lot of people was struggling (also me) without success so far. The code is really mess up! It just procedural static methods calling each other. If you want to use, use at your own risk. But it will be pretty much better to instead just copy it try to implement something better, it's fairly easy to get something better than those codes.

 

Regards,

--
Feel free to press the kudos button on the left side to thank the user that helped you.
Please mark posts as solved if you found a solution.
Please use plain text.
Contributor
kmbauer
Posts: 47
Registered: ‎06-27-2010
My Device: Bold 9700

Re: OAuth / OAuth workaround?

I am having a really tough time tring to figure out how to sign my OAuth request.  I am tring to follow the example at http://dev.twitter.com/pages/xauth and my signature does not come out the same as it does in the example...

 

I am doing....

 

public static void xauth(){
        try {
            String twitter_url="https://api.twitter.com/oauth/access_token";
            String oauth_consumer_key = "sGNxxnqgZRHUt6NunK3uw";
            String oauth_consumer_secret = "5kEQypKe7lFHnufLtsocB1vAzO07xLFgp2Pc4sp2vk";
            String oauth_nonce = "WLxsobj4rhS2xmCbaAeT4aAkRfx4vSHX4OnYpTE77hA";
            String oauth_signature_method = "HMAC-SHA1";
            String oauth_timestamp = "1276101652";
            String oauth_version = "1.0";
            String x_auth_mode = "client_auth";
            String x_auth_password = "%&123!aZ+()456242134";
            String x_auth_username = "tpFriendlyGiant";
            
            String postBody = "x_auth_mode="+x_auth_mode+"&x_auth_password="+encodeUTF8(x_auth_password)+
                "&x_auth_username="+encodeUTF8(x_auth_username);
            
            String baseString = "POST&"+encodeUTF8(twitter_url)+
                "&oauth_consumer_key%3D"+oauth_consumer_key +
                "%26oauth_nonce%3D"+oauth_nonce+
                "%26oauth_signature_method%3D"+oauth_signature_method+
                "%26oauth_timestamp%3D"+oauth_timestamp+
                "%26oauth_version%3D"+oauth_version+
                "%26"+encodeUTF8(postBody);
            
            String signingSecret = encodeUTF8(oauth_consumer_secret)+"&";
            
            String signature = hmacsha1(signingSecret, baseString);
            
            String header = new StringBuffer("OAuth oauth_nonce=\"").append(oauth_nonce).append("\", oauth_signature_method=\"")
                .append(oauth_signature_method).append("\", oauth_timestamp=\"").append(oauth_timestamp).append("\", oauth_consumer_key=\"")
                .append(oauth_consumer_key).append("\", oauth_signature=\"").append(signature).append("\", oauth_version=\"")
                .append(oauth_version).append("\"").toString();
            
            System.out.println("Header = " + header);
        } catch (CryptoTokenException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (CryptoUnsupportedOperationException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }
    
    private static String hmacsha1(String key, String message) throws CryptoTokenException,
        CryptoUnsupportedOperationException, IOException {
        HMACKey k = new HMACKey(key.getBytes());
        HMAC hmac = new HMAC(k, new SHA1Digest());
        hmac.update(message.getBytes());
        byte[] mac = hmac.getMAC();
        return Base64OutputStream.encodeAsString(mac, 0, mac.length, false, false);
    }

 

Everything matches the example, but when they sign they get...

 

oauth_signature="yUDBrcMMm6ghqBEKCFKVoJPIacU%3D"

 

I get...

 

MUYmiobRdoK6s0ZVqo4xQNNO17w=

 

Can anyone see anything I am doing wrong?

 

Thanks,

Please use plain text.
Developer
schepurny
Posts: 168
Registered: ‎11-22-2009
My Device: 9000 Bold, 8300 Curve

Re: OAuth / OAuth workaround?

Great thread but I'm getting a similar issue and have tried adjusting a number of things. I get the same 401 error issue. I converted my keys to uppercase from the start. Here is my header:

 

In the debugger I see that my url is this:

 

http://twitter.com/oauth/request_token?oauth_consumer_key=7HBKKB21AYQQ2QPHU9ARVQ&oauth_nonce=5756352...

 

And I get this message when I enter it manually:

 

Failed to validate oauth signature and token

 

 

Does anyone have any suggestions?

 

 

 

Please use plain text.
Contributor
kmbauer
Posts: 47
Registered: ‎06-27-2010
My Device: Bold 9700

Re: OAuth / OAuth workaround?

Yeah that is what I get when I put in my real consumer info.  That why I tried to follow the exact example they posted and from what I can tell it did not sign correctly.  That is why I think I may not be doing the HMAC-SHA1 encoding right?

Please use plain text.
Developer
schepurny
Posts: 168
Registered: ‎11-22-2009
My Device: 9000 Bold, 8300 Curve

Re: OAuth / OAuth workaround?

For your issue are you using a hard coded timestamp and nonce? I was told the timestamp must be accurate and the nonce unique.

Please use plain text.
Contributor
kmbauer
Posts: 47
Registered: ‎06-27-2010
My Device: Bold 9700

Re: OAuth / OAuth workaround?

Yes this was just a test to see if I was encoding things correctlly based on the example they give.  Here is the code I am trying to run and I get back a 401 "Failed to validate oauth signature and token" from Twitter....

 

Method to drive the request....

 

 

public static String requestToken(String x_auth_password, String x_auth_username){
        String url = TWITTER_REQUEST_XAUTH_TOKEN;
        HttpConnection httpConn = null;
        InputStream input = null;
        OutputStream os = null;
        try{
        	ConnectionFactory factory = new ConnectionFactory();
        	factory.setPreferredTransportTypes(new int[]{TransportInfo.TRANSPORT_TCP_WIFI,
        			TransportInfo.TRANSPORT_WAP2,
        			TransportInfo.TRANSPORT_BIS_B,
        			TransportInfo.TRANSPORT_MDS,
        			TransportInfo.TRANSPORT_TCP_CELLULAR});

        	ConnectionDescriptor connDesc = factory.getConnection(url);
    		if (connDesc == null) {
    			throw new IOException("Failed to get a http connection");
    		}
    		httpConn = (HttpConnection) connDesc.getConnection();
            httpConn.setRequestMethod(HttpProtocolConstants.HTTP_METHOD_POST);
            httpConn.setRequestProperty("WWW-Authenticate","OAuth realm=http://twitter.com/");
            httpConn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
            String authHeader = getAuthHeader(x_auth_password, x_auth_username);
            httpConn.setRequestProperty("Authorization", authHeader);

            //write post body
            String postBody = postBody(x_auth_password, x_auth_username);
            httpConn.setRequestProperty("Content-Length", Integer.toString(postBody.getBytes().length));
            os = httpConn.openOutputStream();
            os.write(postBody.getBytes());
            //os.flush();
            os.close();
            os = null;
            
            input = httpConn.openDataInputStream();
            int resp = httpConn.getResponseCode();
            //if (resp == HttpConnection.HTTP_OK) {
                StringBuffer buffer = new StringBuffer();
                int ch;
                while ( (ch = input.read()) != -1){
                    buffer.append( (char) ch);
                }
                String content = buffer.toString();
                System.out.println(content);
//                Const.token = content.substring(content.indexOf((Const.OAUTH_TOKEN+"="))+(Const.OAUTH_TOKEN+"=").length(), content.indexOf('&'));
//                Const.tokenSecret = content.substring(content.indexOf((Const.OAUTH_TOKEN_SECRET+"="))+(Const.OAUTH_TOKEN_SECRET+"=").length(), content.length());

           // }
            return content;
        } catch (Exception e) {
            return "exception";
        } finally {
            try {
                httpConn.close();
                input.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

 

 

Methods to construct AUTH header... and post body

 

 

    private static String getAuthHeader(String x_auth_password,
			String x_auth_username) throws UnsupportedEncodingException,
			CryptoTokenException, CryptoUnsupportedOperationException,
			IOException {
		
		String oauth_signature_method = "HMAC-SHA1";
		String oauth_timestamp = String.valueOf(timestamp());
		String oauth_nonce = createNonce(oauth_timestamp);
		String oauth_version = "1.0";
		
		String postBody = postBody(x_auth_password, x_auth_username);
		
		String baseString = "POST&"+encodeUTF8(TWITTER_REQUEST_XAUTH_TOKEN)+
			"&oauth_consumer_key%3D"+OAUTH_CONSUMER_KEY +
			"%26oauth_nonce%3D"+oauth_nonce+
			"%26oauth_signature_method%3D"+oauth_signature_method+
			"%26oauth_timestamp%3D"+oauth_timestamp+
			"%26oauth_version%3D"+oauth_version+
			"%26"+encodeUTF8(postBody);
		
		String signingSecret = encodeUTF8(OAUTH_CONSUMER_SECRET)+"&";
		
		String signature = hmacsha1(signingSecret, baseString);
		
		String header = new StringBuffer("OAuth oauth_nonce=\"").append(oauth_nonce).append("\", oauth_signature_method=\"")
			.append(oauth_signature_method).append("\", oauth_timestamp=\"").append(oauth_timestamp).append("\", oauth_consumer_key=\"")
			.append(OAUTH_CONSUMER_KEY).append("\", oauth_signature=\"").append(signature).append("\", oauth_version=\"")
			.append(oauth_version).append("\"").toString();
		
		System.out.println("Header = " + header);
		
		return header;
	}

	private static String postBody(String x_auth_password, String x_auth_username) {
		String x_auth_mode = "client_auth";
		String postBody = "x_auth_mode="+x_auth_mode+"&x_auth_password="+encodeUTF8(x_auth_password)+
			"&x_auth_username="+encodeUTF8(x_auth_username);
		return postBody;
	}

        private static long timestamp() {
        return new Date().getTime()/1000;
   }
	
	private static String createNonce(String data) {
        return Long.toString(Math.abs(RandomSource.getLong()));
    }

    private static String hmacsha1(String key, String message) throws CryptoTokenException,
        CryptoUnsupportedOperationException, IOException {
        HMACKey k = new HMACKey(key.getBytes());
        HMAC hmac = new HMAC(k, new SHA1Digest());
        hmac.update(message.getBytes());
        byte[] mac = hmac.getMAC();
        return Base64OutputStream.encodeAsString(mac, 0, mac.length, false, false);
    }

 

Anybody see what I am doing fundementilly wrong?  Again why did they make this so difficult :smileysad:

 

 

 

Please use plain text.
Developer
schepurny
Posts: 168
Registered: ‎11-22-2009
My Device: 9000 Bold, 8300 Curve

Re: OAuth / OAuth workaround?

kmbauer, what URLUTF8Encoder are you using? Did you make the changes that the user above suggested?

 

I'm suspecting the encoding too for my issues. For those that got theirs working, did you make the result of the encoding uppercase, or make the keys uppercase first?

Please use plain text.
Developer
raquibulbari
Posts: 137
Registered: ‎09-30-2009
My Device: Torch 9800

Re: OAuth / OAuth workaround?

in order to make it work, I had to make the encoder return capital letters and space character as %20 not as +

----------------------
Press like if you find a message helpful
---------
Please use plain text.