将 JWT 令牌存储在共享首选项中?并在整个应用程序中检索价值?
Posted
技术标签:
【中文标题】将 JWT 令牌存储在共享首选项中?并在整个应用程序中检索价值?【英文标题】:Store JWT token in shared preference? And retrieve value in whole app? 【发布时间】:2021-03-07 23:19:15 【问题描述】:到目前为止,我为我的客户制作了一个应用程序,现在我集成了 laravel API 我不明白 JWT 令牌如何在会话中存储并检索到其他活动中的方式。基本上,在成功登录 API 创建 JWT 令牌和响应时,我想将其保存在会话中。我能够从结果变量中的 JSON 对象中检索令牌并将其显示到日志中,但我找不到如何将令牌存储到会话中然后检索到我的所有应用程序的方法。 在我的代码下方:
public class LoginActivity extends Activity
private static final String TAG = RegisterActivity.class.getSimpleName();
private Button btnLogin;
private Button btnLinkToRegister;
private EditText inputEmail;
private EditText inputPassword;
private ProgressDialog pDialog;
private SessionManager session;
private SQLiteHandler db;
String result;
@Override
public void onCreate(Bundle savedInstanceState)
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_login);
inputEmail = (EditText) findViewById(R.id.email);
inputPassword = (EditText) findViewById(R.id.password);
btnLogin = (Button) findViewById(R.id.btnLogin);
// Progress dialog
pDialog = new ProgressDialog(this);
pDialog.setCancelable(false);
// Session manager
session = new SessionManager(getApplicationContext());
// Check if user is already logged in or not
if (session.isLoggedIn())
// User is already logged in. Take him to main activity
Intent intent = new Intent(LoginActivity.this, MainActivity.class);
startActivity(intent);
finish();
btnLogin.setOnClickListener(new View.OnClickListener()
public void onClick(View view)
String email = inputEmail.getText().toString().trim();
String password = inputPassword.getText().toString().trim();
// Check for empty data in the form
if (!email.isEmpty() && !password.isEmpty())
// login user
checkLogin(email, password);
else
// Prompt user to enter credentials
Toast.makeText(getApplicationContext(),
"Please enter the credentials!", Toast.LENGTH_LONG)
.show();
);
/**
* function to verify login details in mysql db
* */
private void checkLogin(final String email, final String password)
// Tag used to cancel the request
String tag_string_req = "req_login";
pDialog.setMessage("Logging in ...");
showDialog();
StringRequest strReq = new StringRequest(Method.POST,
AppConfig.URL_LOGIN, new Response.Listener<String>()
@Override
public void onResponse(String response)
Log.e(TAG, "Login Response: " + response.toString());
hideDialog();
try
JSONObject jObj = new JSONObject(response);
boolean error = jObj.getBoolean("error");
// Check for error node in json
if (!error)
// user successfully logged in
// Create login session
session.setLogin(true);
//This is status api returned e.g 200 etc
Integer status = jObj.getInt("status");
//this is my token variable in this variable jwt is stored but how to store this variable in shared preferances.
String result = jObj.getString("result");
Log.d(TAG, "Login Response: " + status.toString());
Log.e(TAG,"Token "+result.toString());
if(status == 200)
Intent intent = new Intent(LoginActivity.this,
MainActivity.class);
//intent.putExtra("full_name", name);
intent.putExtra("result", result.toString());
startActivity(intent);
finish();
else
// Error in login. Get the error message
String errorMsg = jObj.getString("error_msg");
Toast.makeText(getApplicationContext(),
errorMsg, Toast.LENGTH_LONG).show();
catch (JSONException e)
// JSON error
e.printStackTrace();
Toast.makeText(getApplicationContext(), "Json error: " + e.getMessage(), Toast.LENGTH_LONG).show();
, new Response.ErrorListener()
@Override
public void onErrorResponse(VolleyError error)
Log.e(TAG, "Login Error: " + error.getMessage());
Toast.makeText(getApplicationContext(),
error.getMessage(), Toast.LENGTH_LONG).show();
hideDialog();
)
@Override
protected Map<String, String > getParams()
// Posting parameters to login url
Map<String, String> params = new HashMap<String, String>();
params.put("email", email);
params.put("password", password);
//params.put("result", result);
return params;
;
// Adding request to request queue
AppController.getInstance().addToRequestQueue(strReq, tag_string_req);
private void showDialog()
if (!pDialog.isShowing())
pDialog.show();
private void hideDialog()
if (pDialog.isShowing())
pDialog.dismiss();
这是我的共享偏好类代码:
public class SessionManager
// LogCat tag
private static String TAG = SessionManager.class.getSimpleName();
// Shared Preferences
SharedPreferences pref;
Editor editor;
Context _context;
// Shared pref mode
int PRIVATE_MODE = 0;
// Shared preferences file name
private static final String PREF_NAME = "androidHiveLogin";
private static final String KEY_IS_LOGGED_IN = "isLoggedIn";
public SessionManager(Context context)
this._context = context;
pref = _context.getSharedPreferences(PREF_NAME, PRIVATE_MODE);
editor = pref.edit();
public void setLogin(boolean isLoggedIn)
editor.putBoolean(KEY_IS_LOGGED_IN, isLoggedIn);
// commit changes
editor.commit();
Log.d(TAG, "User login session modified!");
public boolean isLoggedIn()
return pref.getBoolean(KEY_IS_LOGGED_IN, false);
【问题讨论】:
【参考方案1】:在SessionManager
类中添加以下方法
//Save String data to Shared Prefs
public boolean saveStringData(String key, String value)
SharedPreferences.Editor editor=mSharedPref.edit ();
editor.putString (key, value);
return editor.commit ();
public String getStringData(String key)
String value=mSharedPref.getString (key, "");
return value;
现在在保存令牌时调用saveStringData
方法并传递唯一键(记住获取令牌时将使用此键)并在值参数中传递令牌。
用于获取令牌调用getStringData
方法并传递您在保存令牌时传递的密钥。
添加上述方法后根据您的查询只需编写
1- 用于保存令牌:
session.saveStringData ("jwtToken", jObj.getString("result"));
2- 要在应用程序的任何位置获取令牌,首先初始化 Session manager
对象,然后调用 getStringData
方法,如下所示。
private SessionManager session;
session = new SessionManager(getApplicationContext());
String token = session.getStringData("jwtToken");
【讨论】:
是的,我看到了这个 sn-p,但我一个字都不懂,因为我对 android 世界很陌生。我不明白如何从这些函数中保存和检索数据 您的问题解决了吗?请将此标记为真实 是的,但现在我想将它发送到 API 的标头中,不知道怎么做 在那里调用 getStringData("jwtToken") 很简单。你可以在任何你想获取令牌的地方调用这个方法并通过!!。我认为您之前的查询现在已解决,将其标记为 true。 好的,但请告诉我如何将此令牌和 ID 发送到下一个活动以上是关于将 JWT 令牌存储在共享首选项中?并在整个应用程序中检索价值?的主要内容,如果未能解决你的问题,请参考以下文章
如何在不使用共享首选项的情况下将数据存储为颤动的对象[关闭]