aspnetcore authentication basic

2025-12-07 0 356

AspNetCore.Authentication.Basic

Easy to use and very light weight Microsoft style Basic Scheme Authentication Implementation for ASP.NET Core.

View On GitHub

.NET (Core) Frameworks Supported

.NET Framework 4.6.1 and/or NetStandard 2.0 onwards
Multi targeted: net9.0; net8.0; net7.0; net6.0; net5.0; netcoreapp3.1; netcoreapp3.0; netstandard2.0; net461

Installing

This 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.

Download directly from below link. Please consider downloading the new package as the old one has been made obsolete.
New Package link – AspNetCore.Authentication.Basic.
Old Package link – Mihir.AspNetCore.Authentication.Basic.

Or by running the below command on your project.

PM> Install-Package AspNetCore.Authentication.Basic

Example Usage

Samples are available under samples directory.

Setting 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.

There are 2 different ways of using this library to do it\’s job. Both ways can be mixed if required.
1] Using the implementation of IBasicUserValidationService
2] Using BasicOptions.Events (OnValidateCredentials delegate) which is same approach you will find on Microsoft\’s authentication libraries

Notes:

  • It requires Realm to be set in the options if SuppressWWWAuthenticateHeader is not set.
  • 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.

Always use HTTPS (SSL Certificate) protocol in production when using basic authentication.

Startup.cs (ASP.NET Core 3.0 onwards)

using AspNetCore.Authentication.Basic;
public class Startup
{
	public void ConfigureServices(IServiceCollection services)
	{
		// It requires Realm to be set in the options if SuppressWWWAuthenticateHeader is not set.
		// 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.
		
		services.AddAuthentication(BasicDefaults.AuthenticationScheme)

			// The below AddBasic without type parameter will require options.Events.OnValidateCredentials delegete to be set.
			//.AddBasic(options => { options.Realm = \"My App\"; });

			// The below AddBasic with type parameter will add the BasicUserValidationService to the dependency container. 
			.AddBasic<BasicUserValidationService>(options => { options.Realm = \"My App\"; });

		services.AddControllers();

		//// By default, authentication is not challenged for every request which is ASP.NET Core\'s default intended behaviour.
		//// So to challenge authentication for every requests please use below FallbackPolicy option.
		//services.AddAuthorization(options =>
		//{
		//	options.FallbackPolicy = new AuthorizationPolicyBuilder().RequireAuthenticatedUser().Build();
		//});
	}

	public void Configure(IApplicationBuilder app, IHostingEnvironment env)
	{
		app.UseHttpsRedirection();

		// The below order of pipeline chain is important!
		app.UseRouting();

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

		app.UseEndpoints(endpoints =>
		{
			endpoints.MapControllers();
		});
	}
}

Startup.cs (ASP.NET Core 2.0 onwards)

using AspNetCore.Authentication.Basic;
public class Startup
{
	public void ConfigureServices(IServiceCollection services)
	{
		// It requires Realm to be set in the options if SuppressWWWAuthenticateHeader is not set.
		// 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.

		services.AddAuthentication(BasicDefaults.AuthenticationScheme)

			// The below AddBasic without type parameter will require options.Events.OnValidateCredentials delegete to be set.
			//.AddBasic(options => { options.Realm = \"My App\"; });

			// The below AddBasic with type parameter will add the BasicUserValidationService to the dependency container. 
			.AddBasic<BasicUserValidationService>(options => { options.Realm = \"My App\"; });

		services.AddMvc();

		//// By default, authentication is not challenged for every request which is ASP.NET Core\'s default intended behaviour.
		//// So to challenge authentication for every requests please use below option instead of above services.AddMvc().
		//services.AddMvc(options => 
		//{
		//	options.Filters.Add(new AuthorizeFilter(new AuthorizationPolicyBuilder().RequireAuthenticatedUser().Build()));
		//});
	}

	public void Configure(IApplicationBuilder app, IHostingEnvironment env)
	{
		app.UseAuthentication();
		app.UseMvc();
	}
}

BasicUserValidationService.cs

using AspNetCore.Authentication.Basic;
public class BasicUserValidationService : IBasicUserValidationService
{
	private readonly ILogger<BasicUserValidationService> _logger;
	private readonly IUserRepository _userRepository;

	public BasicUserValidationService(ILogger<BasicUserValidationService> logger, IUserRepository userRepository)
	{
		_logger = logger;
		_userRepository = userRepository;
	}

	public async Task<bool> IsValidAsync(string username, string password)
	{
		try
		{
			// NOTE: DO NOT USE THIS IMPLEMENTATION. THIS IS FOR DEMO PURPOSE ONLY
			// Write your implementation here and return true or false depending on the validation..
			var user = await _userRepository.GetUserByUsername(username);
			var isValid = user != null && user.Password == password;
			return isValid;
		}
		catch (Exception e)
		{
			_logger.LogError(e, e.Message);
			throw;
		}
	}
}

Configuration (BasicOptions)

Realm

Required to be set if SuppressWWWAuthenticateHeader is not set to true. It is used with WWW-Authenticate response header when challenging un-authenticated requests.

SuppressWWWAuthenticateHeader

Default value is false.
If set to true, it will NOT return WWW-Authenticate response header when challenging un-authenticated requests.
If set to false, it will return WWW-Authenticate response header when challenging un-authenticated requests.

IgnoreAuthenticationIfAllowAnonymous (available on ASP.NET Core 3.0 onwards)

Default value is false.
If 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.

Events

The object provided by the application to process events raised by the basic authentication middleware.
The 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.

  • OnValidateCredentials

    A delegate assigned to this property will be invoked just before validating credentials.
    You must provide a delegate for this property for authentication to occur.
    In 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.
    If only context.Principal property set without calling context.Success() method then, Success() method is automaticalled called.

  • OnAuthenticationSucceeded

    A delegate assigned to this property will be invoked when the authentication succeeds. It will not be called if OnValidateCredentials delegate is assigned.
    It can be used for adding claims, headers, etc to the response.

  • OnAuthenticationFailed

    A delegate assigned to this property will be invoked when any unexpected exception is thrown within the library.

  • OnHandleChallenge

    A delegate assigned to this property will be invoked before a challenge is sent back to the caller when handling unauthorized response.
    Only 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.)
    Call context.Handled() at the end so that any default logic for this challenge will be skipped.

  • OnHandleForbidden

    A delegate assigned to this property will be invoked if Authorization fails and results in a Forbidden response.
    Only use this if you know what you are doing and if you want to use custom implementation.
    Set the delegate to handle Forbid.
    Call context.Handled() at the end so that any default logic will be skipped.

Additional Notes

Basic Authentication Not Challenged

With 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.

However, 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.

// On ASP.NET Core 3.0 onwards
services.AddAuthorization(options =>
{
	options.FallbackPolicy = new AuthorizationPolicyBuilder().RequireAuthenticatedUser().Build();
});

// OR

// On ASP.NET Core 2.0 onwards
services.AddMvc(options => 
{
	options.Filters.Add(new AuthorizeFilter(new AuthorizationPolicyBuilder().RequireAuthenticatedUser().Build()));
});

If 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.

// ASP.NET Core 3.0 onwards
app.UseEndpoints(endpoints =>
{
	endpoints.MapGet(\"/\", async context =>
	{
		await context.Response.WriteAsync(\"Hello World!\");
	}).RequireAuthorization();  // NOTE THIS HERE!!!! 
});

Multiple Authentication Schemes

ASP.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.

Please note that scheme name parameter can be any string you want.

public void ConfigureServices(IServiceCollection services)
{
	services.AddTransient<IUserRepository, InMemoryUserRepository>();
		
	services.AddAuthentication(\"Scheme1\")

		.AddBasic<BasicUserValidationService>(\"Scheme1\", options => { options.Realm = \"My App\"; })

		.AddBasic<BasicUserValidationService_2>(\"Scheme2\", options => { options.Realm = \"My App\"; })
		
		.AddBasic(\"Scheme3\", options => 
		{ 
			options.Realm = \"My App\"; 
			options.Events = new BasicEvents
			{
				OnValidateCredentials = async (context) =>
				{
					var userRepository = context.HttpContext.RequestServices.GetRequiredService<IUserRepository>();
					var user = await userRepository.GetUserByUsername(context.Username);
					var isValid = user != null && user.Password == context.Password;
					if (isValid)
					{
						context.Response.Headers.Add(\"ValidationCustomHeader\", \"From OnValidateCredentials\");
						var claims = new[]
						{
							new Claim(\"CustomClaimType\", \"Custom Claim Value - from OnValidateCredentials\")
						};
						context.ValidationSucceeded(claims);    // claims are optional
					}
					else
					{
						context.ValidationFailed();
					}
				}
			}
		});

	services.AddControllers();

	services.AddAuthorization(options =>
	{
		options.FallbackPolicy = new AuthorizationPolicyBuilder(\"Scheme1\", \"Scheme2\", \"Scheme3\").RequireAuthenticatedUser().Build();
	});
}

Release Notes

Version           Notes
9.0.0
  • net9.0 support added
  • Sample project for net9.0 added
  • Readme updated
  • Nullable reference types enabled
  • Language version set to latest
  • Implicit usings enabled
  • AOT support added
8.0.0
  • net8.0 support added
  • Sample project for net8.0 added
  • BasicSamplesClient.http file added for testing sample projects
  • Readme updated
7.0.0
  • net7.0 support added
  • Information log on handler is changed to Debug log when Authorization header is not found on the request
  • Added package validations
  • Sample project for net7.0 added
  • Readme updated
  • Readme added to package
6.0.1
  • net6.0 support added
  • Information log on handler is changed to Debug log when IgnoreAuthenticationIfAllowAnonymous is enabled #9
  • Sample project added
  • Readme updated
  • Copyright year updated on License
5.1.0
  • Visibility of the handler changed to public
  • Tests added
  • Readme updated
  • Copyright year updated on License
5.0.0
  • Net 5.0 target framework added
  • IgnoreAuthenticationIfAllowAnonymous added to the BasicOptions from netcoreapp3.0 onwards
3.1.1
  • Fixed issue with resolving of IBasicUserValidationService implementation when using multiple schemes
3.1.0
  • Multitarget framework support added
  • Strong Name Key support added
  • Source Link support added
  • SuppressWWWAuthenticateHeader added to configure options
  • Events added to configure options
2.2.0
  • Basic Authentication Implementation for ASP.NET Core

References

  • RFC 7617: Technical spec for HTTP Basic
  • ASP.NET Core Security documentation
  • aspnet/Security

License

MIT License

下载源码

通过命令行克隆项目:

git clone https://github.com/mihirdilip/aspnetcore-authentication-basic.git

收藏 (0) 打赏

感谢您的支持,我会继续努力的!

打开微信/支付宝扫一扫,即可进行扫码打赏哦,分享从这里开始,精彩与您同在
点赞 (0)

申明:本文由第三方发布,内容仅代表作者观点,与本网站无关。对本文以及其中全部或者部分内容的真实性、完整性、及时性本站不作任何保证或承诺,请读者仅作参考,并请自行核实相关内容。本网发布或转载文章出于传递更多信息之目的,并不意味着赞同其观点或证实其描述,也不代表本网对其真实性负责。

左子网 开发教程 aspnetcore authentication basic https://www.zuozi.net/31237.html

overscript
上一篇: overscript
Netly
下一篇: Netly
常见问题
  • 1、自动:拍下后,点击(下载)链接即可下载;2、手动:拍下后,联系卖家发放即可或者联系官方找开发者发货。
查看详情
  • 1、源码默认交易周期:手动发货商品为1-3天,并且用户付款金额将会进入平台担保直到交易完成或者3-7天即可发放,如遇纠纷无限期延长收款金额直至纠纷解决或者退款!;
查看详情
  • 1、描述:源码描述(含标题)与实际源码不一致的(例:货不对板); 2、演示:有演示站时,与实际源码小于95%一致的(但描述中有”不保证完全一样、有变化的可能性”类似显著声明的除外); 3、发货:不发货可无理由退款; 4、安装:免费提供安装服务的源码但卖家不履行的; 5、收费:价格虚标,额外收取其他费用的(但描述中有显著声明或双方交易前有商定的除外); 6、其他:如质量方面的硬性常规问题BUG等。 注:经核实符合上述任一,均支持退款,但卖家予以积极解决问题则除外。
查看详情
  • 1、左子会对双方交易的过程及交易商品的快照进行永久存档,以确保交易的真实、有效、安全! 2、左子无法对如“永久包更新”、“永久技术支持”等类似交易之后的商家承诺做担保,请买家自行鉴别; 3、在源码同时有网站演示与图片演示,且站演与图演不一致时,默认按图演作为纠纷评判依据(特别声明或有商定除外); 4、在没有”无任何正当退款依据”的前提下,商品写有”一旦售出,概不支持退款”等类似的声明,视为无效声明; 5、在未拍下前,双方在QQ上所商定的交易内容,亦可成为纠纷评判依据(商定与描述冲突时,商定为准); 6、因聊天记录可作为纠纷评判依据,故双方联系时,只与对方在左子上所留的QQ、手机号沟通,以防对方不承认自我承诺。 7、虽然交易产生纠纷的几率很小,但一定要保留如聊天记录、手机短信等这样的重要信息,以防产生纠纷时便于左子介入快速处理。
查看详情

相关文章

猜你喜欢
发表评论
暂无评论
官方客服团队

为您解决烦忧 - 24小时在线 专业服务