In ASP.NET Core-6 Web API project, I am implementing Basic Authentication. I have this code:
Model:
public class User
{
public int Id { get; set; }
public string Username { get; set; }
public string Password { get; set; }
}
Service:
public interface IUserService
{
public bool isUser(string username, string password);
}
public class UserService : IUserService
{
private readonly ApplicationDbContext _dbContext;
public UserService(
ApplicationDbContext dbContext,
)
{
_dbContext = dbContext;
}
public bool isUser(string username, string password)
{
var userFind = _dbContext.User.Where(u => u.Username == username && u.Password == password);
if (userFind.Any()) return true;
else return false;
}
}
Then I have this Basic Auth Handler code in the helpers.
BasicAuthHandler:
public class BasicAuthHandler : AuthenticationHandler<AuthenticationSchemeOptions>
{
private readonly IUserService _repository;
public BasicAuthHandler(IOptionsMonitor<AuthenticationSchemeOptions> options,
ILoggerFactory loggerFactory,
UrlEncoder urlEncoder,
ISystemClock systemClockm,
IUserService repository)
: base(options, loggerFactory, urlEncoder, systemClockm)
{
_repository = repository;
}
protected override async Task<AuthenticateResult> HandleAuthenticateAsync()
{
if (!Request.Headers.ContainsKey("Authorization"))
return AuthenticateResult.Fail("No contains header");
bool result = false;
try
{
var AuthHeader = AuthenticationHeaderValue.Parse(Request.Headers["Authorization"]);
var credentialBytes = Convert.FromBase64String(AuthHeader.Parameter);
var credentials = Encoding.UTF8.GetString(credentialBytes).Split(new[] { ':' }, 2);
//get parameters in array format
var username = credentials[0];
var password = credentials[1];
result = _repository.isUser(username, password);
}
catch(Exception)
{
return AuthenticateResult.Fail("Some ERROR");
}
if (!result)
return AuthenticateResult.Fail("Error User Name or Password ");
var claims = new Claim[]
{
new Claim(ClaimTypes.NameIdentifier, "id"),
new Claim(ClaimTypes.Name, "user")
};
var identity = new ClaimsIdentity(claims, Scheme.Name);
var principal = new ClaimsPrincipal(identity);
var ticket = new AuthenticationTicket(principal, Scheme.Name);
return AuthenticateResult.Success(ticket);
}
}
Program.cs:
builder.Services.AddScoped<IUserService, UserService>();
builder.Services.AddAuthentication("BasicAuthentication")
.AddScheme<AuthenticationSchemeOptions, BasicAuthHandler>("BasicAuthentication", null);
When I run the application, the page was blank, and I got this error in the log file:
BasicAuthentication was not authenticated. Failure message: No contains header
Which indicates that it stops here:
if (!Request.Headers.ContainsKey("Authorization"))
return AuthenticateResult.Fail("No contains header");
bool result = false;
How do I resolve it?
Thanks


Response.Headers.Add("WWW-Authenticate", "Basic");above theif (!Request.Headers.ContainsKey("Authorization"))line so that the browser's native login dialog will show for the site? Otherwise it sounds like you're not allowing anonymous access to the login page (if that's what you have).WWW-Authenticatecontents. IfWWW-AuthenticateisBasicthen the browser will ask the user for username and password. So you must make sure that you always respond with 401 UNAUTHORIZED and theWWW-Authenticateheader to obtain the desired result.