i have a legacy web API written in MVC 4 web API,it has basic authentication, when i test it,it works on localhost using POSTMAN, when i publish on iis i get 401 - Unauthorized: Access is denied due to invalid credentials.i have enabled the basic authentication for this API on iis server but still I get the same error,should i change something on iis or in my code?
Web Api Config:
config.Filters.Add(new BasicAuthenticationAttribute());
// config.Filters.Add(new AuthorizeAttribute());
config.Routes.MapHttpRoute(
name: "DefaultApi",
routeTemplate: "api/{controller}/{id}",
defaults: new { id = RouteParameter.Optional }
);
// Uncomment the following line of code to enable query support for actions with an IQueryable or IQueryable<T> return type.
// To avoid processing unexpected or malicious queries, use the validation settings on QueryableAttribute to validate incoming queries.
// For more information, visit http://go.microsoft.com/fwlink/?LinkId=279712.
//config.EnableQuerySupport();
// To disable tracing in your application, please comment out or remove the following line of code
// For more information, refer to: http://www.asp.net/web-api
config.EnableSystemDiagnosticsTracing()
Authentication class:
public class BasicAuthenticationAttribute: AuthorizationFilterAttribute
{
public override void OnAuthorization(HttpActionContext actionContext)
{
var authHeader = actionContext.Request.Headers.Authorization;
if (authHeader != null)
{
var authenticationToken = actionContext.Request.Headers.Authorization.Parameter;
var decodedAuthenticationToken = Encoding.UTF8.GetString(Convert.FromBase64String(authenticationToken));
var usernamePasswordArray = decodedAuthenticationToken.Split(':');
var userName = usernamePasswordArray[0];
var password = usernamePasswordArray[1];
// Replace this with your own system of security / means of validating credentials
var isValid = userName == "rene" && password == "2019";
if (isValid)
{
var principal = new GenericPrincipal(new GenericIdentity(userName), null);
Thread.CurrentPrincipal = principal;
actionContext.Response =
actionContext.Request.CreateResponse(HttpStatusCode.OK,
"User " + userName + " successfully authenticated");
base.OnAuthorization(actionContext);
}
else
{
HandleUnathorized(actionContext);
}
}