Reputation: 725
I'm implementing a REST service that requires authentication. I am using JWT.
Now the Android App sends a request when logging in, gets a token, and has to send the token in the header for every subsequent request.
My question is, how to store the token, or where should I store it?
What would be the best practice way to do it? Or am I going about this the totally wrong way?
Upvotes: 41
Views: 28655
Reputation: 1467
If you are using REST service and want to store JWT the best way available is SharedPreferences
.You should store in PrivateMode
for security.
SharedPreference
and SharedPreference.Editor
is used to store and retrieve JWT. JWT is retrieved after POST request of Username and Password
private void makeJsonRequest() {
String json_req = "json_req";
// String url = getContext().getString(R.string.LOGIN_URL);
String url="";
final JSONObject obj=new JSONObject();
try{
obj.put("username",name);
obj.put("password",pass);
}catch (JSONException e)
{
e.printStackTrace();
}
JsonObjectRequest req = new JsonObjectRequest(Request.Method.POST, url, obj,
new Response.Listener<JSONObject>() {
@Override
public void onResponse(JSONObject response) {
}
},
new Response.ErrorListener() {
@Override
public void onErrorResponse(VolleyError error) {
}
}) {
@Override
public Map<String, String> getHeaders() throws AuthFailureError {
Map<String, String> headers = new HashMap<>();
return headers;
}
};
AppController.getInstance().addToRequestQueue(req, json_req);
To retrieve JWT from response and save in shared preference use
SharedPreferences prefs;
SharedPreferences.Editor edit;
prefs=getActivity().getSharedPreferences("myPrefs",Context.MODE_PRIVATE);
edit=prefs.edit();
try {
String saveToken=response.getString("token");
edit.putString("token",saveToken);
Log.i("Login",saveToken);
edit.commit();
}
catch (JSONException e)
{
e.printStackTrace();
}
To get Token from SharedPreference
private void getToken() {
prefs=this.getActivity().getSharedPreferences("myPrefs",Context.MODE_PRIVATE);
String token = prefs.getString("token","");
}
Upvotes: 27
Reputation: 974
I found this ans here (src)
If you’re writing an Android app, for instance, you’ll want to store all access tokens in SharedPreferences
(here’s the API docs you need to make it work). If you’re an iOS developer, you will want to store your access tokens in the Keychain
.
Upvotes: 23