Allows you to authenticate a user through GitHub, Google, VK, Microsoft Live, Yandex in just two method calls and get information about the user in a unified form.
$ dotnet add package Dm.OAuth2.ClientSmall library for authentication of users on the third-party services supporting OAuth2 protocol: Google, Yandex, etc - nothing more, only authorization and obtaining information about the user. Deep rework of the project https://github.com/titarenko/OAuth2.
The main difference is that the user data model is simplified as much as possible, the second important point is that the implemented clients can be configured once and registered in the IServiceCollection as singleton objects, the methods is thread-safe.
Clients can create instance of the inherited user's data model - this is sometimes necessary when there are additional fields in the database and you can immediately save the created model without having to transfer data between objects.
The infrastructure is also prepared to verify work with services and testing data.
First release, version 1.0.11, I use in your projects. At the moment, work has been implemented:
UPD 24.11.2025: Added NET10 target in version 1.0.15.
A test site has been made to verify work with services. XUnit tests are made as close as possible to real work, but without real access to services
dotnet add package Dm.OAuth2.Client
// Somewhere in the service configuration
Services.AddSingleton(new OAuth2.Client.For.Google(new Options
{
ClientID = "...",
ClientSecret = "...",
Scope = "...",
RedirectURI = "..."
}));
var url = HttpContext.RequestServices.GetServices<OAuth2.Client.For.Google>().GetLoginURIAsync(state);
// Output url in the template
public async Task<IActionResult> Callback(string code, string? state)
{
try
{
var client = HttpContext.RequestServices.GetServices<OAuth2.Client.For.Google>();
var user = await client.GetUserInfoAsync(Request.Query);
// Work with user data
return RedirectOnSuccess(user);
} catch(Exception ex)
{
return RedirectToError(ex);
}
}
A more complete example of using clients can be found in the OAuth2.Client.TestWeb project.
Steps to create a new client for the service:
SomeService<TUserInfo> : OAuth2Based<TUserInfo> and SomeService : SomeService<UserInfo>OAuth2.Client.TestWeb and debug work with the serviceOAuth2.Client.TestWeb and the service, create a test in the project OAuth2.Client.XUnitTest==Need help translating documentation and comments into English.==
Небольшая библиотека для идентификации пользователей на сторонних сервисах, поддерживающих OAuth2 протокол: Google, Yandex и т.д. - ничего лишнего, только авторизация и получение информации о пользователе. Глубокая переработка проекта https://github.com/titarenko/OAuth2.
Основное отличие - максимально упрощена модель данных пользователя, второй важный момент - реализованные клиенты могут быть сконфингурированы один раз и зарегистрированы в IServiceCollection как singleton объекты, работа методов потокобезопасна.
Клиенты могут создавать наследников модели данных пользователя - это иногда необходимо, когда в базе данных есть дополнительные поля и можно сразу сохранять созданную модель без необходимости переносить данные между моделями.
Так же подготовлена инфраструктура для проверки работы с сервисами и тестирования обмена данными.
Первый выпуск, версия 1.0.11, использую в своих проектах. На данный момент реализована работа с сервисами:
Обновление 24.11.2025: Добавлена сборка для NET10 в версии 1.0.15.
Сделан тестовый сайт для проверки работы с сервисами. Сделаны тесты, максимально приближенные к реальной работе, но без реального обращения к сервисам.
dotnet add package Dm.OAuth2.Client
// Где-то в конфигурации сервисов
Services.AddSingleton(new OAuth2.Client.For.Google(new Options
{
ClientID = "...",
ClientSecret = "...",
Scope = "...",
RedirectURI = "..."
}));
var url = HttpContext.RequestServices.GetServices<OAuth2.Client.For.Google>().GetLoginURIAsync(state);
// Вывод url в шаблоне
public async Task<IActionResult> Callback(string code, string? state)
{
try
{
var client = HttpContext.RequestServices.GetServices<OAuth2.Client.For.Google>();
var user = await client.GetUserInfoAsync(Request.Query);
// Работа с полученными данными
return RedirectOnSuccess(user);
} catch(Exception ex)
{
return RedirectToError(ex);
}
}
Более полный пример использования клиентов можно найти в проекте OAuth2.Client.TestWeb.
Для создания клиента для сервиса нужно:
SomeService<TUserInfo> : OAuth2Based<TUserInfo> и SomeService : SomeService<UserInfo>OAuth2.Client.TestWeb и отладить работу с сервисомOAuth2.Client.TestWeb и сервиса создать тест в проекте OAuth2.Client.XUnitTest==Требуется помощь в переводе документации и комментариев на английский язык.==