Cross.Identity 1.0.0

dotnet add package Cross.Identity --version 1.0.0
                    
NuGet\Install-Package Cross.Identity -Version 1.0.0
                    
This command is intended to be used within the Package Manager Console in Visual Studio, as it uses the NuGet module's version of Install-Package.
<PackageReference Include="Cross.Identity" Version="1.0.0" />
                    
For projects that support PackageReference, copy this XML node into the project file to reference the package.
<PackageVersion Include="Cross.Identity" Version="1.0.0" />
                    
Directory.Packages.props
<PackageReference Include="Cross.Identity" />
                    
Project file
For projects that support Central Package Management (CPM), copy this XML node into the solution Directory.Packages.props file to version the package.
paket add Cross.Identity --version 1.0.0
                    
#r "nuget: Cross.Identity, 1.0.0"
                    
#r directive can be used in F# Interactive and Polyglot Notebooks. Copy this into the interactive tool or source code of the script to reference the package.
#:package Cross.Identity@1.0.0
                    
#:package directive can be used in C# file-based apps starting in .NET 10 preview 4. Copy this into a .cs file before any lines of code to reference the package.
#addin nuget:?package=Cross.Identity&version=1.0.0
                    
Install as a Cake Addin
#tool nuget:?package=Cross.Identity&version=1.0.0
                    
Install as a Cake Tool

Cross.Identity

Библиотека идентификации и аутентификации для .NET: настраиваемые сценарии (регистрация, вход, восстановление пароля, выдача и обновление токенов), JWT, Argon2, верификация по email/SMS, процессный движок с JSON-описанием потоков.

Возможности

  • Process Engine — выполнение сценариев (flow) по JSON-дефинициям с последовательными шагами (steps).
  • Потоки — регистрация, вход по паролю/коду, forgot password, token, refresh token, получение пользователя, запрос и проверка кодов (email/SMS).
  • JWT — выпуск и валидация access/refresh токенов, настраиваемые claims и время жизни.
  • Безопасность — хеширование паролей (Argon2), одноразовые коды, нормализация телефонов.
  • Каналы — email и SMS (отправка кодов через Cross.Notification).
  • Формы — декларативное описание полей и правил валидации (equal, requiredIf, atLeastOneRequired и др.).

Требования

  • .NET 8.0

Структура решения

Cross.Identity.slnx
├── Cross.Identity               # Основная библиотека (flow, JWT, сущности, сервисы)
├── Cross.Identity.UnitTests     # Юнит-тесты (NUnit, Moq, FluentAssertions)
├── Cross.Notification           # Отправка уведомлений: Email (MailKit), SMS (net7.0/net8.0)
├── Cross.PepperVault            # Хранение секретов (pepper и др.)
├── Cross.PepperVault.*          # Провайдеры: Env, FileJson, AwsSecretsJson, AzureKv*, GcpSecretManagerJson, HcvKv2Json
├── _nuget/                      # config.nuspec для публикации пакета Cross.Identity
├── .github/workflows/           # CI (dotnet.yml)
├── RefreshToken.md              # Рекомендации по срокам жизни и ротации refresh-токенов
├── LICENSE.md
└── README.md

Структура проекта Cross.Identity

Cross.Identity/
├── FlowExecutor.cs, IFlowExecutor.cs   # Точка входа: выполнение flow по (flow, operation) и входному словарю
├── IdentityConstants.cs, ClaimConstants.cs
├── Entities/                           # EF Core-сущности и конфигурации
│   ├── UserAccountEntity, AccessTokenEntity, RefreshTokenEntity
│   ├── EmailVerificationEntity, PhoneVerificationEntity
│   ├── ProviderEntity, UserExternalLoginEntity
│   └── *Configuration
├── Infrastructure/
│   └── IdentityContext.cs               # DbContext
├── Services/                            # Доменные сервисы
│   ├── UserService, IUserService
│   ├── CodeService, ICodeService
│   ├── JwtTokenService, IJwtTokenService
│   └── Crypto/                          # PasswordHasher (Argon2), PhoneNormalizer
├── Dtos/                                # FlowResult, ResolveBy, NotificationMessage
├── Options/                             # AuthenticationOptions
├── Helpers/                             # CodeGeneratorHelper, JwtKeys
├── Extensions/                          # ServiceCollectionExtensions (AddCrossIdentity, провайдеры дефиниций)
└── ProcessEngine/
    ├── Core/                            # Ядро движка
    │   ├── Bag, BagKey, BagMapExtensions
    │   ├── IStep, IStepFactory, StepRegistry, StepResult
    │   ├── ProcessLoader, ProcessBuilder, ProcessExecutor
    │   ├── IRequestInput, RequestInput
    │   ├── Enums/                       # ChannelEnum, FlowOperationEnum, StepStatusEnum
    │   └── Forms/                       # Схемы форм и валидация
    │       ├── FormSchema, FieldDescriptor, FieldTypeEnum
    │       ├── ValidatorFactories/      # UnifiedFormValidatorFactory, правила (Equal, RequiredIf, AtLeastOneRequired, …)
    │       └── Providers/               # IFormSchemaProvider, InMemoryFormSchemaProvider
    ├── Steps/                           # Реализации шагов (CollectForm, CreateUser, SendCode, Token, …)
    ├── Factories/                       # Фабрики шагов (CollectFormStepFactory, TokenStepFactory, …)
    └── Definitions/
        ├── Flows/                       # JSON-файлы сценариев (license.Register, game.Token, shop.auth, …)
        ├── Templates/                   # Шаблоны писем (register.*.html/txt, verify.*, reset.*)
        ├── Providers/                   # IProcessDefinitionProvider, Composite, FileSystem, EmbeddedResource
        └── Helpers/                     # JsonHelpers

Использование

  1. Подключение в приложении (ASP.NET Core):
services.AddCrossIdentity(configuration);
// Регистрирует: IFlowExecutor, StepRegistry, все IStepFactory, UserService, CodeService, JwtTokenService,
// провайдер дефиниций (файлы + embedded), формы и т.д.
  1. Выполнение сценария — в контроллере или минимальном API передайте тело запроса как словарь и вызовите:
var result = await _flowExecutor.ExecuteAsync(
    input: requestBodyAsDictionary,
    flow: "license",           // например: license, game, shop, edoctors
    operation: FlowOperationEnum.Token,
    cancellationToken);
// result.Data — объект с полями, заданными шагом collectResult (например access_token, refresh_token).
  1. Дефиниции потоков — JSON в ProcessEngine/Definitions/Flows/ (и при необходимости из файловой системы). Имена файлов: {flow}.{Operation}.json (например license.Token.json, game.Register.json). Подробное описание всех flow и шагов — в ProcessEngine/Definitions/Flows/README.md.

Зависимости (NuGet)

  • Cross.ErrorHandlers
  • Cross.Headers
  • Konscious.Security.Cryptography.Argon2
  • Magick.NET.Core
  • Microsoft.EntityFrameworkCore
  • Microsoft.EntityFrameworkCore.Relational
  • Microsoft.Extensions.Http
  • PhoneNumbersCore
  • System.IdentityModel.Tokens.Jwt
  • ProjectReference: Cross.Notification, Cross.PepperVault

Сборка и тесты

dotnet build
dotnet test

Unit-тесты

Используется соглашение именования Given_When_Then:

  • Given — контекст/предусловия.
  • When — действие.
  • Then — ожидаемый результат.

Пример: Given_ExistingUser_When_RequestCode_Then_SendsCodeAndReturnsLastCode.

Тесты потоков и шагов расположены в Cross.Identity.UnitTests/Identity/ (FlowTests, StepTests, StepFactoryTests).

Дополнительно

  • RefreshToken.md — рекомендации по срокам жизни access/refresh токенов и ротации.
  • LICENSE.md — лицензия.
Product Compatible and additional computed target framework versions.
.NET net8.0 is compatible.  net8.0-android was computed.  net8.0-browser was computed.  net8.0-ios was computed.  net8.0-maccatalyst was computed.  net8.0-macos was computed.  net8.0-tvos was computed.  net8.0-windows was computed.  net9.0 was computed.  net9.0-android was computed.  net9.0-browser was computed.  net9.0-ios was computed.  net9.0-maccatalyst was computed.  net9.0-macos was computed.  net9.0-tvos was computed.  net9.0-windows was computed.  net10.0 was computed.  net10.0-android was computed.  net10.0-browser was computed.  net10.0-ios was computed.  net10.0-maccatalyst was computed.  net10.0-macos was computed.  net10.0-tvos was computed.  net10.0-windows was computed. 
Compatible target framework(s)
Included target framework(s) (in package)
Learn more about Target Frameworks and .NET Standard.

NuGet packages

This package is not used by any NuGet packages.

GitHub repositories

This package is not used by any popular GitHub repositories.

Version Downloads Last Updated
1.0.0 68 2/28/2026
1.0.0-dev.23 42 2/24/2026

Cross.Identity: identity and authentication flows, JWT, process engine.