Отправка сообщений через FCM работала вчера, но сегодня я получаю следующую ошибку:
В запросе отсутствуют необходимые учетные данные для аутентификации. Ожидаемый токен доступа OAuth 2, файл cookie для входа или другие действительные учетные данные для аутентификации. См.
https://developers.google.com/identity/ ... le-project.
В качестве первого шага я создал новый файл JSON в Firebase, но по-прежнему получаю ту же ошибку. Как это исправить?
public async Task SendPushNotificationAsync(string fcmToken, string title, string message)
{
if (string.IsNullOrWhiteSpace(fcmToken))
{
_logger.LogWarning("FCM token is null or empty");
throw new ArgumentException("FCM token cannot be null or empty", nameof(fcmToken));
}
if (FirebaseApp.DefaultInstance == null)
{
_logger.LogError("Firebase App is not initialized. DefaultInstance is null");
throw new ApplicationException("Firebase App is not initialized");
}
var notification = new Message
{
Token = fcmToken,
Notification = new FirebaseAdmin.Messaging.Notification
{
Title = title,
Body = message
},
Apns = new ApnsConfig()
{
Aps = new Aps()
{
Alert = new ApsAlert()
{
Title = title,
Body = message
},
Sound = "default",
Badge = 1,
},
}
};
try
{
_logger.LogInformation("Sending push notification to token: {Token}", fcmToken);
var messageId = await FirebaseMessaging.DefaultInstance.SendAsync(notification); // Error Line
_logger.LogInformation("Push notification sent successfully. Message ID: {MessageId}", messageId);
}
catch (Exception e)
{
_logger.LogError(e, "Error sending push notification to token {Token}", fcmToken);
throw new ApplicationException($"Error sending push notification: {e.Message}", e);
}
}
Служба CTOR:
public FirebasePushService(IConfiguration configuration, ILogger logger, IWebHostEnvironment environment)
{
_logger = logger;
// Initialize Firebase Admin SDK if not already initialized
if (FirebaseApp.DefaultInstance == null)
{
var firebaseConfigPath = configuration["Firebase:ConfigPath"];
if (string.IsNullOrEmpty(firebaseConfigPath))
{
throw new ApplicationException("Firebase:ConfigPath configuration is missing");
}
// Try to find the file in multiple locations, using ContentRootPath as primary source
var possiblePaths = new[]
{
firebaseConfigPath,
Path.Combine(environment.ContentRootPath, firebaseConfigPath),
Path.Combine(AppDomain.CurrentDomain.BaseDirectory, firebaseConfigPath),
Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "..", firebaseConfigPath)
};
var configPath = possiblePaths.FirstOrDefault(File.Exists);
if (configPath == null)
{
_logger.LogError("Firebase configuration file not found in any of these locations: {Paths}",
string.Join(", ", possiblePaths));
throw new ApplicationException(
$"Firebase configuration file not found in any of these locations: {string.Join(", ", possiblePaths)}");
}
try
{
_logger.LogInformation("Initializing Firebase with config file: {ConfigPath}", configPath);
FirebaseApp.Create(new AppOptions()
{
Credential = GoogleCredential.FromFile(configPath)
});
_logger.LogInformation("Firebase initialized successfully");
}
catch (Exception ex)
{
_logger.LogError(ex, "Failed to initialize Firebase Admin SDK");
throw;
}
}
}
Подробнее здесь: https://stackoverflow.com/questions/798 ... tion-error
Ошибка отправки push-уведомления .NET Firebase ⇐ C#
Место общения программистов C#
-
Anonymous
1766742674
Anonymous
Отправка сообщений через FCM работала вчера, но сегодня я получаю следующую ошибку:
В запросе отсутствуют необходимые учетные данные для аутентификации. Ожидаемый токен доступа OAuth 2, файл cookie для входа или другие действительные учетные данные для аутентификации. См.
https://developers.google.com/identity/sign-in/web/devconsole-project.
В качестве первого шага я создал новый файл JSON в Firebase, но по-прежнему получаю ту же ошибку. Как это исправить?
public async Task SendPushNotificationAsync(string fcmToken, string title, string message)
{
if (string.IsNullOrWhiteSpace(fcmToken))
{
_logger.LogWarning("FCM token is null or empty");
throw new ArgumentException("FCM token cannot be null or empty", nameof(fcmToken));
}
if (FirebaseApp.DefaultInstance == null)
{
_logger.LogError("Firebase App is not initialized. DefaultInstance is null");
throw new ApplicationException("Firebase App is not initialized");
}
var notification = new Message
{
Token = fcmToken,
Notification = new FirebaseAdmin.Messaging.Notification
{
Title = title,
Body = message
},
Apns = new ApnsConfig()
{
Aps = new Aps()
{
Alert = new ApsAlert()
{
Title = title,
Body = message
},
Sound = "default",
Badge = 1,
},
}
};
try
{
_logger.LogInformation("Sending push notification to token: {Token}", fcmToken);
var messageId = await FirebaseMessaging.DefaultInstance.SendAsync(notification); // Error Line
_logger.LogInformation("Push notification sent successfully. Message ID: {MessageId}", messageId);
}
catch (Exception e)
{
_logger.LogError(e, "Error sending push notification to token {Token}", fcmToken);
throw new ApplicationException($"Error sending push notification: {e.Message}", e);
}
}
Служба CTOR:
public FirebasePushService(IConfiguration configuration, ILogger logger, IWebHostEnvironment environment)
{
_logger = logger;
// Initialize Firebase Admin SDK if not already initialized
if (FirebaseApp.DefaultInstance == null)
{
var firebaseConfigPath = configuration["Firebase:ConfigPath"];
if (string.IsNullOrEmpty(firebaseConfigPath))
{
throw new ApplicationException("Firebase:ConfigPath configuration is missing");
}
// Try to find the file in multiple locations, using ContentRootPath as primary source
var possiblePaths = new[]
{
firebaseConfigPath,
Path.Combine(environment.ContentRootPath, firebaseConfigPath),
Path.Combine(AppDomain.CurrentDomain.BaseDirectory, firebaseConfigPath),
Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "..", firebaseConfigPath)
};
var configPath = possiblePaths.FirstOrDefault(File.Exists);
if (configPath == null)
{
_logger.LogError("Firebase configuration file not found in any of these locations: {Paths}",
string.Join(", ", possiblePaths));
throw new ApplicationException(
$"Firebase configuration file not found in any of these locations: {string.Join(", ", possiblePaths)}");
}
try
{
_logger.LogInformation("Initializing Firebase with config file: {ConfigPath}", configPath);
FirebaseApp.Create(new AppOptions()
{
Credential = GoogleCredential.FromFile(configPath)
});
_logger.LogInformation("Firebase initialized successfully");
}
catch (Exception ex)
{
_logger.LogError(ex, "Failed to initialize Firebase Admin SDK");
throw;
}
}
}
Подробнее здесь: [url]https://stackoverflow.com/questions/79853434/net-firebase-send-push-notification-error[/url]
Ответить
1 сообщение
• Страница 1 из 1
Перейти
- Кемерово-IT
- ↳ Javascript
- ↳ C#
- ↳ JAVA
- ↳ Elasticsearch aggregation
- ↳ Python
- ↳ Php
- ↳ Android
- ↳ Html
- ↳ Jquery
- ↳ C++
- ↳ IOS
- ↳ CSS
- ↳ Excel
- ↳ Linux
- ↳ Apache
- ↳ MySql
- Детский мир
- Для души
- ↳ Музыкальные инструменты даром
- ↳ Печатная продукция даром
- Внешняя красота и здоровье
- ↳ Одежда и обувь для взрослых даром
- ↳ Товары для здоровья
- ↳ Физкультура и спорт
- Техника - даром!
- ↳ Автомобилистам
- ↳ Компьютерная техника
- ↳ Плиты: газовые и электрические
- ↳ Холодильники
- ↳ Стиральные машины
- ↳ Телевизоры
- ↳ Телефоны, смартфоны, плашеты
- ↳ Швейные машинки
- ↳ Прочая электроника и техника
- ↳ Фототехника
- Ремонт и интерьер
- ↳ Стройматериалы, инструмент
- ↳ Мебель и предметы интерьера даром
- ↳ Cантехника
- Другие темы
- ↳ Разное даром
- ↳ Давай меняться!
- ↳ Отдам\возьму за копеечку
- ↳ Работа и подработка в Кемерове
- ↳ Давай с тобой поговорим...
Мобильная версия