invalid_grant - type = password: 用户或管理员未同意使用该应用程序

invalid_grant - type = password: user or admin has not consented to use the application

我在尝试获取令牌时遇到同意错误。由于我们的应用程序,我们无法显示用于表示同意的交互式对话框。

"AADSTS65001: The user or administrator has not consented to use the application with ID <'my native client app id'>. Send an interactive authorization request for this user and resource.

AuthenticationContext ctx = new AuthenticationContext(
string.Format("https://login.microsoftonline.com/{0}","mytenant.onmicrosoft.com"));
UserPasswordCredential cred = new UserPasswordCredential("login@mytenant.onmicrosoft.com", "Password");
var result = ctx.AcquireTokenAsync("my api uri", "my native client id", cred);

我们正在使用 grant_type=passwordclient_id 是本机应用程序 ID,resource 是 Web API 应用程序 URI。

权限方面,从客户端应用程序,已授予访问 api 应用程序的委派权限,并且还尝试在清单中设置 oauth2AllowImplicitFlow : true

所有应用程序都已在新门户的新预览版 Azure AD 部分中创建 (portal.azure.com)

不幸的是,如果您的应用程序需要访问某些资源,例如 Graph API,您将需要至少提示一次同意。

即使您的应用没有交互式登录体验,您也应该能够提示一次以在您的租户中解锁您的方案。

使用以下 URL:

https://login.microsoftonline.com/<TenantID>/oauth2/authorize?client_id=<AppID>&response_type=code&redirect_uri=<RedirectURI>&resource=<ResourceURI>&prompt=admin_consent

您可以在这里看到,我们只是简单地生成了登录名 URL,它将作为交互式登录体验的一部分生成。您需要填写自己的具体数据,如回复URL、App ID、资源URI等...

请注意,我们在强制“同意”提示的末尾添加了最终查询字符串。这应该由管理员完成,管理员可以代表整个租户同意。完成后,username/password 流程应该开始为您工作。

另外,作为补充说明,隐式授权流程与同意无关。 请阅读 OAuth 2 规范中的这一部分: https://www.rfc-editor.org/rfc/rfc6749#section-1.3.2

如果您使用 JavaScript 之类的东西创建单页应用程序,您应该只使用此设置;否则,在本不应具有此设置的应用程序上存在重大安全问题。