我正在尝试保护我的 Web API 应用程序,以便只有特定的用户和应用程序才能使用这些服务。我遵循了许多不同的说明,这些说明建议我使用以下代码进行身份验证(我已将其简化为可以在控制台应用程序中轻松重现):
class Program
{
private const string ServicesClientId = "11111111-1111-1111-1111-111111111111";
private const string ClientId = "aaaaaaaa-aaaa-aaaa-aaaa-aaaaaaaaaaaa";
private const string ClientKey = "abcdefghijklmnopqrstuvwxyz1234567890=";
private const string AadLoginUri = "https://login.windows.net/{0}";
private const string TenantId = "example.onmicrosoft.com";
private static readonly string Authority = string.Format(CultureInfo.InvariantCulture, AadLoginUri, TenantId);
static void Main(string[] args)
{
var clientCredential = new ClientCredential(ClientId, ClientKey);
var context = new AuthenticationContext(Authority, false);
// This line fails!
var appAuthResult = context.AcquireToken(ServicesClientId, clientCredential);
// AADSTS50105: Application 'aaaaaaaa-aaaa-aaaa-aaaa-aaaaaaaaaaaa' is not
// assigned to a role for the application '11111111-1111-1111-1111-111111111111'.
var appAuthTokenProvider = new ApplicationTokenProvider(context, "https://example.azurewebsites.net", clientCredential, appAuthResult);
var tokenCreds = new TokenCredentials(appAuthTokenProvider);
Console.WriteLine(tokenCreds.ToString());
Console.ReadLine();
}
}
因此,只要禁用用户分配,这段代码就可以很好地工作,但在启用用户分配的那一刻(您稍等一下,因为它似乎不会立即生效,即使它说它已成功启用),它失败。
我收到以下错误:
AADSTS50105: Application 'aaaaaaaa-aaaa-aaaa-aaaa-aaaaaaaaaaaa' is not assigned to a role for the application '11111111-1111-1111-1111-111111111111'.
我必须做什么才能让它发挥作用?
我已经尝试了各种方法来让这个问题消失,但运气不佳。我尝试过的事情:
- 将我的注册客户端的默认“Access MyWebAPI”权限添加到注册的 Web API 项目
- 更改 Web API 应用程序的 list 以添加应用程序角色:
{ “允许的成员类型”:[ “应用” ], "displayName": "通用应用程序客户端", “id”:“c27e3fa1-e96a-445c-aaf7-8cbb60cca980”, “isEnabled”:真, "description": "使用所有服务的应用程序。", “值”:“应用程序客户端” }
,然后设置应用程序权限(在注册的消费应用程序上)以拥有此新的“通用应用程序客户端”权限。 - 更改 Web API 应用程序的 list ,以在
knownClientApplications
数组下添加使用应用程序的客户端 ID。 - 我已经多次重新配置我的 Web API 应用程序,以防我在故障排除过程中出错,但最终总是这样
- 一边摸着我的头,一边揉着我的肚子。
我不知道下一步该尝试什么。
<小时/>出于引用目的,这是我的packages.config 文件:
<?xml version="1.0" encoding="utf-8"?>
<packages>
<package id="Microsoft.IdentityModel.Clients.ActiveDirectory" version="2.28.1" targetFramework="net46" />
<package id="Microsoft.Rest.ClientRuntime" version="1.8.2" targetFramework="net46" />
<package id="Microsoft.Rest.ClientRuntime.Azure.Authentication" version="0.11.3" targetFramework="net46" />
<package id="Newtonsoft.Json" version="9.0.1" targetFramework="net46" />
</packages>
这个问题与 this other question 类似,但如上所述,该问题的答案(重新配置和重新部署)对我不起作用。
最佳答案
我也可以重现这个问题。我发现当我向 Web API 授予应用程序角色时,该角色可能未按预期授予。下图供大家引用:
作为限制用户和应用程序的解决方法,我们可以在 Web API 中对其进行编码以自行实现 token 处理程序。例如,我们可以配置允许的用户、应用程序,然后解析访问 token 以检索 appid
和 upn
来验证它。关于自定义 token 处理程序的更多详细信息,您可以引用this thread .
对于最初的问题,我也在尝试内部报告。
关于azure - 无法从 AAD 获取不记名 token 来使用 Web API,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40292678/