【问题标题】:How to pass Classrooom scope in GoogleCredential for the Google Classroom API?如何在 GoogleCredential 中为 Google Classroom API 传递 Classrooom 范围?
【发布时间】:2018-08-17 20:37:43
【问题描述】:

我无法成功将Classroom.Scope 传递给GoogleCredentials。使用google登录,获取auth token,使用GoogleAuthorizationCodeTokenRequest获取accesstoken,然后将所有凭证传递给GoogleCredentials

这是代码:

public class ServerAuthCodeActivity extends AppCompatActivity implements
        GoogleApiClient.OnConnectionFailedListener,
        View.OnClickListener {

    public static final String TAG = "ServerAuthCodeActivity";
    private static final int RC_GET_AUTH_CODE = 9003;
    private static final String[] SCOPES = {ClassroomScopes.CLASSROOM_COURSES_READONLY};
    Scope SCOPE_CONTACTS_READ =
            new Scope("https://www.googleapis.com/auth/contacts.readonly");

    ArrayList<SamplePojo> arrayList;
    private GoogleApiClient mGoogleApiClient;
    private TextView mAuthCodeTextView;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.idtoken);
        StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();

        StrictMode.setThreadPolicy(policy);
        // Views
        mAuthCodeTextView = (TextView) findViewById(R.id.detail);

          // For sample only: make sure there is a valid server client ID.
        validateServerClientID();

        String serverClientId = getString(R.string.server_client_id);
        GoogleSignInOptions gso = new GoogleSignInOptions.Builder(GoogleSignInOptions.DEFAULT_SIGN_IN)
                 .requestServerAuthCode(serverClientId)
                 .requestEmail()
                .build();
        // [END configure_signin]

        // Build GoogleAPIClient with the Google Sign-In API and the above options.
        mGoogleApiClient = new GoogleApiClient.Builder(this)
                .enableAutoManage(this /* FragmentActivity */, this /* OnConnectionFailedListener */)
                .addApi(Auth.GOOGLE_SIGN_IN_API, gso)
                .build();
    }

    private void getAuthCode() {
         Intent signInIntent = Auth.GoogleSignInApi.getSignInIntent(mGoogleApiClient);
        startActivityForResult(signInIntent, RC_GET_AUTH_CODE);
    }

    private void signOut() {
        Auth.GoogleSignInApi.signOut(mGoogleApiClient).setResultCallback(
                new ResultCallback<Status>() {
                    @Override
                    public void onResult(Status status) {
                        Log.d(TAG, "signOut:onResult:" + status);
                        updateUI(false);
                    }
                });
    }

    private void revokeAccess() {
        Auth.GoogleSignInApi.revokeAccess(mGoogleApiClient).setResultCallback(
                new ResultCallback<Status>() {
                    @Override
                    public void onResult(Status status) {
                        Log.d(TAG, "revokeAccess:onResult:" + status);
                        updateUI(false);
                    }
                });
    }


    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);

        if (requestCode == RC_GET_AUTH_CODE) {
            GoogleSignInResult result = Auth.GoogleSignInApi.getSignInResultFromIntent(data);
            Log.d(TAG, "onActivityResult:GET_AUTH_CODE:success:" + result.getStatus().isSuccess());

            if (result.isSuccess()) {
                // [START get_auth_code]
                GoogleSignInAccount acct = result.getSignInAccount();
                String authCode = acct.getServerAuthCode();
                // Show signed-in UI.
                Log.i("YY", "authCode:" + authCode);
                GoogleTokenResponse response =
                        null;
                try {
                    response = new GoogleAuthorizationCodeTokenRequest(AndroidHttp.newCompatibleTransport(), new JacksonFactory(),
                            "542678605378-hlspiumlr34nq04cmjtkft17i6k3hvr0.apps.googleusercontent.com",
                            "84J_qJ1uShCxgLe8dSqqYCrI",
                            authCode,
                            "")
                            .execute();

                    Log.i("AA","response--accessToken"+response.getAccessToken());
                    Log.i("AA","response--getRefreshToken"+response.getRefreshToken());

                    Log.i("AA","response--getExpiresInSeconds"+response.getExpiresInSeconds());
                    GoogleCredential credential = new GoogleCredential.Builder()
                            .setTransport(AndroidHttp.newCompatibleTransport())

                            .setJsonFactory(JacksonFactory.getDefaultInstance())
                            .setClientSecrets("542678605378-hlspiumlr34nq04cmjtkft17i6k3hvr0.apps.googleusercontent.com","84J_qJ1uShCxgLe8dSqqYCrI")
                            .build();

                    credential.setAccessToken(response.getAccessToken());
                    credential.setExpiresInSeconds(response.getExpiresInSeconds());
                    credential.setRefreshToken(response.getRefreshToken());
                    Log.i("AA","credential-"+credential);

                    new MakeRequestTask(credential).execute();

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

                // Show signed-in UI.
                mAuthCodeTextView.setText(getString(R.string.auth_code_fmt, authCode));
                updateUI(true);

                // TODO(user): send code to server and exchange for access/refresh/ID tokens.
                // [END get_auth_code]
            } else {
                // Show signed-out UI.
                updateUI(false);
            }
        }
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.sign_in_button:
                getAuthCode();
                break;
            case R.id.sign_out_button:
                signOut();
                break;
            case R.id.disconnect_button:
                revokeAccess();
                break;
        }
    }

    private class MakeRequestTask extends AsyncTask {

        private com.google.api.services.classroom.Classroom mService = null;
        private Exception mLastError = null;

        MakeRequestTask(GoogleCredential credential) {

            HttpTransport transport = AndroidHttp.newCompatibleTransport();
            JsonFactory jsonFactory = JacksonFactory.getDefaultInstance();
            mService = new com.google.api.services.classroom.Classroom.Builder(
                    transport, jsonFactory, credential)
                    .setApplicationName("Classroom API Android Quickstart")
                    .build();
            Log.i("RR","mService"+mService);
        }


        @Override
        protected Object doInBackground(Object[] param) {
            try {
                ListCoursesResponse response = mService.courses().list()
                        .setPageSize(10)
                        .execute();
                Log.i("RR","mService.courses().list()"+mService.courses().list());

                Log.i("RR","mService-"+response);
                List<Course> courses = response.getCourses();
                return courses;
            } catch (Exception e) {
                mLastError = e;
                cancel(true);
                return null;
            }
        }

        @Override
        protected void onPreExecute() { }

        @Override
        protected void onPostExecute(Object response) {

            try {
                JSONArray jsonArray = new JSONArray(String.valueOf(response));
                Log.i("PP","jsonArray--"+jsonArray);

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

注意:我正在调用MakeRequest API 来获取课程列表。在那个 api 中,我需要传递凭据,如果在没有范围的情况下传递它会返回此错误:

{
  "code" : 403,
  "errors" : [ {
    "domain" : "global",
    "message" : "Request had insufficient authentication scopes.",
    "reason" : "forbidden"
  } ],
  "message" : "Request had insufficient authentication scopes.",
  "status" : "PERMISSION_DENIED"
}

请有人帮我解决这个问题
课堂范围:

 /** View your Google Classroom classes. */
  public static final String CLASSROOM_COURSES_READONLY = "https://www.googleapis.com/auth/classroom.courses.readonly";

【问题讨论】:

  • 请帮帮我
  • 代码太多了...你能举一个你仍然遇到问题的小例子吗?

标签: android google-api google-api-java-client google-classroom


【解决方案1】:

我正在使用服务帐户,但这是向凭据添加范围的方法:

    List<String> scopes = Arrays.asList(ClassroomScopes.CLASSROOM_COURSES,
ClassroomScopes.CLASSROOM_ROSTERS);

GoogleCredential credential = new GoogleCredential.Builder()
        .setTransport(httpTransport)
        .setJsonFactory(jsonFactory)
        .setServiceAccountId(SERVICE_ACCOUNT_EMAIL)
        .setServiceAccountScopes(scopes)
        .setServiceAccountUser(userEmail)
        .setServiceAccountPrivateKeyFromP12File(
            new java.io.File(SERVICE_ACCOUNT_PKCS12_FILE_PATH))
        .build();

【讨论】:

    猜你喜欢
    • 2016-04-28
    • 2021-05-09
    • 2021-02-23
    • 1970-01-01
    • 2020-03-26
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多