Android - API requiest oAuth 2.0 using volley for access token generate.

Today we use various type of API to access data and we just need to send a request and API give the response. But for security reason now many API provider use oAuth 2.0 to access data which come from API. But How to request apt with oAuth 2.0 authentication and get the response. That is the main problem to solve by using volley library. We use volley to generate access token by using oAuth 2.0. In this blog we mainly focus on the generating access token with client id and client secret key by the help of oAuth 2.0 using volley.


Introduction to oAuth 2.0

oAuth stand for Open Authorization. you may notice that it is a authorization not authentication which means it decide how much resource use who. Here we oAuth 2.0 use access token to authorize resources on behalf of end-user. Here three think work

  • Client:- The user which use protected recourse. To use resource user must have a access Token.
  • Authorization server:- This server responsible for authorize the use by the help of access token. And also handle  expire access token
  • Resource server:- It protects the user's resources and receive access token from the client and return appropriate resource.

How to generate Access Token using Volley

Access Token are just like a key which create for a small time interval to access resource and after that it expire. Now the question come to how we generate Access Token with the help of Volley. To generate access token by Volley you must have client id and client secret key which provide by the API Website.

Requirement

  1. Client ID
  2. Client Secret key
  3. API token generate URL
  4. Volley dependency to use volley


Generate Access Token using Volley

Below is the code in Java which is use to generate access token with oAuth 2.0 authorization using Volley library.

Create a custom java class name "TokenRequest" and past below code 

TokenRequest.java

import android.util.Base64;

import com.android.volley.AuthFailureError;
import com.android.volley.Response;
import com.android.volley.toolbox.StringRequest;

import java.util.HashMap;
import java.util.Map;

public class TokenRequest extends StringRequest {

    private static final String CLIENT_ID = "your client id";
    private static final String CLIENT_SECRET = "your client secret key";
    public TokenRequest(int method, String url, Response.Listener<String> listener,
                        Response.ErrorListener errorListener) {
        super(method, url, listener, errorListener);
    }

    @Override
    protected Map<String, String> getParams() throws AuthFailureError {
        Map<String, String> params = new HashMap<String, String>();
        params.put("grant_type", "client_credentials");
        return params;
    }

    @Override
    public Map<String, String> getHeaders() throws AuthFailureError {
        Map<String, String> headers = new HashMap<String, String>();
        String auth = "Basic "
                + Base64.encodeToString((CLIENT_ID
                        + ":" + CLIENT_SECRET).getBytes(),
                Base64.NO_WRAP);
        headers.put("Authorization", auth);
        return headers;
    }
}

MainActivity.java

public class MainActivity extends AppCompatActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        RequestQueue queue = Volley.newRequestQueue(getContext());
        TokenRequest tokenRequest = new TokenRequest(Request.Method.POST, "your token generate URL", new Response.Listener<String>() {
            @Override
            public void onResponse(String response) {
                Log.i(TAG, "onResponse: "+response);
                if (!response.isEmpty())
                {
                    Log.i(TAG, "onResponse: "+response);

                }
                else
                {
                    Log.i(TAG, "response is empty");
                }
            }
        }, new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError error) {
                Log.i(TAG, "onErrorResponse:token requiest "+error.getMessage());
            }
        });
        queue.add(tokenRequest);
    }

}

Conclusion 

The above code is just a simple way to generate Access Token of oAuth 2.0 with the help of volley. But also their various method available to to same work.

Post a Comment

Previous Post Next Post

Recent Posts