C# WebAPI Custom Authentication

Date: 2021-02-22
public void ConfigureServices(IServiceCollection services)
{
	services.AddAuthentication(CustomAuthHandler.SchemeName)
		.AddCustomAuth(options => { });
}

public class CustomAuthHandler : AuthenticationHandler<CustomAuthOptions>
{
	public static readonly string SchemeName = "custom";
	public CustomAuthHandler(IOptionsMonitor<CustomAuthOptions> options, ILoggerFactory logger, UrlEncoder encoder, ISystemClock clock) : base(options, logger, encoder, clock)
	{

	}

	protected override Task<AuthenticateResult> HandleAuthenticateAsync()
	{
		//return AuthenticateResult.NoResult();
		//return AuthenticateResult.Fail(new System.Exception("Expected bearer token"));
		if (Context.User.Identity.IsAuthenticated)
			return Task.FromResult(AuthenticateResult.NoResult());

		try
		{
			var claims = new List<Claim> {
				new Claim(ClaimTypes.NameIdentifier, "test@test.lan"),
				new Claim(ClaimTypes.Name, "test@test.lan"),
			};
			var claimsIdentity = new ClaimsIdentity(claims, CustomAuthHandler.SchemeName, "userId", "roleId");
			var principal = new ClaimsPrincipal(claimsIdentity);
			var properties = new AuthenticationProperties();
			return Task.FromResult(AuthenticateResult.Success(new AuthenticationTicket(principal, properties, CustomAuthHandler.SchemeName)));
		}
		catch (Exception ex)
		{
			return Task.FromResult(AuthenticateResult.Fail(ex.Message));
		}
	}
}
public class CustomAuthOptions : AuthenticationSchemeOptions
{

}

public static class CustomAuthExtensions
{
	public static AuthenticationBuilder AddCustomAuth(this AuthenticationBuilder builder, Action<CustomAuthOptions> configureOptions)
	{
		return builder.AddScheme<CustomAuthOptions, CustomAuthHandler>(CustomAuthHandler.SchemeName, CustomAuthHandler.SchemeName, configureOptions);
	}
}
46580cookie-checkC# WebAPI Custom Authentication