我正在尝试为 ASP.NET Core 6 Web API 进行应用程序注册授权。我使用应用程序注册凭据获取令牌并通过 API 进行身份验证。令牌验证似乎有效,但我收到 401-未经授权的错误,没有任何信息。在 Postman 中显示为无效令牌。
这是我获取令牌的客户端设置
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 正在使用新的调用从
appsettings.json
获取参数。
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>' `
我的客户收到了 401 - 未经授权,没有其他信息。
端点在未经授权的情况下受到攻击。
在授权开启的情况下,控制器永远不会点击路由中的 Get。 应用程序注册已设置API权限并已获得管理员同意。
我一直在与 Microsoft 合作解决此问题,看似直接的身份验证让我们都感到困惑。
事实证明,解决方案是启动时授权和验证的顺序。我必须在启动时更改这两行的顺序,然后事情就开始工作了。以下是正确的顺序。
app.UseAuthentication();
app.UseAuthorization();
我遇到了这个问题,但它仍然对我不起作用:(