【问题标题】:WebAPI Non-interactive authenticating to Azure AD using username & passwordWebAPI 使用用户名和密码对 Azure AD 进行非交互式身份验证
【发布时间】: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


    【解决方案1】:

    您似乎在 azure 广告中注册了一个使用用户名和密码进行身份验证的网络应用程序/API。我们只能使用来自本机客户端的资源所有者流。机密客户端(例如网站)不能使用直接用户凭据。

    您需要将其作为公共客户端(本机客户端应用)调用,而不是作为机密客户端(网络应用/API)调用。有关如何使用 ADAL .NET 通过用户名/密码对用户进行身份验证的更多信息,请参阅 this document。尤其是 Constraints & Limitations 部分。

    您也可以在您的场景中使用client credential flow,但是通过此流程,应用程序将其客户端凭据提供给 OAuth2 令牌颁发端点,并作为回报获得一个访问令牌,该令牌代表应用程序本身而无需任何用户信息。应用程序不需要获取刷新令牌。当访问令牌过期时,它会简单地返回到 OAuth2 令牌发布端点以获取新的令牌。

    【讨论】:

    • 是的,我使用了客户端凭据流。并能够获得访问令牌。我希望我能同时与多个用户合作
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-05-16
    • 2016-05-08
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多