在Oauth2身份验证中保持会话或刷新cookieManager

时间:2018-03-07 08:52:14

标签: android cookies oauth-2.0 token session-cookies

在我的应用程序中,我使用rest api来获取用户和信息的json对象。身份验证系统是Oauth2。首先要使用该应用程序,用户需要编写他们的电子邮件地址和密码。如果用户在网络上存在电子邮件和密码,他们可以成功登录并查看所有信息。现在,我使用cookiemanager来保存并传递cookie,以便在其他的api中使用它。我是非常新的处理那种情况。问题是cookie没有使用用户名和密码刷新。我想通过每次刷新coockie永远保持会话。但现在不知道我怎么能这样做。我用以下代码解释

用户提供用户名和密码的登录代码。我用了Volley Library。并且方法是POST。

public class LoginPage extends AppCompatActivity {

public static final String MyPREFERENCES = "MyPrefs";

public static final String LOGIN_URL = "url_of_my_app";
public static final String KEY_EMAIL = "username";
public static final String KEY_PASSWORD = "password";
public static final String KEY_IS_USER_LOGED_IN = "is-user-logged-in";


private String mEmail;
private String mPassword;

public static CookieManager cookieManager;

@Override
protected void onCreate(Bundle savedInstanceState) {

    sharedpreferences = getSharedPreferences(MyPREFERENCES, Context.MODE_PRIVATE);

    //login credential

    mEmail = sharedpreferences.getString(KEY_EMAIL, null);
    mPassword = sharedpreferences.getString(KEY_PASSWORD, null);

    if (mEmail != null && mPassword != null && sharedpreferences.getBoolean(KEY_IS_USER_LOGED_IN, false)) {

        final GlobalClass globalClass = new GlobalClass();
        globalClass.setEmail_info(mEmail);

        Intent loginIntent = new Intent(LoginPage.this, MainOptionPage.class);
        loginIntent.putExtra(KEY_EMAIL, mEmail);
        startActivity(loginIntent);
        finish();

    } else {


        });


    }
}


private void attemptLogin() {

   ...
}



//volley library to hit the request

private void loginUser(final String mEmail, final String mPassword) {

    final GlobalClass globalClass = new GlobalClass();
    globalClass.setEmail_info(mEmail);

    setFilePath();

    this.trustAllCertificates();

    cookieManager = new CookieManager(new PersistentCookieStore(getApplicationContext()), CookiePolicy.ACCEPT_ALL);

    CookieHandler.setDefault(cookieManager);

    RequestQueue queue = Volley.newRequestQueue(LoginPage.this);
    StringRequest strReq = new StringRequest(Request.Method.POST,
            LOGIN_URL, new Response.Listener<String>() {

        @Override
        public void onResponse(String response) {
            Log.d(TAG, "Register Response: " + response.toString());

            //parse your response here
            if (response.contains("overview")) {
                showProgress(true);

                if (!globalClass.ifUserDataExist(mEmail)) {
                    Log.d("----After Login---", "After Login");
                   ....
                }

                SharedPreferences.Editor editor = sharedpreferences.edit();
                editor.putString(KEY_EMAIL, mEmail);
                editor.putString(KEY_PASSWORD, mPassword);
                editor.putBoolean(KEY_IS_USER_LOGED_IN, true);

                editor.commit();


                loginIntent.putExtra(KEY_EMAIL, mEmail);
                startActivity(loginIntent);
                finish();

            } else {
                userEmail.setError(getString(R.string.error_incorrect_login));
                userEmail.requestFocus();

            }
        }

    }, new Response.ErrorListener() {
        @Override
        public void onErrorResponse(VolleyError error) {

        }
    }) {
        @Override
        protected Map<String, String> getParams() throws AuthFailureError {
            Log.e(TAG, "Inside getParams");
            Map<String, String> params = new HashMap<>();
            params.put(KEY_EMAIL, mEmail);
            Log.d("email address", mEmail);
            params.put(KEY_PASSWORD, mPassword);
            return params;
        }

        @Override
        public Map<String, String> getHeaders() throws AuthFailureError {

            Map<String, String> headers = new HashMap<>();
            headers.put("Content-Type", "application/x-www-form-urlencoded");
            Log.d("headers", String.valueOf(headers));
            return headers;
        }

    };
    // Adding request to request queue
    queue.add(strReq);
}

现在在UserActivity中,如果登录成功,我将从Rest API获取用户信息。因此我得到了这些信息。在会话过期的某个时间之后,回收者视图为空白。

我只给出了这个活动课的Volley部分。如果cookie为null,我使用了alett对话框。但实际上我不想这样做。如何永久保留登录凭证,这使我可以随时使用所有api。

 public void sendRequest() {

    trustAllCertificates();

    CookieHandler.setDefault( cookieManager );

    if (cookieManager==null) {
        AlertDialog.Builder builder = new AlertDialog.Builder(this);
        builder.setTitle("Your session has expired");
        builder.setPositiveButton("Ok", new DialogInterface.OnClickListener() {
            public void onClick(DialogInterface dialog, int which) {
                //dialog.dismiss();
                Intent intent = new Intent( MyColleaguesPage.this, LoginPage.class);
                intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
                intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK);
                intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                startActivity(intent);

                SharedPreferences sharedPreferences = getSharedPreferences("MyPrefs", MODE_PRIVATE);
                SharedPreferences.Editor editor = sharedPreferences.edit();
                //editor.remove("username");
                //editor.remove("password");
                editor.remove(LoginPage.KEY_IS_USER_LOGED_IN);
                editor.apply();
                finish();
            }
        });
        AlertDialog alert = builder.create();
        alert.show();
    } else {
        JsonArrayRequest jsonArrayRequest = new JsonArrayRequest( Request.Method.GET, UPLOAD_URL + "/api/users", null, new Response.Listener<JSONArray>() {
            @Override
            public void onResponse(JSONArray response) {

                for (int i = 0; i < response.length(); i++) {

                    MyColleagueModel mycolleague = new MyColleagueModel();

                    try {
                        JSONObject object = response.getJSONObject( i );

                        mycolleague.setName( object.optString( "name" ) );
                        mycolleague.setGivenName( object.optString( "givenName" ) );
                        mycolleague.setCompany( object.optString( "company" ) );
                        mycolleague.setTitle( object.optString( "title" ) );
                        mycolleague.setMail( object.optString( "mail" ) );
                        mycolleague.setMobile( object.optString( "mobile" ) );
                        mycolleague.setDepartment( object.optString( "department" ) );

                    } catch (JSONException e) {
                        e.printStackTrace();
                    }

                    myColleagueList.add( mycolleague );

                }

                adapter = new MyColleaguesAdapter( myColleagueList, MyColleaguesPage.this );

                recyclerView.setAdapter( adapter );

            }
        }, new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError error) {
                Log.i( "Volley Error: ", error.toString() );
            }
        } );

        rq.add( jsonArrayRequest );
    }
}

0 个答案:

没有答案