AuthenticationService.Sqlite 1.2.0

There is a newer version of this package available.
See the version list below for details.
dotnet add package AuthenticationService.Sqlite --version 1.2.0
                    
NuGet\Install-Package AuthenticationService.Sqlite -Version 1.2.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.2.0" />
                    
For projects that support PackageReference, copy this XML node into the project file to reference the package.
<PackageVersion Include="AuthenticationService.Sqlite" Version="1.2.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.2.0
                    
#r "nuget: AuthenticationService.Sqlite, 1.2.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.2.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.2.0
                    
Install as a Cake Addin
#tool nuget:?package=AuthenticationService.Sqlite&version=1.2.0
                    
Install as a Cake Tool

AuthenticationService.Sqlite

NuGet

License: MIT

Установка

Package Manager
Install-Package AuthenticationService.Sqlite
.NET CLI
dotnet add package AuthenticationService.Sqlite

Описание

Простая, гибкая и легковесная библиотека для добавления аутентификации, авторизации и безопасного 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={DirectoryHelper.GetAppDataPath("TestApp", "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");
    }
}

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

public MainWindow(IAuthService authService)
    {
        InitializeComponent();
        _authService = authService ?? throw new ArgumentNullException(nameof(authService));

        var person = _authService.GetRememberUser();
        if(person is User user)
        {
            MessageBox.Show($"Добро пожаловать {person.UserName}");
        }
        else if(person is Admin admin)
        {
            MessageBox.Show($"Добро пожаловать, Админ {person.UserName}");
        }
    }
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.3.0 41 2/9/2026
1.2.1 42 2/9/2026
1.2.0 71 2/5/2026
1.1.0 466 12/10/2025
1.0.0 463 12/9/2025