Where to store a JWT token?
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","");
}
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
.
for ios
for android