Gonz
Gonz

Reputation: 11

SoundCloud Official Java ApiWrapper, requests with saved token get rejected with 401

I'm able to authenticate correctly and get a valid token when I enter username and password, then I'm intending to store this token so returning users don't have to enter again the username and password.

So when the user comes back,I retrieve the token and create a new instance of the ApiWrapper passing the token as argument, when I make the request it does not work with "401 Unauthorized".

It's obvious that I'm doing something wrong somewhere, but I'm stuck, I can't seem to find the problem here.

I'm storing the Token as string with:

private void storeAccessToken(Token token) {
    SharedPreferences settings = getSharedPreferences(Constants.PREFS_SOUNDCLOUD_NAME, MODE_PRIVATE);
    SharedPreferences.Editor editor = settings.edit();
    editor.putString("accessTokenToken", token.toString());
    editor.commit();
}

Then when I retrieve it, I do this:

private Token getAccessToken() {
    SharedPreferences settings = getSharedPreferences(Constants.PREFS_SOUNDCLOUD_NAME, MODE_PRIVATE);
    String token = settings.getString("accessTokenToken", "");
    if (token!=null && !"".equals(token)){
        return new Token(token, "refresh_token");
    }
    return null;
}

I retrieve the token from the ApiWrapper instance, and it's not NULL.

Any hints or examples will be highly appreciated,

Thanks in advance.

Upvotes: 0

Views: 323

Answers (1)

Gonz
Gonz

Reputation: 11

Ok, I finally found the problem. The way I was storing the token was wrong. The method Token.toString(), it's really meant for logging purposes, and nothing else.

This is how I'm storing and retrieving the token now:

private void storeAccessToken(Token token) {
    SharedPreferences settings = getSharedPreferences(Constants.PREFS_SOUNDCLOUD_NAME, MODE_PRIVATE);
    SharedPreferences.Editor editor = settings.edit();
    editor.putString("access", token.access);
    editor.putString("refresh", token.refresh); 
    editor.commit();
}

private Token getAccessToken() {
    SharedPreferences settings = getSharedPreferences(Constants.PREFS_SOUNDCLOUD_NAME, MODE_PRIVATE);
    String access = settings.getString("access", "");
    String refresh = settings.getString("refresh", "");
    if (access!=null && refresh!=null && !"".equals(access) && !"".equals(refresh)){
        return new Token(access, refresh);
    }
    return null;
}

Thanks

Upvotes: 1

Related Questions