19 Aug 2011

Twitter oAuth and the net.oauth.j2me library

So I have been toying with a twitter mobile client in Java. I'm using the j2me-oauth library to perform authentication, sign requests and the all the oAuth ish. Everything seems to be working perfectly except that tweeting fails occasionally, returning 401 Unauthorized error. It's clear from the dev docs that it is an authentication credential problem and most likely has to do with the oauth signature. I spent some time debugging how the library performs the oauth signing and noticed the encoding of some characters are skipped. The encoding should actually include all non-alphanumeric characters except -_. with ~ converted to %7E.

My simple workaround is replacing the unreservedCharacters in net.oauth.j2me.OAuthParameterEncoder with

1
//private String unreservedCharacters = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789-._~";<br />private String unreservedCharacters = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789-._";

and comment out some lines in net.oauth.j2me.Util

1
2
3
4
5
6
7
8
9
10
11
12
13
    } else if (
        // safe characters
        c == '-'
        || c == '_'
        || c == '.'
        //|| c == '!'
        //|| c == '~'
        //|| c == '*'
        //|| c == '\''
        //|| c == '('
        //|| c == ')'
        || (c &gt;= 'A' &amp;&amp; c &lt;= 'Z')
        || (c &gt;= 'a' &amp;&amp; c &lt;= 'z') ) {

Here is a zip of both files: http://cl.ly/9RNJ

My name is Opeyemi Obembe. I build things for web and mobile. You should follow me on Twitter (@kehers).