令牌认证 Android Studio
Token authentication Android Studio
如果我想将从服务器检索到的令牌存储在一个我可以从我的代码中的任何地方访问它的地方,以便继续将它作为 json header 发送到我的服务器,我应该把它存放在哪里?你有什么其他建议可以让我使用令牌身份验证吗?
将它存储在应用程序的私有 SharedPreferences 中并创建一个静态助手来获取它似乎是安全的。
只有您的应用可以访问它。
from Android API documentation
File creation mode: the default mode, where the created file can only be accessed by the calling application (or all applications sharing the same user ID).
package net.rouk1.helper;
import android.content.Context;
import android.content.SharedPreferences;
public class TokenSaver {
private final static String SHARED_PREF_NAME = "net.rouk1.SHARED_PREF_NAME";
private final static String TOKEN_KEY = "net.rouk1.TOKEN_KEY";
public static String getToken(Context c) {
SharedPreferences prefs = c.getSharedPreferences(SHARED_PREF_NAME, Context.MODE_PRIVATE);
return prefs.getString(TOKEN_KEY, "");
}
public static void setToken(Context c, String token) {
SharedPreferences prefs = c.getSharedPreferences(SHARED_PREF_NAME, Context.MODE_PRIVATE);
SharedPreferences.Editor editor = prefs.edit();
editor.putString(TOKEN_KEY, token);
editor.apply();
}
}
如果我想将从服务器检索到的令牌存储在一个我可以从我的代码中的任何地方访问它的地方,以便继续将它作为 json header 发送到我的服务器,我应该把它存放在哪里?你有什么其他建议可以让我使用令牌身份验证吗?
将它存储在应用程序的私有 SharedPreferences 中并创建一个静态助手来获取它似乎是安全的。 只有您的应用可以访问它。
from Android API documentation
File creation mode: the default mode, where the created file can only be accessed by the calling application (or all applications sharing the same user ID).
package net.rouk1.helper;
import android.content.Context;
import android.content.SharedPreferences;
public class TokenSaver {
private final static String SHARED_PREF_NAME = "net.rouk1.SHARED_PREF_NAME";
private final static String TOKEN_KEY = "net.rouk1.TOKEN_KEY";
public static String getToken(Context c) {
SharedPreferences prefs = c.getSharedPreferences(SHARED_PREF_NAME, Context.MODE_PRIVATE);
return prefs.getString(TOKEN_KEY, "");
}
public static void setToken(Context c, String token) {
SharedPreferences prefs = c.getSharedPreferences(SHARED_PREF_NAME, Context.MODE_PRIVATE);
SharedPreferences.Editor editor = prefs.edit();
editor.putString(TOKEN_KEY, token);
editor.apply();
}
}