{"id":19099964,"url":"https://github.com/marcominerva/SimpleAuthentication","last_synced_at":"2025-04-18T17:32:21.011Z","repository":{"id":37866810,"uuid":"489350261","full_name":"marcominerva/SimpleAuthentication","owner":"marcominerva","description":"A library to easily integrate Authentication in ASP.NET Core projects.","archived":false,"fork":false,"pushed_at":"2025-04-17T08:39:16.000Z","size":381,"stargazers_count":232,"open_issues_count":6,"forks_count":28,"subscribers_count":8,"default_branch":"master","last_synced_at":"2025-04-17T22:41:50.059Z","etag":null,"topics":["apikey","apikey-authentication","aspnetcore","authentication","authorization","basic-authentication","csharp","hacktoberfest","jwt","jwt-authentication","minimal-api","visual-studio","webapi"],"latest_commit_sha":null,"homepage":"","language":"C#","has_issues":true,"has_wiki":null,"has_pages":null,"mirror_url":null,"source_name":null,"license":"mit","status":null,"scm":"git","pull_requests_enabled":true,"icon_url":"https://github.com/marcominerva.png","metadata":{"files":{"readme":"README.md","changelog":null,"contributing":null,"funding":null,"license":"LICENSE","code_of_conduct":null,"threat_model":null,"audit":null,"citation":null,"codeowners":null,"security":null,"support":null,"governance":null,"roadmap":null,"authors":null,"dei":null,"publiccode":null,"codemeta":null}},"created_at":"2022-05-06T12:42:30.000Z","updated_at":"2025-04-17T08:38:54.000Z","dependencies_parsed_at":"2024-10-25T18:33:46.160Z","dependency_job_id":"06e99475-051a-4990-b12b-ff197e26a125","html_url":"https://github.com/marcominerva/SimpleAuthentication","commit_stats":{"total_commits":105,"total_committers":1,"mean_commits":105.0,"dds":0.0,"last_synced_commit":"6aaf63851e9f13a5bddd6b7e6ab2478a3a5f37f5"},"previous_names":[],"tags_count":73,"template":false,"template_full_name":null,"repository_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/marcominerva%2FSimpleAuthentication","tags_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/marcominerva%2FSimpleAuthentication/tags","releases_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/marcominerva%2FSimpleAuthentication/releases","manifests_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/marcominerva%2FSimpleAuthentication/manifests","owner_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners/marcominerva","download_url":"https://codeload.github.com/marcominerva/SimpleAuthentication/tar.gz/refs/heads/master","host":{"name":"GitHub","url":"https://github.com","kind":"github","repositories_count":249485928,"owners_count":21280150,"icon_url":"https://github.com/github.png","version":null,"created_at":"2022-05-30T11:31:42.601Z","updated_at":"2022-07-04T15:15:14.044Z","host_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub","repositories_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories","repository_names_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repository_names","owners_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners"}},"keywords":["apikey","apikey-authentication","aspnetcore","authentication","authorization","basic-authentication","csharp","hacktoberfest","jwt","jwt-authentication","minimal-api","visual-studio","webapi"],"created_at":"2024-11-09T03:52:24.527Z","updated_at":"2025-04-18T17:32:21.003Z","avatar_url":"https://github.com/marcominerva.png","language":"C#","readme":"# Simple Authentication for ASP.NET Core\n\n[![Lint Code Base](https://github.com/marcominerva/SimpleAuthentication/actions/workflows/linter.yml/badge.svg)](https://github.com/marcominerva/SimpleAuthentication/actions/workflows/linter.yml)\n[![CodeQL](https://github.com/marcominerva/SimpleAuthentication/actions/workflows/codeql.yml/badge.svg)](https://github.com/marcominerva/SimpleAuthentication/actions/workflows/codeql.yml)\n[![Nuget](https://img.shields.io/nuget/v/SimpleAuthenticationTools)](https://www.nuget.org/packages/SimpleAuthenticationTools)\n[![Nuget](https://img.shields.io/nuget/dt/SimpleAuthenticationTools)](https://www.nuget.org/packages/SimpleAuthenticationTools)\n[![License: MIT](https://img.shields.io/badge/License-MIT-yellow.svg)](https://github.com/marcominerva/SimpleAuthentication/blob/master/LICENSE)\n\nA 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.\n\n\u003e [!IMPORTANT]\n\u003e **Update from Version 2.x to 3.x**\n\u003e Swashbuckle (Swagger) support has been moved out from SimpleAuthentication. If you're using the `AddSimpleAuthentication` extension method with `AddSwaggerGen`, now you need to install the [SimpleAuthentication.Swashbuckle](https://github.com/marcominerva/SimpleAuthentication/tree/master/src/SimpleAuthentication.Swashbuckle) package.\n\n## Installation\n\nThe library is available on [NuGet](https://www.nuget.org/packages/SimpleAuthenticationTools). Just search for *SimpleAuthenticationTools* in the **Package Manager GUI** or run the following command in the **.NET CLI**:\n\n```shell\ndotnet add package SimpleAuthenticationTools\n```\n## Usage video\n\nTake a look to a quick demo showing how to integrate the library:\n\n[![Simple Authentication for ASP.NET Core](https://raw.githubusercontent.com/marcominerva/SimpleAuthentication/master/Screenshot.jpg)](https://www.youtube.com/watch?v=SVZuaPE2yNc)\n\n## Configuration\n\nAuthentication can be totally configured adding an _Authentication_ section in the _appsettings.json_ file:\n\n```\n\"Authentication\": {\n    \"DefaultScheme\": \"Bearer\", // Optional\n    \"JwtBearer\": {\n        \"SchemeName\": \"Bearer\" // Default: Bearer\n        //\"NameClaimType\": \"user_name\", // Default: http://schemas.xmlsoap.org/ws/2005/05/identity/claims/name\n        //\"RoleClaimType\": \"user_role\", // Default: http://schemas.microsoft.com/ws/2008/06/identity/claims/role\n        \"SecurityKey\": \"supersecretsecuritykey42!\", // Required\n        \"Algorithm\": \"HS256\", // Default: HS256\n        \"Issuers\": [ \"issuer\" ], // Optional\n        \"Audiences\": [ \"audience\" ], // Optional\n        \"ExpirationTime\": \"01:00:00\", // Default: No expiration\n        \"ClockSkew\": \"00:02:00\", // Default: 5 minutes\n        \"EnableJwtBearerService\": true // Default: true\n    },\n    \"ApiKey\": {\n        \"SchemeName\": \"ApiKey\", // Default: ApiKey\n        // You can specify either HeaderName, QueryStringKey or both\n        \"HeaderName\": \"x-api-key\",\n        \"QueryStringKey\": \"code\",\n        //\"NameClaimType\": \"user_name\", // Default: http://schemas.xmlsoap.org/ws/2005/05/identity/claims/name\n        //\"RoleClaimType\": \"user_role\", // Default: http://schemas.microsoft.com/ws/2008/06/identity/claims/role\n        // Uncomment this line if you want to validate the API Key against a fixed value.\n        // Otherwise, you need to register an IApiKeyValidator implementation that will be used\n        // to validate the API Key.\n        //\"ApiKeyValue\": \"f1I7S5GXa4wQDgLQWgz0\",\n        \"UserName\": \"ApiUser\" // Required if ApiKeyValue is used\n    },\n    \"Basic\": {\n        \"SchemeName\": \"Basic\", // Default: Basic\n        //\"NameClaimType\": \"user_name\", // Default: http://schemas.xmlsoap.org/ws/2005/05/identity/claims/name\n        //\"RoleClaimType\": \"user_role\", // Default: http://schemas.microsoft.com/ws/2008/06/identity/claims/role\n        // Uncomment the following lines if you want to validate user name and password\n        // against fixed values.\n        // Otherwise, you need to register an IBasicAuthenticationValidator implementation\n        // that will be used to validate the credentials.\n        //\"UserName\": \"marco\",\n        //\"Password\": \"P@$$w0rd\"\n    }\n}\n```\n\nYou can configure only the kind of authentication you want to use, or you can include all of them.\n\nThe _DefaultScheme_ attribute is used to specify what kind of authentication must be configured as default. Allowed values are the values of the _SchemeName_ attributes.\n\n**Registering authentication at Startup**\n\n```csharp\nusing SimpleAuthentication;\n\nvar builder = WebApplication.CreateBuilder(args);\n\n// ...\n// Registers authentication schemes and services using IConfiguration information (see above).\nbuilder.Services.AddSimpleAuthentication(builder.Configuration);\n\n// ...\n\nvar app = builder.Build();\n\n//...\n// The following middlewares aren't strictly necessary in .NET 7.0 or higher, because they are automatically\n// added when detecting that the corresponding services have been registered. However, you may\n// need to call them explicitly if the default middlewares configuration is not correct for your\n// app, for example when you need to use CORS.\n// Check https://learn.microsoft.com/en-us/aspnet/core/fundamentals/minimal-apis/middleware\n// for more information.\n//app.UseAuthentication();\n//app.UseAuthorization();\n\n//...\n\napp.Run();\n```\n\n**Integrating with Swashbuckle**\n\nIf you're using Swashbuckle (Swagger) to document your API, you can integrate the authentication configuration with the Swagger documentation. Just search for *SimpleAuthenticationTools.Swashbuckle* in the **Package Manager GUI** or run the following command in the **.NET CLI**:\n\n```shell\ndotnet add package SimpleAuthenticationTools.Swashbuckle\n```\n\nThen, you can use the `AddSimpleAuthentication` extension method:\n\n```csharp\nbuilder.Services.AddSwaggerGen(options =\u003e\n{\n    // ...\n    // Add this line to integrate authentication with Swagger.\n    options.AddSimpleAuthentication(builder.Configuration);\n});\n```\n\n**Integrating with Microsoft.AspNetCore.OpenApi (.NET 9 or later)**\n\nStarting from version 9, .NET offer a built-in support for OpenAPI. If you're using the `AddOpenApi` extension method to provide OpenAPI support, you just need to add the corresponding extension method in its declaration (no extra package required):\n\n```csharp\nbuilder.Services.AddOpenApi(options =\u003e\n{\n    // ...\n    // Add this line to integrate authentication with OpenAPI.\n    options.AddSimpleAuthentication(builder.Configuration);\n});\n```\n\n**Creating a JWT Bearer**\n\nWhen using JWT Bearer authentication, you can set the _EnableJwtBearerService_ setting to _true_ to automatically register an implementation of the [IJwtBearerService](https://github.com/marcominerva/SimpleAuthentication/blob/master/src/SimpleAuthentication.Abstractions/JwtBearer/IJwtBearerService.cs) interface to create a valid JWT Bearer, according to the setting you have specified in the _appsettings.json_ file:\n\n```csharp\napp.MapPost(\"api/auth/login\", (LoginRequest loginRequest, IJwtBearerService jwtBearerService) =\u003e\n{\n    // Check for login rights...\n\n    // Add custom claims (optional).\n    var claims = new List\u003cClaim\u003e\n    {\n        new(ClaimTypes.GivenName, \"Marco\"),\n        new(ClaimTypes.Surname, \"Minerva\")\n    };\n\n    var token = jwtBearerService.CreateToken(loginRequest.UserName, claims);\n    return TypedResults.Ok(new LoginResponse(token));\n});\n\npublic record class LoginRequest(string UserName, string Password);\n\npublic record class LoginResponse(string Token);\n```\n\nThe [IJwtBearerService.CreateToken](https://github.com/marcominerva/SimpleAuthentication/blob/master/src/SimpleAuthentication.Abstractions/JwtBearer/IJwtBearerService.cs#L23) 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.\n\n**Supporting multiple API Keys/Basic Authentication credentials**\n\nWhen using API Key or Basic Authentication, you can specify multiple fixed values for authentication:\n\n```json\n\"Authentication\": {\n    \"ApiKey\": {\n        \"ApiKeys\": [\n            {\n                \"Value\": \"key-1\",\n                \"UserName\": \"UserName1\"\n            },\n            {\n                \"Value\": \"key-2\",\n                \"UserName\": \"UserName2\"\n            }\n        ]\n    },\n    \"Basic\": {\n        \"Credentials\": [\n            {\n                \"UserName\": \"UserName1\",\n                \"Password\": \"Password1\"\n            },\n            {\n                \"UserName\": \"UserName2\",\n                \"Password\": \"Password2\"\n            }\n        ]\n    }\n}\n```\n\nWith this configuration, authentication will succedd if any of these credentials are provided.\n\n**Custom Authentication logic for API Keys and Basic Authentication**\n\nIf 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](https://github.com/marcominerva/SimpleAuthentication/blob/master/src/SimpleAuthentication.Abstractions/ApiKey/IApiKeyValidator.cs) or [IBasicAuthenticationValidator.cs](https://github.com/marcominerva/SimpleAuthentication/blob/master/src/SimpleAuthentication.Abstractions/BasicAuthentication/IBasicAuthenticationValidator.cs):\n\n```csharp\nbuilder.Services.AddTransient\u003cIApiKeyValidator, CustomApiKeyValidator\u003e();\nbuilder.Services.AddTransient\u003cIBasicAuthenticationValidator, CustomBasicAuthenticationValidator\u003e();\n//...\n\npublic class CustomApiKeyValidator : IApiKeyValidator\n{\n    public Task\u003cApiKeyValidationResult\u003e ValidateAsync(string apiKey)\n    {\n        var result = apiKey switch\n        {\n            \"ArAilHVOoL3upX78Cohq\" =\u003e ApiKeyValidationResult.Success(\"User 1\"),\n            \"DiUU5EqImTYkxPDAxBVS\" =\u003e ApiKeyValidationResult.Success(\"User 2\"),\n            _ =\u003e ApiKeyValidationResult.Fail(\"Invalid User\")\n        };\n\n        return Task.FromResult(result);\n    }\n}\n\npublic class CustomBasicAuthenticationValidator : IBasicAuthenticationValidator\n{\n    public Task\u003cBasicAuthenticationValidationResult\u003e ValidateAsync(string userName, string password)\n    {\n        if (userName == password)\n        {\n            var claims = new List\u003cClaim\u003e() { new(ClaimTypes.Role, \"User\") };\n            return Task.FromResult(BasicAuthenticationValidationResult.Success(userName, claims));\n        }\n\n        return Task.FromResult(BasicAuthenticationValidationResult.Fail(\"Invalid user\"));\n    }\n}\n```\n\n## Permission-based authorization\n\nThe library provides services for adding permission-based authorization to an ASP.NET Core project. Just use the following registration at startup:\n\n```csharp\n// Enable permission-based authorization.\nbuilder.Services.AddPermissions\u003cT\u003e();\n```\n\nThe **AddPermissions** extension method requires an implementation of the [IPermissionHandler interface](https://github.com/marcominerva/SimpleAuthentication/blob/master/src/SimpleAuthentication.Abstractions/Permissions/IPermissionHandler.cs), that is responsible to check if the user owns the required permissions:\n\n```csharp\npublic interface IPermissionHandler\n{\n    Task\u003cbool\u003e IsGrantedAsync(ClaimsPrincipal user, IEnumerable\u003cstring\u003e permissions);\n}\n```\n\nThe library provides the built-in [ScopeClaimPermissionHandler class](https://github.com/marcominerva/SimpleAuthentication/blob/master/src/SimpleAuthentication/Permissions/ScopeClaimPermissionHandler.cs), 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:\n\n```csharp\nbuilder.Services.AddScopePermissions(); \n// The line above is equivalent to builder.Services.AddPermissions\u003cScopeClaimPermissionHandler\u003e();\n```\n\nBased 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.\n\nThen, just use the [PermissionAttribute](https://github.com/marcominerva/SimpleAuthentication/blob/master/src/SimpleAuthentication.Abstractions/Permissions/PermissionAttribute.cs) or the [RequirePermission](https://github.com/marcominerva/SimpleAuthentication/blob/master/src/SimpleAuthentication/PermissionAuthorizationExtensions.cs#L98) extension method:\n\n```csharp\n// In a Controller\n[Permission(\"profile\")]\npublic ActionResult\u003cUser\u003e Get() =\u003e new User(User.Identity!.Name);\n\n// In a Minimal API\napp.MapGet(\"api/me\", (ClaimsPrincipal user) =\u003e\n{\n    return TypedResults.Ok(new User(user.Identity!.Name));\n})\n.RequirePermission(\"profile\")\n```\n\nWith the [ScopeClaimPermissionHandler](https://github.com/marcominerva/SimpleAuthentication/blob/master/src/SimpleAuthentication/Permissions/ScopeClaimPermissionHandler.cs) 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:\n\n```json\n\"scp\": \"profile email calendar:read\"\n```\n\nIt is also possible to explicitly create a policy that requires the one or more permissions:\n\n```csharp\nbuilder.Services.AddAuthorization(options =\u003e\n{\n    // Define permissions using a policy.\n    options.AddPolicy(\"UserProfile\", builder =\u003e builder.RequirePermission(\"profile\"));\n});\n\n// ...\n\n// In a Controller\n[Authorize(Policy = \"UserProfile\")] \npublic ActionResult\u003cUser\u003e Get() =\u003e new User(User.Identity!.Name);\n\n// In a Minimal API\napp.MapGet(\"api/me\", (ClaimsPrincipal user) =\u003e\n{\n    return TypedResults.Ok(new User(user.Identity!.Name));\n})\n.RequireAuthorization(policyNames: \"UserProfile\")\n```\n\n## Samples\n\n- JWT Bearer ([Controller](https://github.com/marcominerva/SimpleAuthentication/tree/master/samples/Controllers/JwtBearerSample) | [Minimal API](https://github.com/marcominerva/SimpleAuthentication/tree/master/samples/MinimalApis/JwtBearerSample))\n- API Key ([Controller](https://github.com/marcominerva/SimpleAuthentication/tree/master/samples/Controllers/ApiKeySample) | [Minimal API](https://github.com/marcominerva/SimpleAuthentication/tree/master/samples/MinimalApis/ApiKeySample))\n- Basic Authentication ([Controller](https://github.com/marcominerva/SimpleAuthentication/tree/master/samples/Controllers/BasicAuthenticationSample) | [Minimal API](https://github.com/marcominerva/SimpleAuthentication/tree/master/samples/MinimalApis/BasicAuthenticationSample))\n\n## Contribute\n\nThe 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. \n","funding_links":[],"categories":["hacktoberfest"],"sub_categories":[],"project_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fmarcominerva%2FSimpleAuthentication","html_url":"https://awesome.ecosyste.ms/projects/github.com%2Fmarcominerva%2FSimpleAuthentication","lists_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fmarcominerva%2FSimpleAuthentication/lists"}