2017-08-09 36 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

是的,我已經使用客戶端憑證流程。並能夠獲得訪問令牌。我希望我會同時與多個用戶合作 –

相關問題