在调用 ASP.NET 中的 OAuth 身份验证 Web api 点时收到 401 时如何调试原因

How can I debug the cause when I get 401 when calling an OAuth authenticated web api point in ASP.NET

我在(运行 on .NET 4.8 - not .NET Core)中有一个 ASP.NET Web API 项目。我通过添加设置 'Bearer token' 身份验证:

public static class WebApiConfig
{
    public static void Register(HttpConfiguration config)
    {
        // Web API configuration and services
        config.SuppressDefaultHostAuthentication();
        config.Filters.Add(new HostAuthenticationFilter(OAuthDefaults.AuthenticationType))
     }
 }

并且在 Startup.cs 中:

public class Startup1
{
    public void Configuration(IAppBuilder app)
    {
        // For more information on how to configure your application, visit https://go.microsoft.com/fwlink/?LinkID=316888

        app.UseJwtBearerAuthentication(
            new JwtBearerAuthenticationOptions
                {
                    AuthenticationMode = AuthenticationMode.Active,
                    TokenValidationParameters = new TokenValidationParameters()
                                                {
                                                    ValidateIssuer = true,
                                                    ValidIssuer = "https://www.example.com", //some string, normally web url,  
                                                }
                });
    }
}

并且在我的控制器方法中,我在我的控制器 API 中添加了 [Authorize]

但是当我在浏览器中调用端点时,我检查它在 http header 中是否有不记名令牌。 http响应的body是

"Message":"Authorization has been denied for this request."

如何调试我的问题?因为我在日志中没有看到任何异常或任何消息。

能否在代码中添加这些参数并尝试:

app.UseJwtBearerAuthentication(new JwtBearerAuthenticationOptions
        {
            AuthenticationMode = AuthenticationMode.Active,
            AllowedAudiences = new[] { "Any" },
            IssuerSecurityKeyProviders = new IIssuerSecurityKeyProvider[] {
                new SymmetricKeyIssuerSecurityKeyProvider(issuer, secret)
            }
        });


var issuer = ConfigurationManager.AppSettings["issuer"];
var secret = TextEncodings.Base64Url.Decode(ConfigurationManager.AppSettings["secret"]);

在应用程序配置文件中添加这些参数:

<appSettings>
  <add key="issuer" value="http://localhost:xxx/"/>
  <add key="secret" value="YourToken"/>
</appSettings>