每小时刷新访问令牌OAuth Android

时间:2014-10-08 04:50:27

标签: android oauth access-token

Iam已经在我的Android应用中实施了OAuth。当我登录时,我获得了一个带有刷新令牌和到期时间的访问令牌。 Access令牌在1小时后到期。我知道如何从刷新令牌请求新的访问令牌,但我不知道如何在达到到期时间时执行此操作。

这是我的代码: -

mMap = helper.getUserDetails();

                    mAccessToken =  mMap.get("accesstoken");
                    mRefreshToken = mMap.get("refresh_token");
                    mExpiresIn = mMap.get("expires_in");
                    mExpiresOn = mMap.get("expires_on");
                    mIdToken = mMap.get("id_token");
                    mScope = mMap.get("scope");
                    mTokenType = mMap.get("token_type");
                    userName = mMap.get("username");
                    firstName = mMap.get("name");





private class RefreshTokenTask extends AsyncTask<Void, Void, Void>
    {

        @Override
        protected Void doInBackground(Void... params) 
        {
            // TODO Auto-generated method stub
            /**
             * Check if access token is expired
             * Request new  access token  by passing refresh token 
             */
            String mUrl = Constants.LOGIN_URL + Constants.TENANT +"/oauth2/token";

            HttpClient httpclient = new DefaultHttpClient();
            HttpPost httppost = new HttpPost(mUrl);
            int expiryHour = (Integer.parseInt(mExpiresIn)/60)/60;



            try 
            {
                List<NameValuePair> nvps = new ArrayList<NameValuePair>(4);
                nvps.add(new BasicNameValuePair("client_id", Constants.CLIENT_ID));

                nvps.add(new BasicNameValuePair("grant_type", "authorization_code"));
                nvps.add(new BasicNameValuePair("refresh_token", mRefreshToken));
                httppost.setEntity(new UrlEncodedFormEntity(nvps));

                // Execute HTTP Post Request
                HttpResponse refreshResponse = httpclient.execute(httppost);
                HttpEntity refreshEntity = refreshResponse.getEntity();
                result = EntityUtils.toString(refreshEntity);

                //Deserialize the data into JSON
                JSONObject refreshStatusObject = new JSONObject(result);
                //Pull values out of the JSON
                mAccessToken = refreshStatusObject.getString("access_token");
                Log.i(TAG, "Access Token: " + mAccessToken);
                mExpiresIn = refreshStatusObject.getString("expires_in");
                mRefreshToken = refreshStatusObject.getString("refresh_token");
                mPortalId = refreshStatusObject.getString("portal_id");

                int firstIndex = mAccessToken.indexOf(".");
                int secondIndex = mAccessToken.indexOf(".", firstIndex+2);
                String claims = mAccessToken.substring(firstIndex + 1, secondIndex);
                //Decode base64 URL ended claims
                byte[] data = Base64.decode(claims, Base64.URL_SAFE);

                String text = new String(data, "ASCII");
                //Display claims on screen

                JSONObject jObject = new JSONObject(text);
                //Get and display the logged in user name
                userName = jObject.getString("unique_name");
                firstName = jObject.getString("given_name");

                helper.createLoginSession(mAccessToken, mExpiresIn, mExpiresOn, mIdToken, mRefreshToken, mResource, mScope, mTokenType, userName, firstName);
            } 
            catch (UnsupportedEncodingException e) 
            {
                // TODO Auto-generated catch block
                e.printStackTrace();
            } catch (ClientProtocolException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            } catch (IOException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            } catch (JSONException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }




            return null;
        }

        @Override
        protected void onPostExecute(Void result) 
        {
            // TODO Auto-generated method stub
            super.onPostExecute(result);
            Intent i = new Intent(SplashScreen.this, SUpdate.class);
            startActivity(i);
            finish();
        }

        @Override
        protected void onPreExecute() {
            // TODO Auto-generated method stub
            super.onPreExecute();
        }


    }

1 个答案:

答案 0 :(得分:1)

您应该使用Android Authenticator。然后,您将使用AccountManager来请求令牌。然后将调用您的自定义身份验证器。在该验证器中,您需要检查您当前的访问令牌是否已过期。如果是,请使用刷新令牌进行调用并获取新的令牌,更新帐户管理器中的身份验证令牌,然后将其返回给调用者。

因此,您的应用程序不需要知道更新令牌的方式和时间的详细信息,它只是知道“我需要一个令牌,让我从AccountManager获取一个令牌”,然后客户经理和验证者接管并且为你做其余的事。

这是a good tutorial on building your own Authenticator