【发布时间】:2018-01-17 09:39:51
【问题描述】:
我在 Azure 上托管了一项启用了 Azure AD 身份验证的 Rest 服务。我正在 Microsoft Add in 中使用此 Web 服务。
我不想向用户提示 Microsoft 登录页面。而是使用他的用户名和密码在后台登录并获取访问令牌和刷新令牌。
我一直在使用下面的代码:
private static string authority = String.Format(CultureInfo.InvariantCulture, aadInstance, tenant);
AuthenticationResult result = null;
string user = "";
string password = "";
string resrouce = "web service URL";
authContext = new AuthenticationContext(authority, new FileCache());
UserCredential uc = new UserPasswordCredential(user, password);
result = authContext.AcquireTokenAsync(todoListResourceId, clientId, uc).Result;
此代码的例外是“请求正文必须包含以下参数:client_secret 或 client_assertion”。我没有找到使用用户凭据传递客户端机密或客户端断言的方法。
我也试过下面的代码。在下面的代码中,使用客户端 ID 和客户端密钥并取回将在一小时内到期的访问令牌,并且此代码不返回刷新令牌。此访问令牌并非特定于用户。
string tenantName = "contoso.com";
string authString = "https://login.microsoftonline.com/" + tenantName;
AuthenticationContext authenticationContext = new AuthenticationContext(authString, false);
string clientId = "a3b4eef4-33f0-4e98-9d57-ad14549bf310";
string key = "Secret Key";
ClientCredential clientCred = new ClientCredential(clientId, key);
string resource = "Service URL ";
string token;
AuthenticationResult authenticationResult = authenticationContext.AcquireTokenAsync(resource, clientCred).Result;
token = authenticationResult.AccessToken;
有什么方法可以在不提示用户 Microsoft 登录表单的情况下从 Azure AD 获取访问令牌和刷新令牌。
【问题讨论】:
标签: c# azure authentication asp.net-web-api