我正在开发一款Android应用,它通过管理基于magento后端的API的Cookie来使用会话。 在应用程序方面,我使用Volley Library进行网络请求。我已成功获得网络响应,并从中获取了“Set-Cookie”值。现在,当我将此cookie附加到标头但服务器未验证我的会话时。
奇怪的是我尝试从其他客户端请求相同的JSON请求,然后使用该cookie并将其作为静态值添加到标头中,然后我获得了会话访问权限。我完全不知道发生了什么。为什么来自其他客户端的cookie正在工作,而来自我的网络响应的cookie值没有。
这是我的SignIn Activity代码,我在这里执行登录json请求并存储cookie值。
package com.paaltao.activity;
import android.content.Intent;
import android.content.SharedPreferences;
import android.graphics.Color;
import android.support.v7.app.ActionBarActivity;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ProgressBar;
import android.widget.TextView;
import com.android.volley.AuthFailureError;
import com.android.volley.NetworkError;
import com.android.volley.NetworkResponse;
import com.android.volley.NoConnectionError;
import com.android.volley.ParseError;
import com.android.volley.Request;
import com.android.volley.RequestQueue;
import com.android.volley.Response;
import com.android.volley.ServerError;
import com.android.volley.TimeoutError;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.JsonObjectRequest;
import com.github.mrengineer13.snackbar.SnackBar;
import com.paaltao.R;
import com.paaltao.classes.MyApp;
import com.paaltao.classes.PersistentCookieStore;
import com.paaltao.classes.ProgressWheel;
import com.paaltao.classes.SharedPreferenceClass;
import com.paaltao.logging.L;
import com.paaltao.network.VolleySingleton;
import org.json.JSONException;
import org.json.JSONObject;
import java.net.CookieHandler;
import java.net.CookieManager;
import java.net.CookiePolicy;
import java.util.Arrays;
import java.util.Collections;
import java.util.HashMap;
import java.util.Map;
import java.util.Objects;
import static com.paaltao.extras.Keys.UserCredentials.*;
import static com.paaltao.extras.urlEndPoints.BASE_URL;
import static com.paaltao.extras.urlEndPoints.LOGIN;
import static com.paaltao.extras.urlEndPoints.UAT_BASE_URL;
public class SignInActivity extends AppCompatActivity {
private static final String SET_COOKIE_KEY = "Set-Cookie";
private static final String COOKIE_KEY = "Cookie";
private static final String SESSION_COOKIE = "sessionid";
Button SignUpBtn;
Button SignInBtn;
ProgressWheel progressBar;
EditText email, password;
TextView forgotPassword;
String emailId,accessToken,api_ver,token,firstName,lastName,cookie,newCookie;
Boolean login_success;
SharedPreferenceClass preferenceClass;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_sign_in);
Toolbar toolbar = (Toolbar) this.findViewById(R.id.app_bar);
toolbar.setTitleTextColor(Color.WHITE);
toolbar.setBackgroundColor(getResources().getColor(R.color.transparent));
this.setSupportActionBar(toolbar);
this.setTitle("Sign in");
initiate();
onItemClick();
}
public void initiate() {
SignUpBtn = (Button) findViewById(R.id.signUpBtn);
email = (EditText) findViewById(R.id.email_field);
password = (EditText) findViewById(R.id.password_field);
SignInBtn = (Button) findViewById(R.id.signInBtn);
forgotPassword = (TextView) findViewById(R.id.forgot_password);
progressBar = (ProgressWheel)findViewById(R.id.action_progress);
preferenceClass = new SharedPreferenceClass(getApplicationContext());
}
public boolean validationCheck() {
if (email.getText().toString().length() == 0)
email.setError("Please provide your email. Your email must be in the format abc@xyz.com");
else if (password.getText().toString().length() == 0)
password.setError("Please provide a password");
else return true;
return false;
}
public void onItemClick() {
SignInBtn.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
if (validationCheck()) {
sendJsonRequest();
}
}
});
SignUpBtn.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Intent intent = new Intent(SignInActivity.this, SignUpActivity.class);
startActivity(intent);
}
});
forgotPassword.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Intent intent = new Intent(SignInActivity.this, ForgotPasswordActivity.class);
startActivity(intent);
}
});
}
public static String getRequestUrl() {
return UAT_BASE_URL
+ LOGIN;
}
public void sendJsonRequest() {
progressBar.setVisibility(View.VISIBLE);
final JSONObject jsonObject = new JSONObject();
final JSONObject signIn = new JSONObject();
try {
jsonObject.put("email", email.getText().toString());
jsonObject.put("password", password.getText().toString());
signIn.put("emailSignIn", jsonObject);
} catch (JSONException e) {
e.printStackTrace();
}
RequestQueue requestQueue = VolleySingleton.getsInstance().getRequestQueue();
JsonObjectRequest jsonObjectRequest = new JsonObjectRequest(Request.Method.POST, getRequestUrl(), signIn, new Response.Listener<JSONObject>() {
@Override
public void onResponse(JSONObject jsonObject) {
if (progressBar.getVisibility() == View.VISIBLE) {
progressBar.setVisibility(View.GONE);
}
parseJSONResponse(jsonObject);
//Calling the Snackbar
Log.e("response", jsonObject.toString());
}
}, new Response.ErrorListener() {
@Override
public void onErrorResponse(VolleyError volleyError) {
if (progressBar.getVisibility() == View.VISIBLE) {
progressBar.setVisibility(View.GONE);
}
if (volleyError instanceof TimeoutError || volleyError instanceof NoConnectionError) {
new SnackBar.Builder(SignInActivity.this)
.withMessage("No Internet Connection!")
.withTextColorId(R.color.white)
.withDuration((short) 6000)
.show();
} else if (volleyError instanceof AuthFailureError) {
//TODO
} else if (volleyError instanceof ServerError) {
//TODO
} else if (volleyError instanceof NetworkError) {
//TODO
} else if (volleyError instanceof ParseError) {
//TODO
}
}
}) {
@Override
protected Response<JSONObject> parseNetworkResponse(NetworkResponse response) {
// since we don't know which of the two underlying network vehicles
// will Volley use, we have to handle and store session cookies manually
// MyApp.get().checkSessionCookie(response.headers);
L.m(response.headers.toString());
L.m(Arrays.toString(response.data));
L.m(response.headers.get("Set-Cookie"));
preferenceClass.saveCookiee(response.headers.get("Set-Cookie"));
cookie = response.headers.get("Set-Cookie");
String[] splitCookie = cookie.split(";");
String[] splitSessionId = splitCookie[0].split("=");
newCookie = splitSessionId[1];
//cookie = response.headers.values().toString();
Log.e("split",newCookie);
preferenceClass.saveCookie(newCookie);
return super.parseNetworkResponse(response);
}
@Override
public Map<String, String> getHeaders ()throws AuthFailureError {
Map<String, String> headers = super.getHeaders();
if (headers == null
|| headers.equals(Collections.emptyMap())) {
headers = new HashMap<String, String>();
}
// MyApp.get().addSessionCookie(headers);
return headers;
}
}
;
requestQueue.add(jsonObjectRequest);
}
public void parseJSONResponse(JSONObject jsonObject) {
if (jsonObject == null || jsonObject.length() == 0) {
return;
}
try {
JSONObject dataObject = jsonObject.getJSONObject(KEY_DATA);
JSONObject signInObject = dataObject.getJSONObject(KEY_SIGN_IN);
JSONObject accessTokenObject = signInObject.getJSONObject(KEY_ACCESS_TOKEN);
JSONObject errorNodeObject = dataObject.getJSONObject(KEY_ERROR_NODE);
if(dataObject.has(KEY_VENDOR)){
if (dataObject.isNull(KEY_VENDOR)){
return;
}
else {JSONObject vendorObject = dataObject.getJSONObject(KEY_VENDOR);
if(vendorObject != null){
String vendor_login = vendorObject.getString(KEY_HAS_SHOP);
if(vendor_login != null && vendor_login.contains("true")){
preferenceClass.saveVendorLoginSuccess(vendor_login);
}}}
}
emailId = signInObject.getString(KEY_EMAIL);
firstName = signInObject.getString(KEY_FIRST_NAME);
lastName = signInObject.getString(KEY_LAST_NAME);
login_success = signInObject.getBoolean(KEY_USER_LOGIN_SUCCESS);
preferenceClass.saveFirstName(firstName);
preferenceClass.saveLastName(lastName);
preferenceClass.saveUserEmail(emailId);
if(accessTokenObject.has(KEY_TOKEN)){
token = accessTokenObject.getString(KEY_TOKEN);}
String errorCode = errorNodeObject.getString(KEY_ERROR_CODE);
String message = errorNodeObject.getString(KEY_MESSAGE);
if (login_success){
Log.e("TAG",login_success.toString());
if (token!= null && token.length()!=0){
preferenceClass.saveAccessToken(token);
preferenceClass.saveUserEmail(emailId);
Intent intent = new Intent(SignInActivity.this,HomeActivity.class);
intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK|Intent.FLAG_ACTIVITY_NEW_TASK);
startActivity(intent);
finish();
}
}
else{
Log.e("TAG",login_success.toString());
new SnackBar.Builder(SignInActivity.this)
.withMessage("Username or Password is Incorrect!")
.withTextColorId(R.color.white)
.withDuration((short) 6000)
.show();
}
} catch (JSONException e) {
e.printStackTrace();
}
}
}
这是片段的代码,我正在使用从网络响应收到的存储cookie进行检查会话测试(注意:我用从休息客户端获得的cookie替换了cookie,并且它工作了!!)
package com.paaltao.fragment;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.util.Log;
import android.view.LayoutInflater;
import android.support.v4.app.Fragment;
import android.view.View;
import android.view.ViewGroup;
import android.widget.RelativeLayout;
import android.widget.TextView;
import com.android.volley.AuthFailureError;
import com.android.volley.NetworkError;
import com.android.volley.NetworkResponse;
import com.android.volley.NoConnectionError;
import com.android.volley.ParseError;
import com.android.volley.Request;
import com.android.volley.RequestQueue;
import com.android.volley.Response;
import com.android.volley.ServerError;
import com.android.volley.TimeoutError;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.HttpClientStack;
import com.android.volley.toolbox.HttpHeaderParser;
import com.android.volley.toolbox.HttpStack;
import com.android.volley.toolbox.JsonObjectRequest;
import com.android.volley.toolbox.StringRequest;
import com.android.volley.toolbox.Volley;
import com.github.mrengineer13.snackbar.SnackBar;
import com.paaltao.R;
import com.paaltao.activity.AddressActivity;
import com.paaltao.activity.IntroPageActivity;
import com.paaltao.activity.PaaltaoInfo;
import com.paaltao.activity.EditProfileActivity;
import com.paaltao.classes.MyApp;
import com.paaltao.classes.PersistentCookieStore;
import com.paaltao.classes.SharedPreferenceClass;
import com.paaltao.logging.L;
import com.paaltao.network.VolleySingleton;
import org.apache.http.impl.client.AbstractHttpClient;
import org.apache.http.impl.client.BasicCookieStore;
import org.apache.http.impl.client.DefaultHttpClient;
import org.json.JSONException;
import org.json.JSONObject;
import java.net.CookieHandler;
import java.net.CookieManager;
import java.net.CookiePolicy;
import java.net.CookieStore;
import java.util.Collections;
import java.util.HashMap;
import java.util.Map;
import cn.pedant.SweetAlert.SweetAlertDialog;
import static com.paaltao.extras.Keys.UserCredentials.KEY_ACCESS_TOKEN;
import static com.paaltao.extras.Keys.UserCredentials.KEY_DATA;
import static com.paaltao.extras.Keys.UserCredentials.KEY_ERROR_CODE;
import static com.paaltao.extras.Keys.UserCredentials.KEY_ERROR_NODE;
import static com.paaltao.extras.Keys.UserCredentials.KEY_MESSAGE;
import static com.paaltao.extras.Keys.UserCredentials.KEY_SIGN_OUT;
import static com.paaltao.extras.urlEndPoints.BASE_URL;
import static com.paaltao.extras.urlEndPoints.SIGN_OUT;
import static com.paaltao.extras.urlEndPoints.UAT_BASE_URL;
//This is a user account fragment.
public class AccountFragment extends Fragment {
private static final String SET_COOKIE_KEY = "Set-Cookie";
private static final String COOKIE_KEY = "Cookie";
private static final String SESSION_COOKIE = "sessionid";
RelativeLayout accountLink,my_address,signOut;
View view;
String accessToken;
TextView firstName,lastName,about,terms,privacy,notificationSettings;
SharedPreferenceClass preferenceClass;
SweetAlertDialog dialog;
Context context;
@Override
public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
view = inflater.inflate(R.layout.fragment_account, container, false);
initialize();
onItemClick();
return view;
}
public static String getRequestUrl() {
return UAT_BASE_URL
+ SIGN_OUT;
}
public void sendJsonRequest(){
final JSONObject jsonObject = new JSONObject();
final JSONObject signOut = new JSONObject();
try{
jsonObject.put("accessToken","67drd56g");
signOut.put("signOut", jsonObject);
} catch (JSONException e) {
e.printStackTrace();
}
RequestQueue requestQueue = VolleySingleton.getsInstance().getRequestQueue();
JsonObjectRequest jsonObjectRequest = new JsonObjectRequest(Request.Method.POST,getRequestUrl(),signOut,new Response.Listener<JSONObject>() {
@Override
public void onResponse(JSONObject jsonObject) {
Log.e("error", jsonObject.toString());
Log.e("json", signOut.toString());
parseJSONResponse(jsonObject);
}
},new Response.ErrorListener() {
@Override
public void onErrorResponse(VolleyError volleyError) {
if (volleyError instanceof TimeoutError || volleyError instanceof NoConnectionError) {
new SnackBar.Builder(getActivity())
.withMessage("No Internet Connection!")
.withTextColorId(R.color.white)
.withDuration((short) 6000)
.show();
} else if (volleyError instanceof AuthFailureError) {
//TODO
} else if (volleyError instanceof ServerError) {
//TODO
} else if (volleyError instanceof NetworkError) {
//TODO
} else if (volleyError instanceof ParseError) {
//TODO
}
}
});
requestQueue.add(jsonObjectRequest);
}
public void parseJSONResponse(JSONObject jsonObject) {
if (jsonObject == null || jsonObject.length() == 0) {
return;
}
try {
JSONObject dataObject = jsonObject.getJSONObject(KEY_DATA);
JSONObject signOutObject = jsonObject.getJSONObject(KEY_SIGN_OUT);
JSONObject errorNodeObject = dataObject.getJSONObject(KEY_ERROR_NODE);
accessToken = signOutObject.getString(KEY_ACCESS_TOKEN);
String errorCode = errorNodeObject.getString(KEY_ERROR_CODE);
String message = errorNodeObject.getString(KEY_MESSAGE);
if (errorCode.equals("200")){
preferenceClass.clearAccessToken();
preferenceClass.clearFirstName();
preferenceClass.clearLastName();
preferenceClass.clearUserEmail();
Log.e("accessToken",accessToken);
Intent intent = new Intent(getActivity(),IntroPageActivity.class);
intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK | Intent.FLAG_ACTIVITY_NEW_TASK);
startActivity(intent);
getActivity().finish();
}
else{
new SnackBar.Builder(getActivity())
.withMessage("Error in signing out")
.withTextColorId(R.color.white)
.withDuration((short) 6000)
.show();
}
} catch (JSONException e) {
e.printStackTrace();
}
}
public void sendJsonRequest1(){
final JSONObject jsonObject = new JSONObject();
final JSONObject sessionCheck = new JSONObject();
try{
jsonObject.put("accessToken","67drd56g");
sessionCheck.put("checkSession", jsonObject);
} catch (JSONException e) {
e.printStackTrace();
}
RequestQueue requestQueue = VolleySingleton.getsInstance().getRequestQueue();
JsonObjectRequest jsonObjectRequest = new JsonObjectRequest(Request.Method.POST,getRequestUrl1(),sessionCheck,new Response.Listener<JSONObject>() {
@Override
public void onResponse(JSONObject jsonObject) {
Log.e("error", jsonObject.toString());
Log.e("json", sessionCheck.toString());
Log.e("url",getRequestUrl());
L.m(jsonObject.toString());
}
},new Response.ErrorListener() {
@Override
public void onErrorResponse(VolleyError volleyError) {
if (volleyError instanceof TimeoutError || volleyError instanceof NoConnectionError) {
} else if (volleyError instanceof AuthFailureError) {
//TODO
} else if (volleyError instanceof ServerError) {
//TODO
} else if (volleyError instanceof NetworkError) {
//TODO
} else if (volleyError instanceof ParseError) {
//TODO
}
}
})
{
@Override
protected Response<JSONObject> parseNetworkResponse(NetworkResponse response) {
// since we don't know which of the two underlying network vehicles
// will Volley use, we have to handle and store session cookies manually
// MyApp.get().checkSessionCookie(response.headers);
//L.m(response.headers.toString());
return super.parseNetworkResponse(response);
}
@Override
public Map<String, String> getHeaders() throws AuthFailureError {
Map<String, String> headers = super.getHeaders();
if (headers == null
|| headers.equals(Collections.emptyMap())) {
headers = new HashMap<String, String>();
}
String sessionId = preferenceClass.getCookie();
Log.e("cOOOKIE","frontend="+sessionId);
Log.e("sessionid","frontend=7fgenogpffjvvmdg1gf439hta7");
// headers.put(COOKIE_KEY,"frontend="+sessionId);
headers.put(COOKIE_KEY,"frontend=e7qfldgsnf7aop381a8vk3b866");
return headers;
}};
requestQueue.add(jsonObjectRequest);
}
private String getRequestUrl1() {
return UAT_BASE_URL+"checkSession";
}
public void initialize(){
accountLink = (RelativeLayout)view.findViewById(R.id.account_link);
my_address = (RelativeLayout)view.findViewById(R.id.my_address);
signOut = (RelativeLayout)view.findViewById(R.id.signOut);
preferenceClass = new SharedPreferenceClass(getActivity());
firstName = (TextView)view.findViewById(R.id.firstName);
lastName = (TextView)view.findViewById(R.id.lastName);
about = (TextView)view.findViewById(R.id.about);
terms = (TextView)view.findViewById(R.id.terms);
privacy = (TextView)view.findViewById(R.id.privacy);
if(preferenceClass.getFirstName() != null)
firstName.setText(preferenceClass.getFirstName());
if(preferenceClass.getLastName() != null)
lastName.setText(preferenceClass.getLastName());
notificationSettings = (TextView)view.findViewById(R.id.notification_settings);
}
public void onItemClick(){
notificationSettings.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
sendJsonRequest1();
}
});
accountLink.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
startActivity(new Intent(getActivity(), EditProfileActivity.class));
}
});
my_address.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
startActivity(new Intent(getActivity(), AddressActivity.class));
}
});
signOut.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
confirmSignOut();
}
});
about.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Intent intent = new Intent(getActivity(), PaaltaoInfo.class);
intent.putExtra("page","about_paaltao");
startActivity(intent);
}
});
terms.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Intent intent = new Intent(getActivity(), PaaltaoInfo.class);
intent.putExtra("page","terms");
startActivity(intent);
}
});
privacy.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Intent intent = new Intent(getActivity(), PaaltaoInfo.class);
intent.putExtra("page","privacy_policy");
startActivity(intent);
}
});
}
public void confirmSignOut(){
dialog = new SweetAlertDialog(getActivity(), SweetAlertDialog.NORMAL_TYPE);
dialog.setTitleText("Signout")
.setContentText("Are you sure you want to sign out?")
.setConfirmText("Yes")
.setCancelText("No")
.setConfirmClickListener(new SweetAlertDialog.OnSweetClickListener() {
@Override
public void onClick(SweetAlertDialog sDialog) {
sendJsonRequest();
}
})
.setCancelClickListener(new SweetAlertDialog.OnSweetClickListener() {
@Override
public void onClick(SweetAlertDialog sDialog) {
dialog.cancel();
}
})
.show();
}
}
其他客户端cookie与应用程序中收到的cookie之间没有结构差异:
rest客户端cookie:frontend = 48b1i38fgls4d0241mp6d6rrr0 app side cookie:frontend = 86n349m3patu37eud00ntobd90
提前致谢。如果有人可以提供帮助,那将会延长生命。