AuthenticationService.Sqlite 1.1.0

dotnet add package AuthenticationService.Sqlite --version 1.1.0
                    
NuGet\Install-Package AuthenticationService.Sqlite -Version 1.1.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="AuthenticationService.Sqlite" Version="1.1.0" />
                    
For projects that support PackageReference, copy this XML node into the project file to reference the package.
<PackageVersion Include="AuthenticationService.Sqlite" Version="1.1.0" />
                    
Directory.Packages.props
<PackageReference Include="AuthenticationService.Sqlite" />
                    
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 AuthenticationService.Sqlite --version 1.1.0
                    
#r "nuget: AuthenticationService.Sqlite, 1.1.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 AuthenticationService.Sqlite@1.1.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=AuthenticationService.Sqlite&version=1.1.0
                    
Install as a Cake Addin
#tool nuget:?package=AuthenticationService.Sqlite&version=1.1.0
                    
Install as a Cake Tool

AuthenticationService.Sqlite

License: MIT

Описание

Простая, гибкая и легковесная библиотека для добавления аутентификации, авторизации и безопасного RememberMe-функционала в .NET/WPF приложениях. Работает с Dependency Injection. Использует SQLite и встроенный безопасный механизм защиты данных Windows DPAPI. Пароли хэшируются с помощью BCrypt.

Функциональность

  • 🔐 Аутентификация - проверка логина/пароля
  • 👥 Регистрация - создание новых пользователей
  • 🔒 Хэширование паролей - с использованием BCrypt
  • 💾 SQLite хранение - легковесная база данных
  • 🏗️ Интеграция с DI - готовность к использованию в ASP.NET Core и приложениях с DI
  • 📦 Минимальные зависимости - только необходимые пакеты
  • ⭐ Безопасный Remember Me

Быстрый старт

Подключение через Dependency Injection

App.xaml.cs

using AuthenticationService.Sqlite;
using Microsoft.Extensions.DependencyInjection;
using SQLitePCL;
using System.Windows;

namespace TestApp;

public partial class App : Application
{
    public new static App Current => (App)Application.Current;
    public IServiceProvider Services { get; private set; }
    protected override void OnStartup(StartupEventArgs e)
    {
        Batteries.Init(); // Инициализация SQLite - обязательно!
        base.OnStartup(e);

        var services = new ServiceCollection();

        services.AddAuthService("Data Source=auth.db");
        services.AddSingleton<MainWindow>();

        Services = services.BuildServiceProvider();

        //Автоматическое создание БД
        using (var scope = Services.CreateScope())
        {
            var context = scope.ServiceProvider.GetRequiredService<AuthContext>();
            context.Database.EnsureCreated();
        }

        var mainWindow = Services.GetRequiredService<MainWindow>();
        mainWindow.Show();
    }
}

MainWindow.xaml.cs

using AuthenticationService.Sqlite;
using System.Windows;

namespace TestApp;
public partial class MainWindow : Window
{
    private readonly IAuthService _authService;
    public MainWindow(IAuthService authService)
    {
        InitializeComponent();
        _authService = authService ?? throw new ArgumentNullException(nameof(authService));
    }

    private void login_click(object sender, RoutedEventArgs e)
    {
        var login = tbLogin.Text;
        var pass = tbPassword.Text;
        bool result = _authService.LoginUser(login, pass);
        if (result)
            MessageBox.Show("Success!");
        else
            MessageBox.Show("Fail");
    }

    private void register_click(object sender, RoutedEventArgs e)
    {
        var login = tbLogin.Text;
        var pass = tbPassword.Text;
        bool result = _authService.RegisterUser(login, pass);
        if (result)
            MessageBox.Show("Success!");
        else
            MessageBox.Show("User already exists");
    }
}

RememberMe

Сохранение пользователя после успешного входа

private void login_click(object sender, RoutedEventArgs e)
{
    var login = tbLogin.Text;
    var pass = tbPassword.Password;

    bool result = _authService.LoginUser(login, pass);

    if (result)
    {
        if (cbRememberMe.IsChecked == true)
            _authService.RememverMe(login);

        MessageBox.Show("Success!");
    }
    else
    {
        MessageBox.Show("Fail");
    }
}

Автоматический вход при старте приложения

protected override void OnStartup(StartupEventArgs e)
{
    base.OnStartup(e);

    var auth = App.Current.Services.GetRequiredService<IAuthService>();
    var remembered = auth.GetRememberUser();

    if (remembered != null)
    {
        // Пользователь найден — сразу открываем основное окно
        var main = App.Current.Services.GetRequiredService<MainWindow>();
        main.Show();
        return;
    }

    // Иначе — открываем окно авторизации
    var loginWindow = new LoginWindow();
    loginWindow.Show();
}
Product Compatible and additional computed target framework versions.
.NET net9.0-windows7.0 is compatible.  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.1.0 457 12/10/2025
1.0.0 453 12/9/2025