RESTful Api authentication for an android app

18,217

Solution 1

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

 grant_type=password&username=johndoe&password=A3ddj3w

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.setDoOutput(true);
connection.addRequestProperty("Authorization", header);
connection.addRequestProperty("Content-Type", "application/x-www-form-urlencoded");
connection.setRequestMethod("POST");
connection.setRequestProperty("charset", "utf-8");
connection.setRequestProperty("Content-Length", Integer.toString(formData.length()));

OutputStream out = connection.getOutputStream();
out.write(formData.getBytes(StandardCharsets.UTF_8));

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

out.close();
in.close();

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>.

Solution 2

I would recommend you to use the retrofit library to do that.

Let's say your URL base is http://baseurl.com/api and you have to perform a GET request to /login passing the email and password. I am assuming that your API will return a User object as JSON.

Api.java

public interface Api {

    @GET("/login")
    public void login(@Query("email") String email, @Query("password"), Callback<User> callback);

}

Where you need to perform the API call:

Retrofit retrofit = new Retrofit.Builder()
    .setEndpoint("http://baseurl.com")
    .build();

Api api = retrofit.create(Api.class);
api.login(email, password, new Callback<User>() {
    @Override
    public void success(User user, Response response) {
        // login logic
    }

    @Override
    public void failure(RetrofitError error) {
        Log.e("Retrofit", error.getMessage());
    }
});

I hope this example can help you. Don't forget to read the retrofit documentation

Share:
18,217
Admin
Author by

Admin

Updated on June 05, 2022

Comments

  • Admin
    Admin almost 2 years

    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