I am new to ASP.NET and OAuth and I have an ASP.NET project that uses OAuth 2.0, but every time I send a request to the API in Postman, I get back a message
Authorization has been denied for this request
even with the bearer token attached in the header. The token is generated in a separate project.
This is my Startup.cs:
using Microsoft.Owin;
using Microsoft.Owin.Security.OAuth;
using Owin;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Http;
[assembly: OwinStartup(typeof(IMOTBaseWebAPI.Startup))]
//Added by Danish 25/3/2024
namespace IMOTBaseWebAPI
{
public class Startup
{
public static OAuthBearerAuthenticationOptions OAuthBearerOptions { get; private set; }
public void Configuration(IAppBuilder app)
{
// For more information on how to configure your application, visit http://go.microsoft.com/fwlink/?LinkID=316888
ConfigurationOAuth(app);
HttpConfiguration config = new HttpConfiguration();
WebApiConfig.Register(config); //Already called in Global.asax Application_Start
app.UseCors(Microsoft.Owin.Cors.CorsOptions.AllowAll);
app.UseWebApi(config);
}
private void ConfigurationOAuth(IAppBuilder app)
{
OAuthBearerOptions = new OAuthBearerAuthenticationOptions();
//Token Consumption
app.UseOAuthBearerAuthentication(OAuthBearerOptions);
}
}
}
This is my global.asax.cs:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Http;
using System.Web.Mvc;
using System.Web.Routing;
namespace IMOTBaseWebAPI
{
public class WebApiApplication : System.Web.HttpApplication
{
protected void Application_Start()
{
AreaRegistration.RegisterAllAreas();
GlobalConfiguration.Configure(WebApiConfig.Register);
}
protected void Application_BeginRequest(object sender, EventArgs e)
{
var application = sender as HttpApplication;
if (application != null && application.Context != null)
{
application.Context.Response.Headers.Set("Server", "");
}
}
protected void Application_PreSendRequestHeaders ()
{
Response.Headers.Remove("Server");
Response.Headers.Remove("X-AspNet-Version");
Response.Headers.Remove("X-AspNetMvc-Version");
}
}
}
Is there anything I'm doing wrong? Is the Startup.cs is executed automatically or do I need to call it from somewhere?