Hi,
I have an ASP.Net Web API 2 with BasicAuthenticationAttribute that is working as expected. In my application, there are different controllers and I want to add bearer token-based authentication to one of my controllers. I added those NuGet packages:
There is no problem with the web API config.
Here is Owin startup
In the configuration of Owin startup, the program flow goes back to the web API config file.
And finally, it gets a null exception for basic authentication.
How can I solve this and use both basic authentication attribute and token-based authentication in my web API?
Best Regards.
I have an ASP.Net Web API 2 with BasicAuthenticationAttribute that is working as expected. In my application, there are different controllers and I want to add bearer token-based authentication to one of my controllers. I added those NuGet packages:
NuGet:
Microsoft.AspNet.WebApi.Owin
Microsoft.Owin.Host.SystemWeb
Microsoft.Owin.Security.OAuth
There is no problem with the web API config.
WebApiConfig:
public static class WebApiConfig
{
public static void Register(HttpConfiguration config)
{
config.Formatters.JsonFormatter.SerializerSettings.ReferenceLoopHandling = ReferenceLoopHandling.Ignore;
config.Formatters.JsonFormatter.SerializerSettings.DateTimeZoneHandling =
DateTimeZoneHandling.Local;
config.MapHttpAttributeRoutes();
config.Routes.MapHttpRoute(
"DefaultApi",
"api/{controller}/{id}",
new {id = RouteParameter.Optional}
);
config.MessageHandlers.Add(new RequestResponseHandler());
config.Filters.Add(new CustomExceptionFilter());
var resolver = config.DependencyResolver;
var basicAuth = resolver.GetService(typeof(BasicAuthenticationAttribute)) as BasicAuthenticationAttribute;
config.Filters.Add(basicAuth);
}
}
Here is Owin startup
Owin Startup:
public class Startup
{
public void Configuration(IAppBuilder app)
{
var configuration = new HttpConfiguration();
Configure(app);
WebApiConfig.Register(configuration);
app.UseWebApi(configuration);
}
private static void Configure(IAppBuilder app)
{
var options = new OAuthAuthorizationServerOptions()
{
TokenEndpointPath = new Microsoft.Owin.PathString("/token"),
AccessTokenExpireTimeSpan = TimeSpan.FromHours(1),
AllowInsecureHttp = true,
Provider = new AuthorizationServerProvider()
};
app.UseOAuthAuthorizationServer(options);
app.UseOAuthBearerAuthentication(new OAuthBearerAuthenticationOptions());
}
}
In the configuration of Owin startup, the program flow goes back to the web API config file.
C#:
WebApiConfig.Register(configuration);
And finally, it gets a null exception for basic authentication.
C#:
config.Filters.Add(basicAuth);
How can I solve this and use both basic authentication attribute and token-based authentication in my web API?
Best Regards.