Search code examples
javakotlinreddit

Getting Null Access Token for JRaw


Per my understanding, the OAuthHelper in Jraw should automatically generate an access token when I run this piece of code, but it's not. What am I doing wrong? I'm putting a random value in the app Platform field. Does this matter?

public static void main(String[] args) {
    UserAgent userAgent = new UserAgent(
            "appPlatform",
           "appName",
            "version",
            "userName");

    Credentials credentials = Credentials.script(
           "userName",
            "password",
            "clientId",
            "clientSecret"
    );

    NetworkAdapter adapter = new OkHttpNetworkAdapter(userAgent);
    RedditClient redditClient = OAuthHelper.automatic(adapter, credentials);

    // frontPage() returns a Paginator.Builder
    DefaultPaginator<Submission> frontPage = redditClient.frontPage()
            .sorting(SubredditSort.TOP)
            .timePeriod(TimePeriod.DAY)
            .limit(30)
            .build();

    Listing<Submission> submissions = frontPage.next();
    for (Submission s : submissions) {
        System.out.println(s.getTitle());
    }
}

Here is the stack trace:

Exception in thread "main" java.lang.NullPointerException: Null accessToken at net.dean.jraw.models.internal.$AutoValue_OAuthDataJson.($AutoValue_OAuthDataJson.java:23) at net.dean.jraw.models.internal.AutoValue_OAuthDataJson.(AutoValue_OAuthDataJson.java:15) at net.dean.jraw.models.internal.AutoValue_OAuthDataJson$MoshiJsonAdapter.fromJson(AutoValue_OAuthDataJson.java:64) at net.dean.jraw.models.internal.AutoValue_OAuthDataJson$MoshiJsonAdapter.fromJson(AutoValue_OAuthDataJson.java:18) at com.squareup.moshi.JsonAdapter.fromJson(JsonAdapter.java:41) at net.dean.jraw.http.HttpResponse.deserializeWith(HttpResponse.kt:49) at net.dean.jraw.oauth.OAuthHelper.scriptOAuthData$lib(OAuthHelper.kt:96) at net.dean.jraw.oauth.OAuthHelper.automatic(OAuthHelper.kt:32) at net.dean.jraw.oauth.OAuthHelper.automatic$default(OAuthHelper.kt:27) at net.dean.jraw.oauth.OAuthHelper.automatic(OAuthHelper.kt) at com.signalscanner.reddit.RedditAuthenticator.main(RedditAuthenticator.java:34)

It should be noted RedditAuthenticator.java:34 is this line:

RedditClient redditClient = OAuthHelper.automatic(adapter, credentials);


Solution

  • I believe I've found the cause for this. When you're creating your app in Reddit you need to select Script here in this section:

    enter image description here

    I was debugging JRAW to see what it's doing and when it's building the HTTP request to send to Reddit it's adding a parameter for your applications' type. I don't know if you can somehow configure JRAW to use any of the other types but the default it uses is 'Script'

    Edit: More info on different Authentication schemes for JRAW can be found here - https://mattbdean.gitbooks.io/jraw/content/v/v1.1.0/oauth2.html