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?
To keep them secure, you should always store JWTs inside an httpOnly cookie. This is a special kind of cookie that's only sent in HTTP requests to the server. It's never accessible (both for reading or writing) from JavaScript running in the browser.
If in any case more than one JWT can be generated for a user for a single purpose like an email verification token, or reset password token in those cases we must save the tokens/latest token in DB to match with the most recent one.
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",""); }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With