I am using Basic Authentication
and I have created a Middleware
for this. When I use the Authorize
attribute and try to make an API call through Postman, i get 401 Unauthorize
even as I am added the authorization details in Postman.
I am not sure if it is the way i am calling the controller action via postman or whether I am missing a header option in postman.
ConfigureServices
services
.AddAuthentication(BasicAuthenticationDefaults.AuthenticationScheme)
.AddBasicAuthentication(GetBasicAuthenticationOptions(users));
Configure
public void Configure(IApplicationBuilder app, IHostingEnvironment env)
{
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
}
app.UseMvc();
app.UseCors("SiteCorsPolicy");
app.UseAuthentication();
}
Basic Authentication Implementation
private Action<BasicAuthenticationOptions> GetBasicAuthenticationOptions(IList<UserConfiguration> users)
{
return options =>
{
options.Realm = "Public API";
options.Events = new BasicAuthenticationEvents
{
OnValidatePrincipal = context =>
{
var authenticatedUser = users.FirstOrDefault(u =>
u.Username == context.UserName && u.Password == context.Password);
if (authenticatedUser != null)
{
var claims = new List<Claim>
{
new Claim(ClaimTypes.Name,
context.UserName,
context.Options.ClaimsIssuer)
};
var principal = new ClaimsPrincipal(new ClaimsIdentity(claims,
BasicAuthenticationDefaults.AuthenticationScheme));
context.Principal = principal;
return Task.CompletedTask;
}
return Task.FromResult(AuthenticateResult.Fail("Authentication failed."));
}
};
};
}
Controller Action with Authorize
[Authorize]
[HttpPost]
[Route("test")]
public IActionResult Test()
{
return Json("yes");
}
Postman request
The username and passwords are in the appsettings.json file