• Stars
    star
    111
  • Rank 308,128 (Top 7 %)
  • Language
    C#
  • License
    MIT License
  • Created about 2 years ago
  • Updated 12 months ago

Reviews

There are no reviews yet. Be the first to send feedback to the community and the maintainers!

Repository Details

A library to easily integrate Authentication in ASP.NET Core projects.

Simple Authentication for ASP.NET Core

Lint Code Base CodeQL Nuget Nuget License: MIT

A library to easily integrate Authentication in ASP.NET Core projects. Currently it supports JWT Bearer, API Key and Basic Authentication in both Controller-based and Minimal API projects.

Installation

The library is available on NuGet. Just search for SimpleAuthenticationTools in the Package Manager GUI or run the following command in the .NET CLI:

dotnet add package SimpleAuthenticationTools

Usage video

Take a look to a quick demo showing how to integrate the library:

Simple Authentication for ASP.NET Core

Configuration

Authentication can be totally configured adding an Authentication section in the appsettings.json file:

"Authentication": {
  "DefaultScheme": "Bearer", // Optional
  "JwtBearer": {
      "SchemeName": "Bearer" // Default: Bearer
      //"NameClaimType": "user_name", // Default: http://schemas.xmlsoap.org/ws/2005/05/identity/claims/name
      //"RoleClaimType": "role", // Default: http://schemas.microsoft.com/ws/2008/06/identity/claims/role"
      "SecurityKey": "supersecretsecuritykey42!", // Required
      "Algorithm": "HS256", // Default: HS256
      "Issuers": [ "issuer" ], // Optional
      "Audiences": [ "audience" ], // Optional
      "ExpirationTime": "01:00:00", // Default: No expiration
      "ClockSkew": "00:02:00", // Default: 5 minutes
      "EnableJwtBearerService": true // Default: true
  },
  "ApiKey": {
      "SchemeName": "MyApiKeyScheme", // Default: ApiKey
      // You can specify either HeaderName, QueryStringKey or both
      "HeaderName": "x-api-key",
      "QueryStringKey": "code",
      // Uncomment this line if you want to validate the API Key against a fixed value.
      // Otherwise, you need to register an IApiKeyValidator implementation that will be used
      // to validate the API Key.
      //"ApiKeyValue": "f1I7S5GXa4wQDgLQWgz0",
      "UserName": "ApiUser" // Required if ApiKeyValue is used
  },
  "Basic": {
      "SchemeName": "Basic", // Default: Basic
      // Uncomment the following lines if you want to validate user name and password
      // against fixed values.
      // Otherwise, you need to register an IBasicAuthenticationValidator implementation
      // that will be used to validate the credentials.
      //"UserName": "marco",
      //"Password": "P@$$w0rd"
  }
}

You can configure only the kind of authentication you want to use, or you can include all of them.

The DefaultScheme attribute is used to specify what kind of authentication must be configured as default. Allowed values are the values of the SchemeName attributes.

Registering authentication at Startup

using SimpleAuthentication;

var builder = WebApplication.CreateBuilder(args);

// ...
// Registers authentication schemes and services using IConfiguration information (see above).
builder.Services.AddSimpleAuthentication(builder.Configuration);

builder.Services.AddSwaggerGen(options =>
{
    // ...
    // Add this line to integrate authentication with Swagger.
    options.AddSimpleAuthentication(builder.Configuration);
});

// ...

var app = builder.Build();

//...
// The following middlewares aren't strictly necessary in .NET 7.0, because they are automatically
// added when detecting that the corresponding services have been registered. However, you may
// need to call them explicitly if the default middlewares configuration is not correct for your
// app, for example when you need to use CORS.
// Check https://learn.microsoft.com/en-us/aspnet/core/fundamentals/minimal-apis/middleware
// for more information.
//app.UseAuthentication();
//app.UseAuthorization();

//...

app.Run();

Creating a JWT Bearer

When using JWT Bearer authentication, you can set the EnableJwtBearerService setting to true to automatically register an implementation of the IJwtBearerService interface to create a valid JWT Bearer, according to the setting you have specified in the appsettings.json file:

app.MapPost("api/auth/login", (LoginRequest loginRequest, IJwtBearerService jwtBearerService) =>
{
    // Check for login rights...

    // Add custom claims (optional).
    var claims = new List<Claim>
    {
        new(ClaimTypes.GivenName, "Marco"),
        new(ClaimTypes.Surname, "Minerva")
    };

    var token = jwtBearerService.CreateToken(loginRequest.UserName, claims);
    return TypedResults.Ok(new LoginResponse(token));
})
.WithOpenApi();

public record class LoginRequest(string UserName, string Password);

public record class LoginResponse(string Token);

The IJwtBearerService.CreateToken method allows to specify the issuer and the audience of the token. If you don't specify any value, the first ones defined in appsettings.json will be used.

Supporting multiple API Keys/Basic Authentication credentials

When using API Key or Basic Authentication, you can specify multiple fixed values for authentication:

"Authentication": {
    "ApiKey": {
        "ApiKeys": [
            {
                "Value": "key-1",
                "UserName": "UserName1"
            },
            {
                "Value": "key-2",
                "UserName": "UserName2"
            }
        ]
    },
    "Basic": {
        "Credentials": [
            {
                "UserName": "UserName1",
                "Password": "Password1"
            },
            {
                "UserName": "UserName2",
                "Password": "Password2"
            }
        ]
    }
}

With this configuration, authentication will succedd if any of these credentials are provided.

Custom Authentication logic for API Keys and Basic Authentication

If you need to implement custom authentication login, for example validating credentials with dynamic values and adding claims to identity, you can omit all the credentials in the appsettings.json file and then provide an implementation of IApiKeyValidator.cs or IBasicAuthenticationValidator.cs:

builder.Services.AddTransient<IApiKeyValidator, CustomApiKeyValidator>();
builder.Services.AddTransient<IBasicAuthenticationValidator, CustomBasicAuthenticationValidator>();
//...

public class CustomApiKeyValidator : IApiKeyValidator
{
    public Task<ApiKeyValidationResult> ValidateAsync(string apiKey)
    {
        var result = apiKey switch
        {
            "ArAilHVOoL3upX78Cohq" => ApiKeyValidationResult.Success("User 1"),
            "DiUU5EqImTYkxPDAxBVS" => ApiKeyValidationResult.Success("User 2"),
            _ => ApiKeyValidationResult.Fail("Invalid User")
        };

        return Task.FromResult(result);
    }
}

public class CustomBasicAuthenticationValidator : IBasicAuthenticationValidator
{
    public Task<BasicAuthenticationValidationResult> ValidateAsync(string userName, string password)
    {
        if (userName == password)
        {
            var claims = new List<Claim>() { new(ClaimTypes.Role, "User") };
            return Task.FromResult(BasicAuthenticationValidationResult.Success(userName, claims));
        }

        return Task.FromResult(BasicAuthenticationValidationResult.Fail("Invalid user"));
    }
}

Permission-based authorization

The library provides services for adding permission-based authorization to an ASP.NET Core project. Just use the following registration at startup:

// Enable permission-based authorization.
builder.Services.AddPermissions<T>();

The AddPermissions extension method requires an implementation of the IPermissionHandler interface, that is responsible to check if the user owns the required permissions:

public interface IPermissionHandler
{
    Task<bool> IsGrantedAsync(ClaimsPrincipal user, IEnumerable<string> permissions);
}

The library provides the built-in ScopeClaimPermissionHandler class, that checks for permissions reading the default scope claims of the current user (scp or http://schemas.microsoft.com/identity/claims/scope). To use this default handler, we can just write this:

builder.Services.AddScopePermissions(); 
// The line above is equivalent to builder.Services.AddPermissions<ScopeClaimPermissionHandler>();

Based on the scenario, we can provide our own implementation, for example reading different claims or using external services (database, HTTP calls, etc.) to get user permissions.

Then, just use the PermissionAttribute or the RequirePermission extension method:

// In a Controller
[Permission("profile")]
public ActionResult<User> Get() => new User(User.Identity!.Name);

// In a Minimal API
app.MapGet("api/me", (ClaimsPrincipal user) =>
{
    return TypedResults.Ok(new User(user.Identity!.Name));
})
.RequirePermission("profile")

With the ScopeClaimPermissionHandler mentioned above, the invocation succeeds if the user has a scp or http://schemas.microsoft.com/identity/claims/scope claim that contains the profile value, for example:

"scp": "profile email calendar:read"

It is also possible to explicitly create a policy that requires the one or more permissions:

builder.Services.AddAuthorization(options =>
{
    // Define permissions using a policy.
    options.AddPolicy("UserProfile", builder => builder.RequirePermission("profile"));
});

// ...

// In a Controller
[Authorize(Policy = "UserProfile")] 
public ActionResult<User> Get() => new User(User.Identity!.Name);

// In a Minimal API
app.MapGet("api/me", (ClaimsPrincipal user) =>
{
    return TypedResults.Ok(new User(user.Identity!.Name));
})
.RequireAuthorization(policyNames: "UserProfile")

Samples

Contribute

The project is constantly evolving. Contributions are welcome. Feel free to file issues and pull requests on the repo and we'll address them as we can.

More Repositories

1

ChatGptNet

A ChatGPT integration library for .NET, supporting both OpenAI and Azure OpenAI Service
C#
214
star
2

TinyHelpers

A collection of helper methods and classes for .NET that I use every day. I have packed them in a single library to avoid code duplication.
C#
179
star
3

MinimalHelpers

A collection of helpers libraries for Minimal API projects.
C#
31
star
4

OperationResults

A set of lightweight libraries to totally decouple operation results and actual application responses.
C#
27
star
5

AlexaSkillTemplate

A Visual Studio Project Template to create Alexa Skills using an Azure Function as backend.
C#
14
star
6

IdentitySample

A sample that shows how to deal with Tokens, Users, Roles, Claims and Policy using ASP.NET Core Identity
C#
13
star
7

TinyCMS

The smallest CMS engine ever, made with ASP. NET Core and Dapper
JavaScript
13
star
8

TranslatorService

A lightweight library that uses Cognitive Translator Service for text translation and Cognitive Speech Service for text-to-speech and speech-to-text
C#
11
star
9

TotalDecoupling

A sample that shows how to write a Web API in which every Controller method is literally formed by a single line of code, yet with the ability to handle all response types, validation errors, etc.
C#
9
star
10

DesktopNet70

A couple of .NET 7.0 Windows Forms and WPF applications that show how to use Host Builder, Dependency Injection, Logging and how to access to Windows 10 APIs.
C#
8
star
11

XamarinNetCore

A sample on how to use .NET 5.0 features like HostBuilder, Dependecy Injection, Logging and HttpClientFactory with Xamarin.Forms
C#
7
star
12

MinimalHelpers.Binding

A library that provides Binding helpers for Minimal API projects.
C#
7
star
13

MyWebApiToolbox

A sample structure of a Web API project with Entity Framework Core, Mapping, Validation, Error Handling and much more.
C#
7
star
14

QueueMessaging

A library that allows to easily integrate Queue messaging with RabbitMQ and Azure Service Bus in a .NET application.
C#
7
star
15

Schrodinger

Like the famous paradox, a .NET type that can be any value until you check it.
C#
6
star
16

EntityDapperCore

An example that shows how to use both Entity Framework Core and Dapper in the same project, sharing the database configuration.
C#
6
star
17

SearchGPT

A sample that shows how to integrate ChatGPT with your own data that comes from Azure Cognitive Search
JavaScript
6
star
18

BabelFish

An app that shows how to use the Microsoft Translator Speech APIs to build a real-time voice translation app for the Universal Windows Platform, event for Windows 10 IoT Core
C#
5
star
19

marcominerva

My public profile
5
star
20

StorageProviders

A collection of Storage Providers for various destinations (e.g. file system and Azure Storage)
C#
5
star
21

WebApiUploaderSample

A sample that shows how to handle file uploads/downloads in an ASP.NET Core Web API
C#
5
star
22

RestLibrary

A lightweight library to perform common REST API calls
C#
5
star
23

AICompanion

A sample app showcasing the use of Cognitive Services within UWP & Xamarin apps: Vision, Face and Custom Vision.
C#
5
star
24

Dapper110

A collection of samples that show how to use some advanced features of Dapper
C#
5
star
25

PeopleFinder

Enrich Azure Cognitive Search index with Face Cognitive Service, Azure Maps & Exif Metadata and access all the information within a UWP client
C#
5
star
26

DallENet

A DALLยทE integration library for .NET
C#
5
star
27

WebAPI-Samples

A collection of Web APIs made with ASP.NET Core 5.0 and related clients to show their usage
C#
4
star
28

UWPCustomVisionCompanion

A sample app showcasing the use of Custom Vision in the Universal Windows Platform.
C#
4
star
29

WeatherApp

A sample that shows how to leverage .NET 5.0 features like HostBuilder, ServiceProvider, Logging and Cache on every supported platform
C#
4
star
30

MultiTenant

An ASP.NET Core application that uses wildcard domains to handle multi-tenancy
C#
4
star
31

AwesomeBackend

A sample API backend made with ASP.NET Core 5.0
C#
4
star
32

LoggingNetCore

A sample that shows how to use Logging features of .NET on every supported platforms
C#
4
star
33

ErrorHandling

Some samples that show how to correctly handle errors in Web API projects
C#
4
star
34

customvision-trainer

A small application that allows to automatically upload and tag images for Custom Vision Service
C#
4
star
35

Minimal-IoT

A sample that showcases how to use Minimal APIs to build a Web Server to control IoT devices
C#
3
star
36

LocalizationSample

A sample about how to handle Localization with ASP.NET Core WEB APIs
C#
3
star
37

FluentEmailSample

A Web API that uses FluentEmail to send e-mails, with the support for Sendinblue
C#
3
star
38

ChatGptPlayground

A ready-to-use ASP.NET Core chat application backed by a Minimal API that can be used to test ChatGPT workflows
JavaScript
3
star
39

HangfireSample

A collection of samples about using Hangfire in a Web API application
C#
3
star
40

Friendbook

A sample Web API for managing a friends' list
C#
3
star
41

MinimalApiHang

This repository shows a problem with Swagger when using WithOpenApi extension method in a Minimal API project
C#
2
star
42

AI-Samples

A collection of AI related samples made with different frameworks
C#
2
star
43

ValidationSample

A sample that shows how to use FluentValidation in .NET
C#
2
star
44

AspNetCoreWithAlpineJs

A sample that shows how to integrate Alpine.js with ASP.NET Core Razor Pages and Web API
JavaScript
2
star
45

MinimalApiSample

A sample that showcases Minimal APIs features.
C#
2
star
46

SqlDatabaseProject

SQL Server Database Project sample
TSQL
2
star
47

EntityFrameworkCore7Samples

A collection of samples about the main new features available in Entity Framework Core 7.0
C#
2
star
48

DateTimeMadness

A collection of use cases and samples that show how to manage dates and times in a backend
C#
2
star
49

DateTimeOnly

A repository that shows how to work with DateOnly and TimeOnly data types with .NET 6.0, ASP.NET Core and Entity Framework Core 6.0
C#
2
star
50

Raspberry-Jukebox

A remotely controlled Jukebox built with a Raspberry Pi 2 running Windows 10 IoT Core
JavaScript
2
star
51

SortingPagination

A sample that shows how to efficiently handle dynamic sorting and pagination of data that come from a database, using Entity Framework Core or Dapper
C#
2
star
52

AspNetCore7Samples

A collection of samples about the main new features available in ASP.NET Core 7.0
C#
2
star
53

MultilanguageChat

This project shows how to use Azure SignalR, Microsoft Translator and Speech Service to build a real-time voice translation system
C#
2
star
54

CognitiveSearch

Samples about Azure Cognitive Search with a UWP client
C#
1
star
55

Kowalski

A personal assistant made with LUIS and the Bot Framework, running on a Windows 10 IoT Core device
C#
1
star
56

RateLimiterSample

A sample that shows how to use the Rate Limiter of ASP.NET Core 7.0 in conjunction with Authentication
C#
1
star
57

GalacticProject

Sample projects that show how to not reinvent the wheel while developing
C#
1
star
58

EntityFrameworkCoreAuditing

This repository show different ways to audit database changes with Entity Framework Core
C#
1
star
59

EntityFrameworkCoreTipsTricks

A collection of code samples that can be useful when using Entity Framework Core
C#
1
star
60

Swagger

A sample that shows how to effectively integrate Swagger into an ASP.NET Core 6.0 Web API
C#
1
star
61

TheMovieDbApiClient

A small library that allows to access the API of The Movie Database (https://www.themoviedb.org)
C#
1
star
62

MultipleAuthenticationProviders

A sample that shows how to handle multiple authentication providers in an ASP.NET Core Web API project
C#
1
star
63

marcominerva.github.io

Sharp Design Web Site
HTML
1
star
64

SecondaryClock

A clock that is shown on secondary (last) Taskbar on Windows 11.
C#
1
star
65

OutputCacheIssue

This repository shows an inconsistency in Output caching behavior documentation.
C#
1
star
66

ParameterRenameIssue

This repository shows that Route, Query and Header parameter names are ignored when using WithOpenApi extension method
C#
1
star
67

RandomPhotos

Use AI to generate random photos
JavaScript
1
star
68

TranslatorGPT

Translate text using AI
JavaScript
1
star
69

DataProtectionSample

This example shows how to use the DataProtection APIs with ASP.NET Core
C#
1
star
70

PathIssue

This repository shows that Route parameters are not set as required when using WithOpenApi and Nullable Reference Types are disabled
C#
1
star
71

OpenApiParameterIssue

This repository shows a problem with OpenAPI definition of path, query and header parameters when there is a body and we're using WithOpenApi extension method
C#
1
star
72

KeyedServicesIssue

This repository shows a different behavior of FromKeyedServices attribute in Minimal APIs endpoint handler and inside a class library
C#
1
star
73

CustomCommands

A sample that shows how to integrate Custom Commands in a real system, with support for Wake Word.
C#
1
star