我正在尝试通过邮递员使用Firebase云消息传递测试通知。我正在对这个网址进行POST
https://fcm.googleapis.com/v1/projects/[my project name]/messages:send
Postman中的“授权”选项卡设置为“无验证”,“我的标题”选项卡如下所示
Content-Type: application/json
Authorization: Bearer [server key]
[服务器密钥]是Firebase项目“设置”区域的“云消息传递”选项卡中新生成的服务器密钥。我不断收到此错误。
"error": {
"code": 401,
"message": "Request had invalid authentication credentials. Expected OAuth 2 access token, login cookie or other valid authentication credential. See https://developers.google.com/identity/sign-in/web/devconsole-project.",
"status": "UNAUTHENTICATED"
}
根据我能找到的所有内容,我使用了正确的令牌,但谷歌似乎不同意。我应该将什么作为授权标题发送以通过此错误?
答案 0 :(得分:7)
获取身份验证载体的步骤:
发送FCM投掷邮递员的步骤:
如果要使用cURL,则进行数据通知:
curl --location --request POST 'https://fcm.googleapis.com/v1/projects/your-project-id/messages:send' \
--header 'Content-Type: application/json' \
--header 'Authorization: Bearer your-access-token-*****-wqewe' \
--data-raw '{
"message": {
"token": "device-token-qwfqwee-***-qefwe",
"data": {
"Key1": "val1",
"Key2": "val2"
}
}
}'
答案 1 :(得分:3)
您必须在Postman中生成新的访问令牌。
首先,请确保您已在Google Developer Console中启用了FCM API。 比转到Google开发者控制台-> API和服务->凭据。查看“ OAuth 2.0客户端ID”部分。列表中至少应有一项。将其下载为json文件。
在Postman中打开“授权”标签,然后选择“类型” =“ OAuth 2.0”,然后单击“获取新访问令牌”。出现对话框。
字段:
令牌名称-输入您想要的
授予类型=授权代码
从下载的json中回调URL = redirect_uris
验证URL = auth_uri
访问令牌URL = token_uri
客户ID = client_id
Client Secret = client_secret
范围=“ https://www.googleapis.com/auth/firebase.messaging”
状态-留空
客户端身份验证=默认,作为基本身份验证标头发送
单击“请求令牌”,仅此而已。
答案 2 :(得分:0)
无记名令牌是您的Firebase服务帐户获得OAuth访问令牌的结果。
获取Firebase服务帐户密钥。
转到您的firebase console>设置>服务帐户。
如果您在Firebase Admin SDK上生成了新的私钥。
您使用服务帐户密钥进行身份验证并获取承载令牌。
请在此处遵循如何在Node,Python或Java中执行此操作:
https://firebase.google.com/docs/cloud-messaging/auth-server。
因此在Java中,您可以像这样获得令牌:
private static final String SCOPES = "https://www.googleapis.com/auth/firebase.messaging";
public static void main(String[] args) throws IOException {
System.out.println(getAccessToken());
}
private static String getAccessToken() throws IOException {
GoogleCredential googleCredential = GoogleCredential
.fromStream(new FileInputStream("service-account.json"))
.createScoped(Arrays.asList(SCOPES));
googleCredential.refreshToken();
return googleCredential.getAccessToken();
}
邮递员代码:
POST /v1/projects/[projectId]/messages:send HTTP/1.1
Host: fcm.googleapis.com
Content-Type: application/json
Authorization: Bearer access_token_you_just_got
{
"message":{
"token" : "token_from_firebase.messaging().getToken()_inside_browser",
"notification" : {
"body" : "This is an FCM notification message!",
"title" : "FCM Message"
}
}
}
答案 3 :(得分:0)
您应该绝对使用Google-OAuth2.0,它可以通过提供的链接中所述的步骤生成。
您可以找到detailed steps here,我也回答了类似的问题。
答案 4 :(得分:0)
要生成用于测试的推送通知,可以使用Google Developers OAuth 2.0 Playground
您甚至可以使用Google Developers OAuth 2.0 Playground本身发送测试推送通知。 或者(如果需要)也可以使用邮递员/终端机(curl命令)。
请找到我编写的详细步骤here。
注意:,您必须使用“ 项目ID ”代替Endpoint中的“ 项目名称”。上面的链接中还提到了获取项目ID的步骤。