{"id":26401615,"url":"https://github.com/mihirdilip/aspnetcore-authentication-basic","last_synced_at":"2025-04-09T13:07:13.345Z","repository":{"id":35401120,"uuid":"126197195","full_name":"mihirdilip/aspnetcore-authentication-basic","owner":"mihirdilip","description":"Easy to use and very light weight Microsoft style Basic Scheme Authentication Implementation for ASP.NET Core.","archived":false,"fork":false,"pushed_at":"2024-02-12T21:17:02.000Z","size":110,"stargazers_count":72,"open_issues_count":0,"forks_count":9,"subscribers_count":2,"default_branch":"master","last_synced_at":"2024-04-28T19:34:34.697Z","etag":null,"topics":["asp","asp-net-core","asp-net-core-authentication","asp-net-core-basic-authentication","aspnet","aspnetcore","aspnetcore-authentication","aspnetcore-basic-authentication","authentication","authentication-scheme","basic","basic-authentication","basicauthentication","dotnetcore","microsoft","microsoft-aspnetcore-authentication","netstandard","netstandard20","security"],"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/mihirdilip.png","metadata":{"files":{"readme":"README.md","changelog":null,"contributing":"CONTRIBUTING.md","funding":null,"license":"LICENSE.txt","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":"2018-03-21T15:07:34.000Z","updated_at":"2024-02-29T08:00:10.000Z","dependencies_parsed_at":"2024-02-12T22:42:55.057Z","dependency_job_id":"89dacfa6-f7d2-4db4-967d-2209c31c2002","html_url":"https://github.com/mihirdilip/aspnetcore-authentication-basic","commit_stats":null,"previous_names":[],"tags_count":12,"template":false,"template_full_name":null,"repository_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/mihirdilip%2Faspnetcore-authentication-basic","tags_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/mihirdilip%2Faspnetcore-authentication-basic/tags","releases_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/mihirdilip%2Faspnetcore-authentication-basic/releases","manifests_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/mihirdilip%2Faspnetcore-authentication-basic/manifests","owner_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners/mihirdilip","download_url":"https://codeload.github.com/mihirdilip/aspnetcore-authentication-basic/tar.gz/refs/heads/master","host":{"name":"GitHub","url":"https://github.com","kind":"github","repositories_count":248045231,"owners_count":21038553,"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":["asp","asp-net-core","asp-net-core-authentication","asp-net-core-basic-authentication","aspnet","aspnetcore","aspnetcore-authentication","aspnetcore-basic-authentication","authentication","authentication-scheme","basic","basic-authentication","basicauthentication","dotnetcore","microsoft","microsoft-aspnetcore-authentication","netstandard","netstandard20","security"],"created_at":"2025-03-17T14:52:19.404Z","updated_at":"2025-04-09T13:07:13.324Z","avatar_url":"https://github.com/mihirdilip.png","language":"C#","readme":"# AspNetCore.Authentication.Basic\nEasy to use and very light weight Microsoft style Basic Scheme Authentication Implementation for ASP.NET Core.\n\n[View On GitHub](https://github.com/mihirdilip/aspnetcore-authentication-basic)\n\n\u003cbr/\u003e\n\n## .NET (Core) Frameworks Supported  \n.NET Framework 4.6.1 and/or NetStandard 2.0 onwards  \nMulti targeted: net9.0; net8.0; net7.0; net6.0; net5.0; netcoreapp3.1; netcoreapp3.0; netstandard2.0; net461\n\n\u003cbr/\u003e \n\n## Installing\nThis library is published on NuGet. So the NuGet package can be installed directly to your project if you wish to use it without making any custom changes to the code.\n\nDownload directly from below link. Please consider downloading the new package as the old one has been made obsolete.  \nNew Package link - [AspNetCore.Authentication.Basic](https://www.nuget.org/packages/AspNetCore.Authentication.Basic).  \nOld Package link - [Mihir.AspNetCore.Authentication.Basic](https://www.nuget.org/packages/Mihir.AspNetCore.Authentication.Basic).  \n\nOr by running the below command on your project.\n\n```\nPM\u003e Install-Package AspNetCore.Authentication.Basic\n```\n\n\u003cbr/\u003e \n\n## Example Usage\n\nSamples are available under [samples directory](samples).\n\nSetting it up is quite simple. You will need basic working knowledge of ASP.NET Core 2.0 or newer to get started using this library.\n\nThere are 2 different ways of using this library to do it's job. Both ways can be mixed if required.  \n1] Using the implementation of *IBasicUserValidationService*  \n2] Using *BasicOptions.Events* (OnValidateCredentials delegate) which is same approach you will find on Microsoft's authentication libraries\n\nNotes:\n- It requires Realm to be set in the options if SuppressWWWAuthenticateHeader is not set.\n- If an implementation of IBasicUserValidationService interface is used as well as BasicOptions.Events.OnValidateCredentials delegate is also set then this delegate will be used first.\n\n**Always use HTTPS (SSL Certificate) protocol in production when using basic authentication.**\n\n#### Startup.cs (ASP.NET Core 3.0 onwards)\n\n```C#\nusing AspNetCore.Authentication.Basic;\npublic class Startup\n{\n\tpublic void ConfigureServices(IServiceCollection services)\n\t{\n\t\t// It requires Realm to be set in the options if SuppressWWWAuthenticateHeader is not set.\n\t\t// If an implementation of IBasicUserValidationService interface is used as well as options.Events.OnValidateCredentials delegate is also set then this delegate will be used first.\n\t\t\n\t\tservices.AddAuthentication(BasicDefaults.AuthenticationScheme)\n\n\t\t\t// The below AddBasic without type parameter will require options.Events.OnValidateCredentials delegete to be set.\n\t\t\t//.AddBasic(options =\u003e { options.Realm = \"My App\"; });\n\n\t\t\t// The below AddBasic with type parameter will add the BasicUserValidationService to the dependency container. \n\t\t\t.AddBasic\u003cBasicUserValidationService\u003e(options =\u003e { options.Realm = \"My App\"; });\n\n\t\tservices.AddControllers();\n\n\t\t//// By default, authentication is not challenged for every request which is ASP.NET Core's default intended behaviour.\n\t\t//// So to challenge authentication for every requests please use below FallbackPolicy option.\n\t\t//services.AddAuthorization(options =\u003e\n\t\t//{\n\t\t//\toptions.FallbackPolicy = new AuthorizationPolicyBuilder().RequireAuthenticatedUser().Build();\n\t\t//});\n\t}\n\n\tpublic void Configure(IApplicationBuilder app, IHostingEnvironment env)\n\t{\n\t\tapp.UseHttpsRedirection();\n\n\t\t// The below order of pipeline chain is important!\n\t\tapp.UseRouting();\n\n\t\tapp.UseAuthentication();\n\t\tapp.UseAuthorization();\n\n\t\tapp.UseEndpoints(endpoints =\u003e\n\t\t{\n\t\t\tendpoints.MapControllers();\n\t\t});\n\t}\n}\n```\n\n#### Startup.cs (ASP.NET Core 2.0 onwards)\n\n```C#\nusing AspNetCore.Authentication.Basic;\npublic class Startup\n{\n\tpublic void ConfigureServices(IServiceCollection services)\n\t{\n\t\t// It requires Realm to be set in the options if SuppressWWWAuthenticateHeader is not set.\n\t\t// If an implementation of IBasicUserValidationService interface is used as well as options.Events.OnValidateCredentials delegate is also set then this delegate will be used first.\n\n\t\tservices.AddAuthentication(BasicDefaults.AuthenticationScheme)\n\n\t\t\t// The below AddBasic without type parameter will require options.Events.OnValidateCredentials delegete to be set.\n\t\t\t//.AddBasic(options =\u003e { options.Realm = \"My App\"; });\n\n\t\t\t// The below AddBasic with type parameter will add the BasicUserValidationService to the dependency container. \n\t\t\t.AddBasic\u003cBasicUserValidationService\u003e(options =\u003e { options.Realm = \"My App\"; });\n\n\t\tservices.AddMvc();\n\n\t\t//// By default, authentication is not challenged for every request which is ASP.NET Core's default intended behaviour.\n\t\t//// So to challenge authentication for every requests please use below option instead of above services.AddMvc().\n\t\t//services.AddMvc(options =\u003e \n\t\t//{\n\t\t//\toptions.Filters.Add(new AuthorizeFilter(new AuthorizationPolicyBuilder().RequireAuthenticatedUser().Build()));\n\t\t//});\n\t}\n\n\tpublic void Configure(IApplicationBuilder app, IHostingEnvironment env)\n\t{\n\t\tapp.UseAuthentication();\n\t\tapp.UseMvc();\n\t}\n}\n```\n\n#### BasicUserValidationService.cs\n```C#\nusing AspNetCore.Authentication.Basic;\npublic class BasicUserValidationService : IBasicUserValidationService\n{\n\tprivate readonly ILogger\u003cBasicUserValidationService\u003e _logger;\n\tprivate readonly IUserRepository _userRepository;\n\n\tpublic BasicUserValidationService(ILogger\u003cBasicUserValidationService\u003e logger, IUserRepository userRepository)\n\t{\n\t\t_logger = logger;\n\t\t_userRepository = userRepository;\n\t}\n\n\tpublic async Task\u003cbool\u003e IsValidAsync(string username, string password)\n\t{\n\t\ttry\n\t\t{\n\t\t\t// NOTE: DO NOT USE THIS IMPLEMENTATION. THIS IS FOR DEMO PURPOSE ONLY\n\t\t\t// Write your implementation here and return true or false depending on the validation..\n\t\t\tvar user = await _userRepository.GetUserByUsername(username);\n\t\t\tvar isValid = user != null \u0026\u0026 user.Password == password;\n\t\t\treturn isValid;\n\t\t}\n\t\tcatch (Exception e)\n\t\t{\n\t\t\t_logger.LogError(e, e.Message);\n\t\t\tthrow;\n\t\t}\n\t}\n}\n```\n\n\u003cbr/\u003e\n\u003cbr/\u003e\n\n## Configuration (BasicOptions)\n\n### Realm\nRequired to be set if SuppressWWWAuthenticateHeader is not set to true. It is used with WWW-Authenticate response header when challenging un-authenticated requests.  \n   \n### SuppressWWWAuthenticateHeader\nDefault value is false.  \nIf set to true, it will NOT return WWW-Authenticate response header when challenging un-authenticated requests.  \nIf set to false, it will return WWW-Authenticate response header when challenging un-authenticated requests.\n\n### IgnoreAuthenticationIfAllowAnonymous (available on ASP.NET Core 3.0 onwards)\nDefault value is false.  \nIf set to true, it checks if AllowAnonymous filter on controller action or metadata on the endpoint which, if found, it does not try to authenticate the request.\n\n### Events\nThe object provided by the application to process events raised by the basic authentication middleware.  \nThe application may implement the interface fully, or it may create an instance of BasicEvents and assign delegates only to the events it wants to process.\n- #### OnValidateCredentials\n\tA delegate assigned to this property will be invoked just before validating credentials.  \n\tYou must provide a delegate for this property for authentication to occur.  \n\tIn your delegate you should either call context.ValidationSucceeded() which will handle construction of authentication claims principal from the user details which will be assiged the context.Principal property and calls context.Success(), or construct an authentication claims principal from the user details and assign it to the context.Principal property and finally call context.Success() method.  \n\tIf only context.Principal property set without calling context.Success() method then, Success() method is automaticalled called.\n\n- #### OnAuthenticationSucceeded  \n\tA delegate assigned to this property will be invoked when the authentication succeeds. It will not be called if OnValidateCredentials delegate is assigned.  \n\tIt can be used for adding claims, headers, etc to the response.\n\n- #### OnAuthenticationFailed  \n\tA delegate assigned to this property will be invoked when any unexpected exception is thrown within the library.\n\n- #### OnHandleChallenge  \n\tA delegate assigned to this property will be invoked before a challenge is sent back to the caller when handling unauthorized response.  \n\tOnly use this if you know what you are doing and if you want to use custom implementation.  Set the delegate to deal with 401 challenge concerns, if an authentication scheme in question deals an authentication interaction as part of it's request flow. (like adding a response header, or changing the 401 result to 302 of a login page or external sign-in location.)  \n\tCall context.Handled() at the end so that any default logic for this challenge will be skipped.\n\n- #### OnHandleForbidden  \n\tA delegate assigned to this property will be invoked if Authorization fails and results in a Forbidden response.  \n\tOnly use this if you know what you are doing and if you want to use custom implementation.  \n\tSet the delegate to handle Forbid.  \n\tCall context.Handled() at the end so that any default logic will be skipped.\n\n\u003cbr/\u003e\n\u003cbr/\u003e\n\n## Additional Notes\n\n### Basic Authentication Not Challenged\nWith ASP.NET Core, all the requests are not challenged for authentication by default. So don't worry if your *BasicUserValidationService* is not hit when you don't pass the required basic authentication details with the request. It is a normal behaviour. ASP.NET Core challenges authentication only when it is specifically told to do so either by decorating controller/method with *[Authorize]* filter attribute or by some other means. \n\nHowever, if you want all the requests to challenge authentication by default, depending on what you are using, you can add the below options line to *ConfigureServices* method on *Startup* class.\n\n```C#\n// On ASP.NET Core 3.0 onwards\nservices.AddAuthorization(options =\u003e\n{\n\toptions.FallbackPolicy = new AuthorizationPolicyBuilder().RequireAuthenticatedUser().Build();\n});\n\n// OR\n\n// On ASP.NET Core 2.0 onwards\nservices.AddMvc(options =\u003e \n{\n\toptions.Filters.Add(new AuthorizeFilter(new AuthorizationPolicyBuilder().RequireAuthenticatedUser().Build()));\n});\n```\n  \nIf you are not using MVC but, using Endpoints on ASP.NET Core 3.0 or newer, you can add a chain method `.RequireAuthorization()` to the endpoint map under *Configure* method on *Startup* class as shown below.\n\n```C#\n// ASP.NET Core 3.0 onwards\napp.UseEndpoints(endpoints =\u003e\n{\n\tendpoints.MapGet(\"/\", async context =\u003e\n\t{\n\t\tawait context.Response.WriteAsync(\"Hello World!\");\n\t}).RequireAuthorization();  // NOTE THIS HERE!!!! \n});\n``` \n\n### Multiple Authentication Schemes\nASP.NET Core supports adding multiple authentication schemes which this library also supports. Just need to use the extension method which takes scheme name as parameter. The rest is all same. This can be achieved in many different ways. Below is just a quick rough example.   \n\nPlease note that scheme name parameter can be any string you want.\n\n```C#\npublic void ConfigureServices(IServiceCollection services)\n{\n\tservices.AddTransient\u003cIUserRepository, InMemoryUserRepository\u003e();\n\t\t\n\tservices.AddAuthentication(\"Scheme1\")\n\n\t\t.AddBasic\u003cBasicUserValidationService\u003e(\"Scheme1\", options =\u003e { options.Realm = \"My App\"; })\n\n\t\t.AddBasic\u003cBasicUserValidationService_2\u003e(\"Scheme2\", options =\u003e { options.Realm = \"My App\"; })\n\t\t\n\t\t.AddBasic(\"Scheme3\", options =\u003e \n\t\t{ \n\t\t\toptions.Realm = \"My App\"; \n\t\t\toptions.Events = new BasicEvents\n\t\t\t{\n\t\t\t\tOnValidateCredentials = async (context) =\u003e\n\t\t\t\t{\n\t\t\t\t\tvar userRepository = context.HttpContext.RequestServices.GetRequiredService\u003cIUserRepository\u003e();\n\t\t\t\t\tvar user = await userRepository.GetUserByUsername(context.Username);\n\t\t\t\t\tvar isValid = user != null \u0026\u0026 user.Password == context.Password;\n\t\t\t\t\tif (isValid)\n\t\t\t\t\t{\n\t\t\t\t\t\tcontext.Response.Headers.Add(\"ValidationCustomHeader\", \"From OnValidateCredentials\");\n\t\t\t\t\t\tvar claims = new[]\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\tnew Claim(\"CustomClaimType\", \"Custom Claim Value - from OnValidateCredentials\")\n\t\t\t\t\t\t};\n\t\t\t\t\t\tcontext.ValidationSucceeded(claims);    // claims are optional\n\t\t\t\t\t}\n\t\t\t\t\telse\n\t\t\t\t\t{\n\t\t\t\t\t\tcontext.ValidationFailed();\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t});\n\n\tservices.AddControllers();\n\n\tservices.AddAuthorization(options =\u003e\n\t{\n\t\toptions.FallbackPolicy = new AuthorizationPolicyBuilder(\"Scheme1\", \"Scheme2\", \"Scheme3\").RequireAuthenticatedUser().Build();\n\t});\n}\n```\n\n\u003cbr/\u003e\n\u003cbr/\u003e\n\n## Release Notes\n| Version | \u0026nbsp;\u0026nbsp;\u0026nbsp;\u0026nbsp;\u0026nbsp;\u0026nbsp;\u0026nbsp;\u0026nbsp;\u0026nbsp; Notes |\n|---------|-------|\n|9.0.0    | \u003cul\u003e\u003cli\u003enet9.0 support added\u003c/li\u003e\u003cli\u003eSample project for net9.0 added\u003c/li\u003e\u003cli\u003eReadme updated\u003c/li\u003e\u003cli\u003eNullable reference types enabled\u003c/li\u003e\u003cli\u003eLanguage version set to latest\u003c/li\u003e\u003cli\u003eImplicit usings enabled\u003c/li\u003e\u003cli\u003eAOT support added\u003c/li\u003e\u003c/ul\u003e |\n|8.0.0    | \u003cul\u003e\u003cli\u003enet8.0 support added\u003c/li\u003e\u003cli\u003eSample project for net8.0 added\u003c/li\u003e\u003cli\u003eBasicSamplesClient.http file added for testing sample projects\u003c/li\u003e\u003cli\u003eReadme updated\u003c/li\u003e\u003c/ul\u003e |\n|7.0.0    | \u003cul\u003e\u003cli\u003enet7.0 support added\u003c/li\u003e\u003cli\u003eInformation log on handler is changed to Debug log when Authorization header is not found on the request\u003c/li\u003e\u003cli\u003eAdded package validations\u003c/li\u003e\u003cli\u003eSample project for net7.0 added\u003c/li\u003e\u003cli\u003eReadme updated\u003c/li\u003e\u003cli\u003eReadme added to package\u003c/li\u003e\u003c/ul\u003e |\n|6.0.1    | \u003cul\u003e\u003cli\u003enet6.0 support added\u003c/li\u003e\u003cli\u003eInformation log on handler is changed to Debug log when IgnoreAuthenticationIfAllowAnonymous is enabled [#9](https://github.com/mihirdilip/aspnetcore-authentication-basic/issues/9)\u003c/li\u003e\u003cli\u003eSample project added\u003c/li\u003e\u003cli\u003eReadme updated\u003c/li\u003e\u003cli\u003eCopyright year updated on License\u003c/li\u003e\u003c/ul\u003e |\n|5.1.0    | \u003cul\u003e\u003cli\u003eVisibility of the handler changed to public\u003c/li\u003e\u003cli\u003eTests added\u003c/li\u003e\u003cli\u003eReadme updated\u003c/li\u003e\u003cli\u003eCopyright year updated on License\u003c/li\u003e\u003c/ul\u003e |\n|5.0.0    | \u003cul\u003e\u003cli\u003eNet 5.0 target framework added\u003c/li\u003e\u003cli\u003eIgnoreAuthenticationIfAllowAnonymous added to the BasicOptions from netcoreapp3.0 onwards\u003c/li\u003e\u003c/ul\u003e |\n|3.1.1    | \u003cul\u003e\u003cli\u003eFixed issue with resolving of IBasicUserValidationService implementation when using multiple schemes\u003c/li\u003e\u003c/ul\u003e |\n|3.1.0    | \u003cul\u003e\u003cli\u003eMultitarget framework support added\u003c/li\u003e\u003cli\u003eStrong Name Key support added\u003c/li\u003e\u003cli\u003eSource Link support added\u003c/li\u003e\u003cli\u003eSuppressWWWAuthenticateHeader added to configure options\u003c/li\u003e\u003cli\u003eEvents added to configure options\u003c/li\u003e\u003c/ul\u003e |\n|2.2.0    | \u003cul\u003e\u003cli\u003eBasic Authentication Implementation for ASP.NET Core\u003c/li\u003e\u003c/ul\u003e |\n\n\u003cbr/\u003e\n\u003cbr/\u003e\n\n## References\n- [RFC 7617: Technical spec for HTTP Basic](https://tools.ietf.org/html/rfc7617)\n- [ASP.NET Core Security documentation](https://docs.microsoft.com/en-us/aspnet/core/security)\n- [aspnet/Security](https://github.com/dotnet/aspnetcore/tree/master/src/Security)\n\n## License\n[MIT License](https://github.com/mihirdilip/aspnetcore-authentication-basic/blob/master/LICENSE.txt)","funding_links":[],"categories":[],"sub_categories":[],"project_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fmihirdilip%2Faspnetcore-authentication-basic","html_url":"https://awesome.ecosyste.ms/projects/github.com%2Fmihirdilip%2Faspnetcore-authentication-basic","lists_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fmihirdilip%2Faspnetcore-authentication-basic/lists"}