GoogleJsonResponseException: 401 Unauthorized calling endpoint with OAuth2 protection

♀尐吖头ヾ 提交于 2021-02-19 06:01:07

问题


I am trying to make an Android app with App Engine as mobile backend. I am getting this error when I try to call an endpoint protected by authentication:

12-21 18:58:05.120    4452-4477/com.test.myapplication W/System.err﹕ com.google.api.client.googleapis.json.GoogleJsonResponseException: 401 Unauthorized
12-21 18:58:05.120    4452-4477/com.test.myapplication W/System.err﹕ {
12-21 18:58:05.130    4452-4477/com.test.myapplication W/System.err﹕ {
12-21 18:58:05.130    4452-4477/com.test.myapplication W/System.err﹕ "domain": "global",
12-21 18:58:05.130    4452-4477/com.test.myapplication W/System.err﹕ "location": "Authorization",
12-21 18:58:05.130    4452-4477/com.test.myapplication W/System.err﹕ "locationType": "header",
12-21 18:58:05.130    4452-4477/com.test.myapplication W/System.err﹕ "message": "Authorization required",
12-21 18:58:05.130    4452-4477/com.test.myapplication W/System.err﹕ "reason": "required"
12-21 18:58:05.130    4452-4477/com.test.myapplication W/System.err﹕ }
12-21 18:58:05.130    4452-4477/com.test.myapplication W/System.err﹕ ],
12-21 18:58:05.130    4452-4477/com.test.myapplication W/System.err﹕ "message": "Authorization required"
12-21 18:58:05.130    4452-4477/com.test.myapplication W/System.err﹕ }
12-21 18:58:05.130    4452-4477/com.test.myapplication W/System.err﹕ at com.google.api.client.googleapis.services.json.AbstractGoogleJsonClientRequest.newExceptionOnError(AbstractGoogleJsonClientRequest.java:113)
12-21 18:58:05.130    4452-4477/com.test.myapplication W/System.err﹕ at com.google.api.client.googleapis.services.json.AbstractGoogleJsonClientRequest.newExceptionOnError(AbstractGoogleJsonClientRequest.java:40)
12-21 18:58:05.130    4452-4477/com.test.myapplication W/System.err﹕ at com.google.api.client.googleapis.services.AbstractGoogleClientRequest$1.interceptResponse(AbstractGoogleClientRequest.java:312)

Here is the endpoint code on App Engine

@ApiMethod(
        name = "signInWithGoogle",
        path = "signInWithGoogle",
        httpMethod = ApiMethod.HttpMethod.POST
)
public Profile signInWithGoogle(final User user) throws UnauthorizedException {
    if (user == null) {
        throw new UnauthorizedException("Authorization required");
    }
    Key<Profile> profileKey = Key.create(Profile.class, user.getEmail());
    return OfyService.ofy().load().key(profileKey).now();
}

And here is the activity code which call the endpoint

public class MainActivity extends Activity {

public static final String WEB_CLIENT_ID = "XXXX.apps.googleusercontent.com";
public static final String AUDIENCE = "server:client_id:" + WEB_CLIENT_ID;
protected static final HttpTransport HTTP_TRANSPORT = AndroidHttp.newCompatibleTransport();
protected static final JsonFactory JSON_FACTORY = new AndroidJsonFactory();

GoogleAccountCredential credential;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    credential = GoogleAccountCredential.usingAudience(this, AUDIENCE);

    startActivityForResult(credential.newChooseAccountIntent(), 0);
}

@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
    String accountName = data.getExtras().getString(AccountManager.KEY_ACCOUNT_NAME);
    credential.setSelectedAccountName(accountName);
    final SignUser signUser = new SignUser.Builder(HTTP_TRANSPORT, JSON_FACTORY, credential).build();
    Log.d("TEST", "start");
    new Thread(new Runnable() {
        @Override
        public void run() {
            try {
                Profile profile = signUser.signInWithGoogle().execute();
                Log.d("TEST", "success");
            } catch (IOException e) {
                e.printStackTrace();
                Log.d("TEST", "failed");
            }
        }
    }).start();
}
}

Seems like signUser.signInWithGoogle().execute() does not create the User object need by the endpoint, therefore, the endpoint throw an UnauthorizedException. Actually, if I remove the OAuth2 protection from the endpoint, everything works fine.

Can anyone explain me what is the error please?

UPDATE

Here is the @Api annotation of the java class.

@Api(
    name = "signUser",
    version = "v1",
    scopes = {Constants.EMAIL_SCOPE},
    clientIds = {Constants.ANDROID_CLIENT_ID, Constants.API_EXPLORER_CLIENT_ID},
    audiences = {Constants.ANDROID_AUDIENCE},
    description = "APIs for sign user"
)

where EMAIL_SCOPE is https://www.googleapis.com/auth/userinfo.email and ANDROID_AUDIENCE is equals to the WEB_CLIENT_ID


回答1:


I've solved this by setting an custom request initializer to the credential object like this

GoogleCredential credential = new GoogleCredential.Builder()
.setTransport(this.TRANSPORT).setJsonFactory(this.JSON_FACTORY)
.setClientSecrets(Constants.CLIENT_ID,     Constants.CLIENT_SECRET).setRequestInitializer((new HttpRequestInitializer(){
            @Override
            public void initialize(HttpRequest request)
                    throws IOException {
                request.getHeaders().put("Authorization", "Bearer " + accessToken);
            }
        })).build()


来源:https://stackoverflow.com/questions/27592289/googlejsonresponseexception-401-unauthorized-calling-endpoint-with-oauth2-prote

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!