logic_error logic_error - 1 year ago 81
JSON Question

RESTful Api authentication for an android app

I have an assignment where i need to use an email and password to authenticate a user and get an access token. I have both the api key, secret and the base URL. I am not required to use a redirect URL for the assignment and it wasn't provided. I am not sure which approach or which library to use. I am drowning in the abundance of information and it is confusing me. I need to be pointed in the right direction.... any kind of help will be welcome. Thanks

Answer Source

Based off your comments, the instructions tells you to use Resource Owner Password Credentials Grant. You can see an example request in the spec.

 POST /token HTTP/1.1
 Host: server.example.com
 Authorization: Basic czZCaGRSa3F0MzpnWDFmQmF0M2JW
 Content-Type: application/x-www-form-urlencoded


The only thing that may seem odd (if you've never encountered it), is the Authorization header value. Read up on Basic Authentication. Basically the czZCaGRSa3F0MzpnWDFmQmF0M2JW is a base64 encoding of username:password (actually <client_id>:<client_secret>).

Without using any outside libraries (just standard Java libs) to make the request, you might have something like

String formData = "username=<uname>&password=<pass>&grant_type=password";
String header = "Basic " + Base64.encodeAsString("<client_id>:<client_secret>");

HttpURLConnection connection
                = (HttpURLConnection) new URL(tokenUrl).openConnection();
connection.addRequestProperty("Authorization", header);
connection.addRequestProperty("Content-Type", "application/x-www-form-urlencoded");
connection.setRequestProperty("charset", "utf-8");
connection.setRequestProperty("Content-Length", Integer.toString(formData.length()));

OutputStream out = connection.getOutputStream();

InputStream in = connection.getInputStream();
AccessToken token = new ObjectMapper().readValue(in, AccessToken.class);


The Base64 I used is not a standard library class. Also the ObjectMapper is not a standard library class. I just used it to parse the token response to the AccessToken class. You can use any parser you like. The AccessToken class just has all the possible token values

public class AccessToken {
    public String access_token;
    public String refresh_token;
    public long expires_in;
    public String token_type;
    public String scope;

From there, once you have the token, any resource requests you want to make, you just need to add an Authorization header with Bearer <access_token>.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download