[英]Where to store a JWT token?
I'm implementing a REST service that requires authentication.我正在实施需要身份验证的 REST 服务。 I am using JWT .
我正在使用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.现在,Android 应用程序在登录时发送请求,获取令牌,并且必须为每个后续请求在标头中发送令牌。
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?
还是我以完全错误的方式解决这个问题?
If you are using REST service and want to store JWT the best way available is SharedPreferences
.You should store in PrivateMode
for security.如果您正在使用 REST 服务并希望存储 JWT,那么可用的最佳方式是
SharedPreferences
。为了安全起见,您应该存储在PrivateMode
中。
SharedPreference
and SharedPreference.Editor
is used to store and retrieve JWT. SharedPreference
和SharedPreference.Editor
用于存储和检索 JWT。 JWT is retrieved after POST request of Username and Password在用户名和密码的POST请求后检索JWT
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从响应中检索 JWT 并保存在共享首选项中使用
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从 SharedPreference 获取令牌
private void getToken() {
prefs=this.getActivity().getSharedPreferences("myPrefs",Context.MODE_PRIVATE);
String token = prefs.getString("token","");
}
I found this ans here ( src )我在这里找到了这个答案( 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).例如,如果您正在编写 Android 应用程序,您需要将所有访问令牌存储在
SharedPreferences
(这里是您需要的 API 文档以使其工作)。 If you're an iOS developer, you will want to store your access tokens in the Keychain
.如果您是 iOS 开发人员,您会希望将您的访问令牌存储在
Keychain
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.