KoukiSimpleAuth 1.0.2

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

KoukiSimpleAuth

KoukiSimpleAuth is an open-source ASP.NET Core library designed to simplify user authentication and authorization in web applications. This library offers a robust solution for handling common authentication needs, such as user registration, login, and JWT-based security, making it easy to integrate a reliable authentication system into any ASP.NET Core project.

Features

  • User Registration and Login: Quickly add secure user registration and login functionality.
  • JWT Authentication: Secure API endpoints with JSON Web Tokens, making user authentication scalable and efficient.
  • Role-Based Authorization: Easily manage user roles and permissions.
  • Social Media Authentication: Extendable to allow authentication through social media platforms (e.g., Google, Facebook).
  • Modular Services: Lightweight and customizable, allowing for easy integration with other services.

Getting Started

To start using KoukiSimpleAuth, follow these steps to set up the library in your ASP.NET Core project.

Prerequisites

  • .NET Core 6.0 or later
  • ASP.NET Core Web API

Installation

  1. install it via NuGet:
  install-package KoukiSimpleAuth

Setup

  1. Configure appsettings.json Add your database connection string and JWT settings in the appsettings.json file of your ASP.NET Core project:
{
  "ConnectionStrings": {
    "DefaultConnection": "YourDatabaseConnectionStringHere"
  },
  "Jwt": {
    "Key": "YourSecretKeyHere",
  }
}
  1. Register Services In Program.cs, configure your authentication library by adding the required services:
public class Program
{
    public static void Main(string[] args)
    {
        var builder = WebApplication.CreateBuilder(args);

        // Add controllers
        builder.Services.AddControllers();

        // Register database context
        var connectionString = builder.Configuration.GetConnectionString("DefaultConnection");
        builder.Services.AddDbContext<ApplicationDbContext>(options =>
            options.UseMySql(connectionString, ServerVersion.AutoDetect(connectionString)));

        // Register JWT authentication
        builder.Services.AddAuthentication(options =>
        {
            options.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme;
            options.DefaultChallengeScheme = JwtBearerDefaults.AuthenticationScheme;
        }).AddJwtBearer(options =>
        {
            options.TokenValidationParameters = new TokenValidationParameters
            {
                ValidateIssuerSigningKey = true,
                IssuerSigningKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(builder.Configuration["Jwt:Key"])),
                ValidateIssuer = false,
                ValidateAudience = false
            };
        });

        // Register your library's AuthService
        builder.Services.AddScoped<IAuthService, AuthService<ApplicationDbContext>>();

        var app = builder.Build();

        // Configure the HTTP request pipeline.
        if (app.Environment.IsDevelopment())
        {
            app.UseDeveloperExceptionPage();
            app.UseSwagger();
            app.UseSwaggerUI();
        }

        app.UseAuthentication();
        app.UseAuthorization();

        app.MapControllers();

        app.Run();
    }
}

  1. Create API Endpoints In your ASP.NET Core project, create controllers to handle registration and login requests using the KoukiSimpleAuth services.

Example of a UsersController:

using Microsoft.AspNetCore.Mvc;
using SimpleAuth.Models;
using SimpleAuth.Services;

namespace YourProjectName.Controllers
{
    [ApiController]
    [Route("api/[controller]")]
    public class AuthController : ControllerBase
    {
        private readonly IAuthService _authService;

        public AuthController(IAuthService authService)
        {
            _authService = authService;
        }

        [HttpPost("register")]
        public async Task<IActionResult> Register([FromBody] UserDTO userDTO)
        {
            if (!ModelState.IsValid)
            {
                return BadRequest(ModelState);
            }

            var result = await _authService.RegisterAsync(userDTO);
            return Ok(result);
        }

        [HttpPost("login")]
        public async Task<IActionResult> Login([FromBody] LoginRequest loginRequest)
        {
            if (!ModelState.IsValid)
            {
                return BadRequest(ModelState);
            }

            var token = await _authService.LoginAsync(loginRequest.Username, loginRequest.Password);
            return Ok(new { Token = token });
        }
    }

    public class LoginRequest
    {
        public string Username { get; set; }
        public string Password { get; set; }
    }
}

Contributing

If you'd like to contribute to KoukiSimpleAuth, feel free to fork the repository and submit a pull request. We welcome all contributions to improve the functionality and usability of the library.

License

MIT License

Copyright (c) 2024 Kouki Ahmed

Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.

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.4 158 11/5/2024
1.0.3 140 11/5/2024
1.0.2 150 11/5/2024
1.0.1 153 11/5/2024
1.0.0 144 11/5/2024