2017-08-09 68 views
1

我有Azure上托管的Rest服务,并且Azure AD身份验证已启用。我在使用Microsoft Add这个Web服务。WebAPI使用用户名和密码对Azure AD进行非交互式验证

我不想提示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; 

有没有什么办法让从Azure的AD访问令牌和刷新令牌不提示用户的Microsoft登录表单。

回答

1

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

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

您也可以在您的方案中使用client credential flow,但通过此流程,应用程序向OAuth2令牌颁发端点呈现其客户端凭据,并返回获取代表应用程序本身的访问令牌,而无需任何用户信息。有不需要为应用程序获取刷新令牌。当访问令牌到期时,它只会返回到OAuth2令牌颁发端点以获取新的端点。

+0

是的,我已经使用客户端凭证流程。并能够获得访问令牌。我希望我会同时与多个用户合作 –

相关问题