如何在 web api Authentication Failed 场景中获取详细错误而不是“消息”:“此请求的授权已被拒绝。”?
Posted
技术标签:
【中文标题】如何在 web api Authentication Failed 场景中获取详细错误而不是“消息”:“此请求的授权已被拒绝。”?【英文标题】:How to get the detailed error in web api Authentication Failed scenario instead of "Message": "Authorization has been denied for this request."? 【发布时间】:2020-04-14 16:04:35 【问题描述】:我从 VS 模板创建了一个 Web api,其 Values Controller 装饰有 [Authorize]。我添加了 Owin Startup 如下:
[assembly: OwinStartup(typeof(WebAPIDotNet.Startup))]
namespace WebAPIDotNet
public class Startup
private static string clientId = "xxxxxxxxx"; // my actual client id from azure ad.
public void Configuration(IAppBuilder app)
app.UseOAuthBearerAuthentication(new OAuthBearerAuthenticationOptions
AccessTokenFormat = new JwtFormat(
new TokenValidationParameters
// Check if the audience is intended to be this application
ValidAudiences = new[] clientId, $"api://clientId" ,
// Change below to 'true' if you want this Web API to accept tokens issued to one Azure AD tenant only (single-tenant)
// Note that this is a simplification for the quickstart here. You should validate the issuer. For details,
// see https://github.com/Azure-Samples/active-directory-dotnet-native-aspnetcore
ValidateIssuer = false,
//new OpenIdConnectSecurityTokenProvider("https://login.microsoftonline.com/common/v2.0/.well-known/openid-configuration")
),
AuthenticationMode = Microsoft.Owin.Security.AuthenticationMode.Active,
// Below Provider is just so that I can capture detailed errors while debugging, but no success
Provider = new OAuthBearerAuthenticationProvider
OnRequestToken = Onrequesttoken,
OnApplyChallenge = applyuingChallenge,
OnValidateIdentity = validatingidentiity
,
);
private Task validatingidentiity(OAuthValidateIdentityContext arg)
return Task.FromResult(0);
private Task applyuingChallenge(OAuthChallengeContext arg)
return Task.FromResult(0);
private Task Onrequesttoken(OAuthRequestTokenContext arg)
return Task.FromResult(0);
我已经有一个访问令牌,并且我已经验证它具有正确的受众,等等。但是向 Postman 发出 GET 请求时一直给我消息 - “消息”:“此请求的授权已被拒绝。”
当我调试时,我可以将令牌视为授权的一部分,有什么方法可以记录/查看实际错误而不是“消息”:“此请求的授权已被拒绝。” ?
邮递员要求:
【问题讨论】:
【参考方案1】:以防万一其他人遇到此问题,我在 Owin Katana 文档中找到了答案。本质上,在 web.config 中放置下面的配置将在输出窗口中启用带有详细信息的日志,并且我能够看到授权失败的根本原因,因为我使用的是 Owin auth 中间件。
<system.diagnostics>
<switches>
<add name="Microsoft.Owin" value="Verbose" />
</switches>
</system.diagnostics>
【讨论】:
以上是关于如何在 web api Authentication Failed 场景中获取详细错误而不是“消息”:“此请求的授权已被拒绝。”?的主要内容,如果未能解决你的问题,请参考以下文章
Web APi 2.0优点和特点?在Web APi中如何启动Session状态?