如何在OAuth 2.0中验证访问令牌?

时间:2019-01-07 09:27:42

标签: android python ios oauth-2.0 access-token

如何验证访问令牌以及如何使用访问令牌获取令牌信息?

这是用于验证访问令牌的URL吗?

https://mydomain/oauth2/v1/tokeninfo?access_token=tYPJr7F6ArYkd1Vdlh1gbhWlnz8NLA9TZmky2NpvaHZxhw14udbmFNRG1pKMKVEY&token_type=bearer

1 个答案:

答案 0 :(得分:0)

以下是从令牌中获取数据的示例(该示例来自Azure身份验证-但这两个都使用OAuth2无关紧要)。

这就是您从令牌中提取信息的方式:

getAuthInteractiveCallback() getAuthSilentCallback()方法中:

private AuthenticationCallback getAuthSilentCallback() {
    return new AuthenticationCallback() {
        @Override
        public void onSuccess(AuthenticationResult authenticationResult) {
            /* Successfully got a token, call api now */
            Log.d(TAG, "Successfully authenticated");
            Log.d(TAG, "ID Token: " + authenticationResult.getIdToken());
            Log.d(TAG, "ID Token: " + authenticationResult.getAccessToken());

            try {
                String token = authenticationResult.getIdToken();
                String token2 = token.substring(token.indexOf('.') + 1, token.lastIndexOf('.'));
                byte[] data = Base64.decode(token2, Base64.DEFAULT);
                String text = new String(data, StandardCharsets.UTF_8);
                JSONObject jsonObject = new JSONObject(text);
                JSONArray jsonArray = new JSONArray(jsonObject.getString("emails"));
                String eMail = jsonArray.get(0).toString();
                Log.d(TAG, "eMail: " + eMail);

            } catch (JSONException ex) { }



            authResult = authenticationResult;
            state.setAuthResult(authResult);
        }

        @Override
        public void onError(MsalException exception) {
        }

        @Override
        public void onCancel() {
        }
    };
}

此外,您还可以获取iod,到期时间(exp),验证时间(auth_time),versiov(ver)