Error 401 firebase

I'm trying to test out Firebase Cloud messaging APIs as all functionality is not available from console (notably customization of notifications when app is in background). But for some reasons, I c...

I’m trying to test out Firebase Cloud messaging APIs as all functionality is not available from console (notably customization of notifications when app is in background). But for some reasons, I cannot get it to work, and it always shows up 401 error. I investigated the reasons for this, and tried it after regenerating new server key, but the error remains constant. Surprisingly, when I generated a new server key, it is not reflected in Firebase console and it shows server key as empty. Also, I tried adding my IP address to the server whitelist IPs but still no luck. I’ve attached a screenshot of a request that I did with Postman (I substitue the server key in place of serverKey.

I’m stuck on this for a few hours and would really appreciate some help.enter image description here

asked Jun 4, 2016 at 17:38

gaurav jain's user avatar

8

I don’t know if someone uses the [Web API Key] as the [YOUR_SERVER_KEY] for POSTMAN test and keep getting ‘401 Error’. [Web API Key] is not [YOUR_SERVER_KEY].

You should go to your Firebase console and check this:

to get the correct Server key.

Hope it help.

answered Nov 1, 2016 at 0:11

S1ngoooor's user avatar

S1ngoooorS1ngoooor

2,5572 gold badges10 silver badges12 bronze badges

1

I noticed from your screenshot that you were using «key: serverKey». Could you try using «key=serverKey» instead?

Also you don’t need to have «POST fcm.googleapus.com/fcm/send»; this is not proper json and would explain the error you are seeing. The URL of the request is already defined elsewhere so remove it from the payload.

answered Jun 7, 2016 at 19:50

Arthur Thompson's user avatar

Arthur ThompsonArthur Thompson

8,9894 gold badges28 silver badges33 bronze badges

5

I faced the same problem.

the problem was that I was using the legacy server key. when I used the new version of the server key the problem solved.

in your firebase console goto settings -> cloud messaging

then use the new server key. it is longer than the old version key.

answered Dec 1, 2016 at 15:12

Karim's user avatar

KarimKarim

3904 silver badges16 bronze badges

0

answered Nov 12, 2017 at 11:04

Omar Makled's user avatar

Omar MakledOmar Makled

1,5381 gold badge18 silver badges17 bronze badges

1

I too am facing the Same problem… I am using curl in php for posting and it works only if I have php files stored on my LocalHost server. When I try to use access the files via a free hosting online, then it say Unautorized 401.

So I would suggest if you can, use the Localhost.

answered Jun 10, 2016 at 5:56

Sugam Mankad's user avatar

4

I have the same problem at Server Side Code(C#).

You basically used wrong Server Key (or API Key) for service side code.

Follow below Link over stackoverflow posted by me (Helpful to find Server Key (or API Key) )

FCM (Firebase Cloud Messaging) Push Notification with Asp.Net

Community's user avatar

answered Sep 24, 2016 at 6:24

Nilesh's user avatar

NileshNilesh

1,00314 silver badges21 bronze badges

401 with FCM through HTTPv1 (Error and Solution for Bearer)

If you are using FCM via HTTP v1, then you will have to make two sucessive POST requests:

1/ In the first call, you make a POST request to ‘https://accounts.google.com/o/oauth2/token’ (or using API packages) using your firebase service account key at
‘https://console.firebase.google.com/u/0/project/{{firebaseProjectName}}/settings/serviceaccounts/adminsdk’
to get the access token.

2/ Then you have to make another POST request to ‘https://fcm.googleapis.com/v1/projects/{{firebaseProjectName}}/messages:send’. If you have followed the steps for the migration from legacy HTTP to HTTP v1 (very clear documentation) on firebase website, you have to make some small changes at the content of the post request and also using ‘Bearer ${accessToken.data}’ for the Authorization.

In my case I was not properly awaiting for the accessToken in the first function (forgot the ‘await’ keyword in front of the function making the post request and AndroidStudio did not notice either that there was something wrong).

Make sure that you await the result of the first post request as it is a Future.

If you don’t, Bearer will be null when you make the second POST request because you did not await for it.

answered Jan 27, 2021 at 0:09

Antonin GAVREL's user avatar

Antonin GAVRELAntonin GAVREL

9,0966 gold badges52 silver badges74 bronze badges

1

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.HttpClientBuilder;
import org.apache.http.util.EntityUtils;
import org.json.JSONArray;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.List;
import javax.validation.Valid;
import javax.validation.constraints.Size;

public class PushNotificationSubmit {

    public static void main(String[] args) {
        new PushNotificationSubmit().send("sample message title", "sample message body");
    }

    final String serverKey = "AAAA_*******";
    final String fcmUrl = "https://fcm.googleapis.com/fcm/send";

    /**
     * note from google: The value should be an array of registration tokens to which to send the multicast message. The array must contain at least 1 and at most 1000 registration tokens.
     * send to specific users
     *
     * @param messageTitle
     * @param messageBody
     * @param tokenList
     */
    @Size.List({@Size(min = 1), @Size(max = 999)})
    public void send(String messageTitle, String messageBody, List<String> tokenList) {
        try {
            String payloadJson = createMessageAsJson(messageTitle, messageBody, tokenList);
            doSend(payloadJson);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * send to all users that registered in my topic
     *
     * @param messageTitle
     * @param messageBody
     */
    public void send(String messageTitle, String messageBody) {
        try {
            String payloadJson = createMessageAsJson(messageTitle, messageBody, null);
            doSend(payloadJson);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    private String createMessageAsJson(String messageTitle, String messageBody, List<String> tokenList) {
        JSONObject payloadObj = new JSONObject();
        try {
            JSONObject notifyObj = new JSONObject();
            notifyObj.put("title", messageTitle);
            notifyObj.put("body", messageBody);
            payloadObj.put("notification", notifyObj);

            if (tokenList != null) {
                if (tokenList != null && tokenList.size() > 0) {
                    JSONArray regId = new JSONArray();
                    for (int i = 0; i < tokenList.size(); i++) {
                        regId.put(tokenList.get(i));
                    }
                    payloadObj.put("registration_ids", regId);
                }
            } else {
                payloadObj.put("to", "/topics/all");
            }

            return payloadObj.toString();
        } catch (Exception e) {
            // TODO: add logger
            e.printStackTrace();
            throw e;
        }
    }

    private void doSend(String payloadJson) throws Exception {
        HttpClient httpclient = HttpClientBuilder.create().build();
        try {
            HttpPost httpPost = new HttpPost(fcmUrl);
            httpPost.setHeader("Content-Type", "application/json");
            httpPost.setHeader("Authorization", "key=" + serverKey);
            httpPost.setEntity(new StringEntity(payloadJson, "UTF-8"));

            HttpResponse response = httpclient.execute(httpPost);
            HttpEntity entity = response.getEntity();

            System.out.println("push notification status: " + response.getStatusLine());
            EntityUtils.consume(entity);
        } finally {
            httpclient.getConnectionManager().shutdown();
        }
    }
}

answered May 3, 2021 at 10:56

M.Namjo's user avatar

M.NamjoM.Namjo

3342 silver badges13 bronze badges

In C# HttpClient response

For wrong server key it will happen, Invalid Key, Unauthorize, 401

answered May 8, 2021 at 4:05

Mahydul Islam Shajal's user avatar

I was facing the same problem, i solved it by using the following steps

1- In the server from where you are sending push, Use the browser key only, you can get it from Firebase console or google api console as I have highlighted in the below images:-

Google api console

Firebase console, click on the project—>settings

Note : The Firebase console web api key and google console browser key are the same you can use either of them

enter image description here

enter image description here

2- If you follow the first step only you will get the Unauthorized error, to resolve this you need to authorize your browser key in google console by adding your server IP address from where you will send the push. Click on the edit pencil icon on the right side of your browser key in google api console, above first image

enter image description here

After adding your Ip address click save
Make sure that your device token is not empty on which you are sending the push, I hope your push will be sent successfully now.

answered Oct 21, 2016 at 2:17

Mehroz Munir's user avatar

Mehroz MunirMehroz Munir

2,1681 gold badge17 silver badges16 bronze badges

2

[REQUIRED] Environment info

firebase-tools:
6.3.1

Platform:
Ubuntu 16.04.5 LTS (GNU/Linux 4.4.0-141-generic x86_64)

[REQUIRED] Test case

Unable to init functions and deploy any functions while having my account logged in. Here are some logs:

λ ~/code/android/CoreWriter/ master* firebase login
Already logged in as one.lite.core@gmail.com

λ ~/code/android/CoreWriter/ master* firebase init      

     ######## #### ########  ######## ########     ###     ######  ########
     ##        ##  ##     ## ##       ##     ##  ##   ##  ##       ##
     ######    ##  ########  ######   ########  #########  ######  ######
     ##        ##  ##    ##  ##       ##     ## ##     ##       ## ##
     ##       #### ##     ## ######## ########  ##     ##  ######  ########

You're about to initialize a Firebase project in this directory:

  /home/core/code/android/CoreWriter

Before we get started, keep in mind:

  * You are initializing in an existing Firebase project directory

? Which Firebase CLI features do you want to setup for this folder? Press Space to select features, then Enter to confirm your choices. Firestore: Deploy rules and create indexes for Firestore

=== Project Setup

First, let's associate this project directory with a Firebase project.
You can create multiple project aliases by running firebase use --add, 
but for now we'll just set up a default project.

i  .firebaserc already has a default project, skipping

=== Firestore Setup

Error: HTTP Error: 401, 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.

λ ~/code/android/CoreWriter/ master* firebase deploy --only functions

Error: HTTP Error: 401, 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.

Having trouble? Try firebase deploy --help

λ ~/code/android/CoreWriter/ master* firebase list

Error: HTTP Error: 401, The entered credentials were incorrect.

As you can see in the log, init, deploy and list command could not be executed and return me a Error 401.

I’ve tried log out and log in, re-install firebase-tools, and reboot, but none of them worked.

[REQUIRED] Steps to reproduce

  1. install latest firebase-tools
  2. init functions or deploy functions

[REQUIRED] Expected behavior

Functions are expected to be deployed online.

[REQUIRED] Actual behavior

Got a Error 401 like this:

Error: HTTP Error: 401, 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.

I have a php script to connect to fcm and the return result is Unauthorized: error 401. How can I diagnose this issue?

PHP code:

<?php

/**
* @author Ravi Tamada
* @link URL Tutorial link
*/
class Firebase {

// sending push message to single user by firebase reg id
public function send($to, $message) {
$fields = array(
‘to’ => $to,
‘data’ => $message,
);
return $this->sendPushNotification($fields);
}

// Sending message to a topic by topic name
public function sendToTopic($to, $message) {
$fields = array(
‘to’ => ‘/topics/’ . $to,
‘data’ => $message,
);
return $this->sendPushNotification($fields);
}

// sending push message to multiple users by firebase registration ids
public function sendMultiple($registration_ids, $message) {
$fields = array(
‘to’ => $registration_ids,
‘data’ => $message,
);

return $this->sendPushNotification($fields);
}

// function makes curl request to firebase servers
private function sendPushNotification($fields) {

require_once __DIR__ . ‘/config.php’;

// Set POST variables
$url = ‘https://fcm.googleapis.com/fcm/send’;

$headers = array(
‘Authorization:key=’ . FIREBASE_API_KEY, // is this the web api key or the cloud messaging key?
‘Content-Type:application/json’
);
// Open connection
$ch = curl_init();

// Set the url, number of POST vars, POST data
curl_setopt($ch, CURLOPT_URL, $url);

curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);

// Disabling SSL Certificate support temporarly
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($ch, CURLOPT_IPRESOLVE, CURL_IPRESOLVE_V4 );
print_r($fields);
curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($fields));

// Execute post
$result = curl_exec($ch);
// curl -X POST —header «Authorization: key=<API_ACCESS_KEY>» —Header «Content-Type: application/json» https://fcm.googleapis.com/fcm/send -d «{«to»:»<YOUR_DEVICE_ID_TOKEN>»,»notification»:{«body»:»Yellow»},»priority»:10}»;
if ($result === FALSE) {
die(‘Curl failed: ‘ . curl_error($ch));
}
echo $result;
// Close connection
curl_close($ch);

return $result;
}
}
?>

edit: Use the key in the cloud messaging tab if you get this error

Я пытаюсь проверить API-интерфейсы Firebase Cloud, поскольку все функции недоступны с консоли (особенно настройка уведомлений, когда приложение находится в фоновом режиме). Но по некоторым причинам я не могу заставить его работать, и он всегда обнаруживает ошибку 401. Я исследовал причины этого и попробовал его после восстановления нового ключа сервера, но ошибка остается постоянной. Удивительно, но когда я сгенерировал новый ключ сервера, он не отражается в консоли Firebase и показывает, что ключ сервера пуст. Кроме того, я попытался добавить свой IP-адрес к IP-адресам серверов, но все равно не повезло. Я добавил скриншот запроса, который я сделал с Postman (я заменяю ключ сервера вместо serverKey.

Я застрял на этом в течение нескольких часов и буду очень благодарен за помощь. введите описание изображения здесь

4b9b3361

Ответ 1

Я заметил с вашего скриншота, что вы использовали «key: serverKey». Не могли бы вы вместо этого использовать «key = serverKey»?

Также вам не нужно иметь «POST fcm.googleapus.com/fcm/send»; это не правильный json и объяснит ошибку, которую вы видите. URL-адрес запроса уже определен в другом месте, поэтому удалите его из полезной нагрузки.

Ответ 2

Я не знаю, использует ли кто-нибудь [Ключ API] в качестве теста [YOUR_SERVER_KEY] для теста POSTMAN и продолжает получать «Ошибка 401». [Веб-интерфейс API] не [YOUR_SERVER_KEY].

Вы должны пойти в консоль Firebase и проверить это:

чтобы получить правильный ключ сервера.

Надеюсь, что это поможет.

Ответ 3

У меня была та же проблема.

проблема заключалась в том, что я использовал старый ключ сервера. когда я использовал новую версию ключа сервера, проблема была решена.

в настройках консоли firebase → облачные сообщения

затем используйте новый ключ сервера. он длиннее старого ключа версии.

Ответ 4

перейти к https://console.firebase.google.com/u/0/project/[project-name]/settings/cloudmessaging/

Project credentials

Вы можете использовать ключ сервера или старый ключ сервера

Ответ 5

Я тоже сталкиваюсь с той же проблемой… Я использую curl в php для публикации, и он работает, только если у меня есть файлы php, хранящиеся на моем сервере LocalHost. Когда я пытаюсь использовать доступ к файлам через бесплатный хостинг в Интернете, тогда он говорит «Неавторизованный 401».

Поэтому я бы предложил, если можно, использовать Localhost.

Ответ 6

У меня такая же проблема с кодом сервера (С#).

В основном вы использовали неправильный ключ сервера (или ключ API) для кода службы.

Следуйте ниже Ссылка на stackoverflow, отправленный мной (полезно найти ключ сервера (или ключ API))

FCM (Firebase Cloud Messaging) Push Notification с Asp.Net

Ответ 7

Я столкнулся с той же проблемой, я решил ее, выполнив следующие шаги

1- На сервере, откуда вы отправляете push, используйте только ключ браузера, вы можете получить его из консоли Firebase или консоли google api, как я выделил следующие изображения: —

Google api console

Консоль Firebase, нажмите на проект → настройки

Примечание. Ключ панели консоли Firebase и ключ браузера Google консоли — это то же самое, что вы можете использовать любой из них

введите описание изображения здесь

введите описание изображения здесь

2- Если вы выполните первый шаг, вы получите Unauthorized error, чтобы решить эту проблему, вам нужно авторизовать свой ключ браузера на консоли Google, добавив IP-адрес вашего сервера, откуда вы отправите push. Нажмите на значок редактирования карандаша в правой части вашего ключа браузера в консоли google api, над первым изображением

введите описание изображения здесь

После добавления адреса Ip нажмите «Сохранить».
Убедитесь, что токен вашего устройства не пуст, на который вы отправляете push, я надеюсь, что ваш push будет отправлен успешно.

I’m trying to test out Firebase Cloud messaging APIs as all functionality is not available from console (notably customization of notifications when app is in background). But for some reasons, I cannot get it to work, and it always shows up 401 error. I investigated the reasons for this, and tried it after regenerating new server key, but the error remains constant. Surprisingly, when I generated a new server key, it is not reflected in Firebase console and it shows server key as empty. Also, I tried adding my IP address to the server whitelist IPs but still no luck. I’ve attached a screenshot of a request that I did with Postman (I substitue the server key in place of serverKey.

I’m stuck on this for a few hours and would really appreciate some help.enter image description here

10 Answers

I don’t know if someone uses the [Web API Key] as the [YOUR_SERVER_KEY] for POSTMAN test and keep getting ‘401 Error’. [Web API Key] is not [YOUR_SERVER_KEY].

You should go to your Firebase console and check this:

to get the correct Server key.

Hope it help.

I noticed from your screenshot that you were using «key: serverKey». Could you try using «key=serverKey» instead?

Also you don’t need to have «POST fcm.googleapus.com/fcm/send»; this is not proper json and would explain the error you are seeing. The URL of the request is already defined elsewhere so remove it from the payload.

I faced the same problem.

the problem was that I was using the legacy server key. when I used the new version of the server key the problem solved.

in your firebase console goto settings -> cloud messaging

then use the new server key. it is longer than the old version key.

I too am facing the Same problem… I am using curl in php for posting and it works only if I have php files stored on my LocalHost server. When I try to use access the files via a free hosting online, then it say Unautorized 401.

So I would suggest if you can, use the Localhost.

I was facing the same problem, i solved it by using the following steps

1- In the server from where you are sending push, Use the browser key only, you can get it from Firebase console or google api console as I have highlighted in the below images:-

Google api console

Firebase console, click on the project—>settings

Note : The Firebase console web api key and google console browser key are the same you can use either of them

enter image description here

enter image description here

2- If you follow the first step only you will get the Unauthorized error, to resolve this you need to authorize your browser key in google console by adding your server IP address from where you will send the push. Click on the edit pencil icon on the right side of your browser key in google api console, above first image

enter image description here

After adding your Ip address click save
Make sure that your device token is not empty on which you are sending the push, I hope your push will be sent successfully now.

401 with FCM through HTTPv1 (Error and Solution for Bearer)

If you are using FCM via HTTP v1, then you will have to make two sucessive POST requests:

1/ In the first call, you make a POST request to ‘https://accounts.google.com/o/oauth2/token’ (or using API packages) using your firebase service account key at
‘https://console.firebase.google.com/u/0/project/{{firebaseProjectName}}/settings/serviceaccounts/adminsdk’
to get the access token.

2/ Then you have to make another POST request to ‘https://fcm.googleapis.com/v1/projects/{{firebaseProjectName}}/messages:send’. If you have followed the steps for the migration from legacy HTTP to HTTP v1 (very clear documentation) on firebase website, you have to make some small changes at the content of the post request and also using ‘Bearer ${accessToken.data}’ for the Authorization.

In my case I was not properly awaiting for the accessToken in the first function (forgot the ‘await’ keyword in front of the function making the post request and AndroidStudio did not notice either that there was something wrong).

Make sure that you await the result of the first post request as it is a Future.

If you don’t, Bearer will be null when you make the second POST request because you did not await for it.

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.HttpClientBuilder;
import org.apache.http.util.EntityUtils;
import org.json.JSONArray;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.List;
import javax.validation.Valid;
import javax.validation.constraints.Size;

public class PushNotificationSubmit {

    public static void main(String[] args) {
        new PushNotificationSubmit().send("sample message title", "sample message body");
    }

    final String serverKey = "AAAA_*******";
    final String fcmUrl = "https://fcm.googleapis.com/fcm/send";

    /**
     * note from google: The value should be an array of registration tokens to which to send the multicast message. The array must contain at least 1 and at most 1000 registration tokens.
     * send to specific users
     *
     * @param messageTitle
     * @param messageBody
     * @param tokenList
     */
    @Size.List({@Size(min = 1), @Size(max = 999)})
    public void send(String messageTitle, String messageBody, List<String> tokenList) {
        try {
            String payloadJson = createMessageAsJson(messageTitle, messageBody, tokenList);
            doSend(payloadJson);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * send to all users that registered in my topic
     *
     * @param messageTitle
     * @param messageBody
     */
    public void send(String messageTitle, String messageBody) {
        try {
            String payloadJson = createMessageAsJson(messageTitle, messageBody, null);
            doSend(payloadJson);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    private String createMessageAsJson(String messageTitle, String messageBody, List<String> tokenList) {
        JSONObject payloadObj = new JSONObject();
        try {
            JSONObject notifyObj = new JSONObject();
            notifyObj.put("title", messageTitle);
            notifyObj.put("body", messageBody);
            payloadObj.put("notification", notifyObj);

            if (tokenList != null) {
                if (tokenList != null && tokenList.size() > 0) {
                    JSONArray regId = new JSONArray();
                    for (int i = 0; i < tokenList.size(); i++) {
                        regId.put(tokenList.get(i));
                    }
                    payloadObj.put("registration_ids", regId);
                }
            } else {
                payloadObj.put("to", "/topics/all");
            }

            return payloadObj.toString();
        } catch (Exception e) {
            // TODO: add logger
            e.printStackTrace();
            throw e;
        }
    }

    private void doSend(String payloadJson) throws Exception {
        HttpClient httpclient = HttpClientBuilder.create().build();
        try {
            HttpPost httpPost = new HttpPost(fcmUrl);
            httpPost.setHeader("Content-Type", "application/json");
            httpPost.setHeader("Authorization", "key=" + serverKey);
            httpPost.setEntity(new StringEntity(payloadJson, "UTF-8"));

            HttpResponse response = httpclient.execute(httpPost);
            HttpEntity entity = response.getEntity();

            System.out.println("push notification status: " + response.getStatusLine());
            EntityUtils.consume(entity);
        } finally {
            httpclient.getConnectionManager().shutdown();
        }
    }
}

In C# HttpClient response

For wrong server key it will happen, Invalid Key, Unauthorize, 401

Я пытаюсь протестировать API обмена сообщениями Firebase Cloud, поскольку все функции недоступны из консоли (в частности, настройка уведомлений, когда приложение находится в фоновом режиме). Но по некоторым причинам, я не могу заставить его работать, и он всегда показывает ошибку 401. Я исследовал причины этого и попробовал его после регенерации нового ключа сервера, но ошибка остается постоянной. Удивительно, но когда я создал новый ключ сервера, он не отражается в консоли Firebase и показывает ключ сервера как пустой. Кроме того, я попытался добавить свой IP-адрес в белый список IPs сервера, но все равно не повезло. Я прикрепил скриншот запроса, который я сделал с Postman (я заменяю ключ сервера вместо serverKey.

Я застрял на этом в течение нескольких часов и был бы очень признателен некоторую помощь.enter image description here

7 ответов


Я заметил с вашего скриншота, что вы используете «key: serverKey». Не могли бы вы попробовать использовать» key=serverKey » вместо этого?

Также вам не нужно иметь «сообщение fcm.googleapus.com/fcm/send»; это не настоящий json и объяснило бы ошибку, которую вы видите. URL-адрес запроса уже определен в другом месте, поэтому удалите его из полезной нагрузки.

27

автор: Arthur Thompson


Я не знаю, использует ли кто-то [ключ веб-API] в качестве [YOUR_SERVER_KEY] для теста POSTMAN и продолжает получать «ошибку 401». [Ключ веб-API] не является [YOUR_SERVER_KEY].

вы должны перейти к консоли Firebase и проверить это:

чтобы получить правильный ключ сервера.

надеюсь, что это поможет.


Я столкнулся с той же проблемой.

проблема в том, что я использовал старый ключ сервера. когда я использовал новую версию ключа сервера, проблема была решена.

в настройках консоли firebase goto — > облачные сообщения

затем используйте новый ключ сервера. он длиннее, чем старый ключ версии.


Я тоже сталкиваюсь с той же проблемой… Я использую curl в php для публикации, и он работает, только если у меня есть файлы php, хранящиеся на моем сервере LocalHost. Когда я пытаюсь использовать доступ к файлам через бесплатный хостинг онлайн, то он говорит Unautorized 401.

поэтому я бы предложил, если вы можете, использовать Localhost.



У меня такая же проблема на стороне сервера(C#).

вы в основном использовали неправильный ключ сервера (или ключ API) для кода стороны обслуживания.

перейдите по ссылке ниже по StackOverflow, опубликованной мной (полезно найти ключ сервера (или ключ API) )

FCM (Firebase Cloud Messaging) Push-уведомление с Asp.Net


Я столкнулся с той же проблемой, я решил ее с помощью следующих шагов

1-на сервере, с которого вы отправляете push, используйте только ключ браузера, вы можете получить его из консоли Firebase или консоли Google api, как я выделил в приведенных ниже изображениях: —

в Google API в консоли

консоль Firebase, нажмите на проект— > настройки

Примечание: ключ веб-api консоли Firebase и google клавиша браузера консоли одинакова, вы можете использовать любой из них

enter image description here

enter image description here

2-Если вы выполните только первый шаг, вы получите несанкционированную ошибку, чтобы решить эту проблему, вам нужно авторизовать свой ключ браузера в консоли google, добавив свой IP-адрес сервера, откуда вы отправите толчок. Нажмите на значок редактировать карандаш в правой части ключа браузера в консоли Google api, над первым изображение

enter image description here

после добавления Ip-адреса нажмите Сохранить
Убедитесь,что маркер вашего устройства не пуст, на котором вы отправляете толчок, я надеюсь, что ваш толчок будет отправлен успешно.



Winifred


Winifred

posted


   $url = "https://fcm.googleapis.com/fcm/send";
    $token = $devicetoken;
    $serverKey = 'BVhFT_kT43i-DHZt6fQBVhFT_kT43i-DHZt6fQ';
    $title =$title;
    $body = $body;
    $notification = array('title' =>$title , 'body' => $body, 'sound' => 'default', 'badge' => '1');
    $arrayToSend = array('to' => $token, 'notification' => $notification,'priority'=>'high');
    $json = json_encode($arrayToSend);
    $headers = array();
    $headers[] = 'Content-Type: application/json';
    $headers[] = 'Authorization: key='. $serverKey;
    $ch = curl_init();
    curl_setopt($ch, CURLOPT_URL, $url);
    curl_setopt($ch, CURLOPT_CUSTOMREQUEST,"POST");
    curl_setopt($ch, CURLOPT_POSTFIELDS, $json);
    curl_setopt($ch, CURLOPT_HTTPHEADER,$headers);
    //Send the request
    $response = curl_exec($ch);
    print_r($response);
    //Close request
    if ($response === FALSE) {
    die('FCM Send Error: ' . curl_error($ch));
    }
    curl_close($ch);

i am getting error : INVALID_KEY_TYPE so not sure what is wrong in the firebase API call for FCM notification


chirag

chirag


You are using the wrong key.
you should get the key from the Project > Settings > Cloud Messaging > Server Key from firebase console.


andy

andy


I tested your code. and it works well but you using the key from the Project settings > General which is not the right key to use, so API response show INVALID_KEY_TYPE from the firebase. you should use from Cloud Messaging .

Я пытаюсь протестировать API обмена сообщениями Firebase Cloud, поскольку все функции недоступны из консоли (в частности, настройка уведомлений, когда приложение находится в фоновом режиме). Но по некоторым причинам я не могу заставить его работать, и всегда выдает ошибку 401. Я исследовал причины этого и попробовал это после восстановления нового ключа сервера, но ошибка остается постоянной. Удивительно, но когда я сгенерировал новый ключ сервера, он не отражается в консоли Firebase и показывает ключ сервера как пустой. Кроме того, я попытался добавить свой IP-адрес в белый список IP-адресов сервера, но все равно не повезло. Я приложил снимок экрана с запросом, который я сделал с Postman (я подставляю ключ сервера вместо serverKey.

Я застрял в этом на несколько часов и был бы очень признателен за помощь.  введите описание изображения здесь

person
gaurav jain
  
schedule
04.06.2016
  
source
источник


Ответы (9)

Я заметил на вашем скриншоте, что вы использовали ключ: serverKey. Не могли бы вы вместо этого использовать «key = serverKey»?

Также вам не нужно иметь «POST fcm.googleapus.com/fcm/send»; это неправильный json и объясняет ошибку, которую вы видите. URL-адрес запроса уже определен в другом месте, поэтому удалите его из полезной нагрузки.

person
Arthur Thompson
  
schedule
07.06.2016

Я не знаю, использует ли кто-нибудь [Ключ веб-API] в качестве [YOUR_SERVER_KEY] для теста POSTMAN и продолжает получать «Ошибка 401». [Ключ веб-API] не [YOUR_SERVER_KEY].

Вам следует зайти в консоль Firebase и проверить это:

чтобы получить правильный ключ сервера.

Надеюсь, это поможет.

person
S1ngoooor
  
schedule
01.11.2016

Я столкнулся с той же проблемой.

проблема заключалась в том, что я использовал старый ключ сервера. когда я использовал новую версию серверного ключа, проблема решилась.

в настройках консоли firebase перейти к> облачным сообщениям

затем используйте новый ключ сервера. он длиннее, чем ключ старой версии.

person
Karim
  
schedule
01.12.2016

Я тоже сталкиваюсь с той же проблемой … Я использую curl в php для публикации, и он работает, только если у меня есть файлы php, хранящиеся на моем сервере LocalHost. Когда я пытаюсь использовать доступ к файлам через бесплатный хостинг в Интернете, появляется сообщение Unautorized 401.

Поэтому я бы посоветовал, если вы можете, использовать Localhost.

person
Sugam Mankad
  
schedule
10.06.2016

У меня такая же проблема с серверным кодом (C #).

Вы в основном использовали неправильный ключ сервера (или ключ API) для кода стороны службы.

Следуйте приведенной ниже ссылке на stackoverflow, опубликованной мной (полезно найти ключ сервера (или ключ API))

Push-уведомление FCM (Firebase Cloud Messaging) с помощью Asp .Net

person
Nilesh
  
schedule
24.09.2016

Я столкнулся с той же проблемой, я решил ее, выполнив следующие шаги

1- На сервере, с которого вы отправляете push, используйте только ключ браузера, вы можете получить его из консоли Firebase или консоли API Google, как я выделил на изображениях ниже: —

консоль API Google

Консоль Firebase, щелкните проект -> настройки

Примечание: ключ веб-API консоли Firebase и ключ браузера консоли Google совпадают, вы можете использовать любой из них.

введите описание изображения здесь

введите описание изображения здесь

2- Если вы выполните только первый шаг, вы получите сообщение об ошибке «Неавторизовано». Чтобы решить эту проблему, вам необходимо авторизовать ключ браузера в консоли Google, добавив IP-адрес своего сервера, с которого вы будете отправлять push. Нажмите на значок карандаша редактирования справа от клавиши браузера в консоли API Google, над первым изображением

введите описание изображения здесь

После добавления вашего IP-адреса нажмите «Сохранить». Убедитесь, что ваш токен устройства не пуст, на который вы отправляете push-уведомление, я надеюсь, что ваш push-запрос будет успешно отправлен сейчас.

person
Mehroz Munir
  
schedule
21.10.2016

401 с FCM через HTTPv1 (ошибка и решение для носителя)

Если вы используете FCM через HTTP v1, вам придется сделать два последовательных запроса POST:

1 / В первом вызове вы делаете POST-запрос на https://accounts.google.com/o/oauth2/token (или используя пакеты API), используя ключ учетной записи службы firebase в https: // console. firebase.google.com/u/0/project/{{firebaseProjectName}}/settings/serviceaccounts/adminsdk ‘
, чтобы получить токен доступа.

2 / Затем вам нужно сделать еще один запрос POST на https://fcm.googleapis.com/v1/projects/{{firebaseProjectName}}/messages:send. Если вы выполнили действия по переходу с устаревшего HTTP на HTTP v1 (очень четкая документация) на веб-сайте firebase, вам необходимо внести небольшие изменения в содержимое почтового запроса, а также использовать Bearer $ {accessToken.data}. для авторизации.

В моем случае я неправильно ожидал accessToken в первой функции (забыл ключевое слово await перед функцией, выполняющей почтовый запрос, и AndroidStudio не заметил, что что-то не так).

Убедитесь, что вы ожидаете результата первого запроса на публикацию, так как это Future.

Если вы этого не сделаете, Bearer будет нулевым, когда вы сделаете второй запрос POST, потому что вы его не ждали.

person
Antonin GAVREL
  
schedule
27.01.2021

В ответе C # HttpClient

При неправильном ключе сервера это произойдет, Неверный ключ, Неавторизовать, 401

person
Mahydul Islam Shajal
  
schedule
08.05.2021

Понравилась статья? Поделить с друзьями:

Читайте также:

  • Error 4002 clack
  • Error 40014 exmo
  • Error 4001 unable to initialize windows gaming services
  • Error 4000 twitch ubuntu
  • Error 400 тимспик

  • 0 0 голоса
    Рейтинг статьи
    Подписаться
    Уведомить о
    guest

    0 комментариев
    Старые
    Новые Популярные
    Межтекстовые Отзывы
    Посмотреть все комментарии