在共享首选项中存储jwt令牌?在整个应用程序中检索值?

mo49yndu  于 2021-07-06  发布在  Java
关注(0)|答案(1)|浏览(320)

到目前为止,我为我的客户做了一个应用程序,现在我集成了laravelapi,我不知道jwt令牌如何在会话中存储并检索到其他活动中。基本上,在成功登录api时创建jwt令牌和响应,我想将其保存在会话中。我能够从result变量中的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);
    }
}
eyh26e7m

eyh26e7m1#

在中添加以下方法 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 方法并传递一个唯一的键(记住在获取令牌时将使用这个键)和值参数passtoken。
用于获取令牌呼叫 getStringData 方法并传递保存令牌时传递的密钥。
根据您的查询添加以上方法后只需编写
1-用于保存令牌:

session.saveStringData ("jwtToken", jObj.getString("result"));

2-用于在应用程序中的任何位置获取令牌,请首先初始化 Session manager 对象,然后调用 getStringData 方法如下。

private SessionManager session; 
session = new SessionManager(getApplicationContext()); 
String token = session.getStringData("jwtToken");

相关问题