.NET 6应用注册授权令牌验证通过却返回401未授权错误
ASP.NET Core 6 Web API Azure AD授权异常:令牌验证通过但返回401
我正在为ASP.NET Core 6 Web API配置Azure AD应用注册授权。已通过应用注册凭据获取令牌并尝试访问API,API日志显示令牌验证通过(包括有效期、受众验证等),但客户端返回无额外信息的401-Unauthorized错误,Postman提示令牌无效。无授权的端点可正常访问,添加授权后控制器的Get方法无法被触发。应用注册已配置API权限并获得管理员同意,与微软团队共同排查仍未找到问题原因。
相关代码配置
客户端获取令牌代码
var keyValues = new List<KeyValuePair<string, string>> { new KeyValuePair<string, string>("tenant_id", tenant_id), new KeyValuePair<string, string>("client_id", client_id), new KeyValuePair<string, string>("client_secret", client_secret), new KeyValuePair<string, string>("scope", scope), new KeyValuePair<string, string>("grant_type", "client_credentials") }; var c = new FormUrlEncodedContent(keyValues); tokenUrl = "https://login.microsoftonline.com/"+tenant_id+"/oauth2/v2.0"; var call = await client.PostAsync(tokenUrl + "/token", c);
Web API的appsettings.json配置
{ "AzureAd": { "Instance": "https://login.microsoftonline.com", "Domain": "<domain>", "TenantId": "<tenant>", "ClientId": "<clientId>", "ClientSecret": "<clientSecret>", "Roles": "api://<role>" }, }
API认证配置代码
var builder = WebApplication.CreateBuilder(args); builder.Services.AddMicrosoftIdentityWebApiAuthentication(configuration);
API令牌验证日志
Microsoft.IdentityModel.LoggingExtensions.IdentityLoggerAdapter: Information: IDX10239: Lifetime of the token is valid. Microsoft.IdentityModel.LoggingExtensions.IdentityLoggerAdapter: Information: IDX10234: Audience Validated.Audience: '<audience>' Microsoft.IdentityModel.LoggingExtensions.IdentityLoggerAdapter: Information: IDX10245: Creating claims identity from the validated token: '<claims>'. Microsoft.IdentityModel.LoggingExtensions.IdentityLoggerAdapter: Information: IDX10241: Security token validated. token: <'token'>
内容的提问来源于stack exchange,提问作者B Thornton
相关产品推荐
相关产品推荐

