Where to store the JWT token?

I am implementing a REST service that requires authentication. I am using JWT .

Now the Android application sends a request at login, receives a token and sends a token in the header for each subsequent request.

My question is how to store a token or where to store it?

  • General settings
  • SQLite Database
  • In file

What would be the best way to do this? Or am I completely wrong about this?

+16
source share
3 answers

I found this ans here ( css )

For example, if you are writing an Android application, you want to save all access tokens in SharedPreferences (here are the API documents necessary for its operation). If you are an iOS developer, you will need to store your access tokens in Keychain .

for ios

for android

+10
source

If you use the REST service and want to keep the JWT, the best way is SharedPreferences . You must save in PrivateMode for security.
SharedPreference and SharedPreference.Editor used to store and retrieve JWT. JWT retrieved after POST request 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 get the JWT from the answer and keep using shared preferences

 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(); } 

Get token from SharedPreference

 private void getToken() { prefs=this.getActivity().getSharedPreferences("myPrefs",Context.MODE_PRIVATE); token = prefs.getString("token",""); } 
+11
source

SharedPreferences is outdated, but now?

0
source

Source: https://habr.com/ru/post/1237813/


All Articles