Reputation: 39
So far I made an app for my customer and now I integrate laravel API I don't understand the way how JWT tokens store in session and retrieve into other activities. Basically, on successful login API create JWT token and response I want to save it in session. I am able to retrieve the token from the JSON object in the result variable and I display it into logs but I don't find the way how I can store the token into session and then retrieve into all my app. Below my code :
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();
}
}
This is my shared preferences class code :
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);
}
}
Upvotes: 0
Views: 1463
Reputation: 509
Add below methods in SessionManager
class
//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;
}
Now on saving token call saveStringData
method and pass a unique key (Remember on getting token this key will be used) and in value parameter pass token.
For getting token call getStringData
method and pass that key which you passed when you saved token.
According to your query after adding above methods just write
1- For saving token :
session.saveStringData ("jwtToken", jObj.getString("result"));
2- For getting token anywhere in your application first initialize Session manager
object and than call getStringData
method like below.
private SessionManager session;
session = new SessionManager(getApplicationContext());
String token = session.getStringData("jwtToken");
Upvotes: 1