0

我已成功地在我的Xamarin表單應用程序中使用客戶端身份驗證來獲取access_token(或Microsoft令牌的authenticationToken)。我能夠使用相同的訪問令牌獲得更多的用戶信息(電子郵件,姓名等)。現在,當我嘗試將該令牌傳遞給Azure移動服務後端時,出現401錯誤。Azure移動服務LoginAsync方法不能與Microsoft Auth令牌一起使用

這裏是我的代碼:

 private async System.Threading.Tasks.Task<string> MSGetUserInfo(Account account) 
    { 
     // Reference: http://graph.microsoft.io/en-us/docs/overview/call_api 
     // Note that Microsoft don't recognize the access_token header entry, but rely instead on an Authorization header entry 

     var client = new HttpClient(); 
     var userInfoRequest = new HttpRequestMessage() 
     { 
      RequestUri = new Uri("https://graph.microsoft.com/v1.0/me"), 
      Method = HttpMethod.Get, 
     }; 
     // Add acccess Bearer 
     userInfoRequest.Headers.Authorization = new System.Net.Http.Headers.AuthenticationHeaderValue("Bearer", account.Properties["access_token"]); 
     using (var response = await client.SendAsync(userInfoRequest).ConfigureAwait(false)) 
     { 
      if (response.IsSuccessStatusCode) 
      { 
       Models.User user = new Models.User(); 
       var responseString = await response.Content.ReadAsStringAsync().ConfigureAwait(false); 
       var jobject = JObject.Parse(responseString); 
       var userName = (string)jobject["userPrincipalName"]; 
       // Check username is valid 
       if (String.IsNullOrEmpty(userName)) 
       { 
        throw new Exception("Username was not set for authenticated user"); 
       } 
       else 
        user.ProviderLoginId = userName; 

       var userDisplayName = (string)jobject["displayName"]; 
       // Replace display name if invalid 
       if (String.IsNullOrWhiteSpace(userDisplayName)) 
       { 
        userDisplayName = userName; 
       } 
       else 
        user.Name = userDisplayName; 
       var userEmail = (string)jobject["mail"]; 
       // Replace email if invalid 
       if (String.IsNullOrWhiteSpace(userEmail)) 
       { 
        userEmail = userName; 
       } 
       else 
        user.Email = userEmail; 

       Valufy.App.currentUser = user; 
      } 
      else 
      { 
       throw new Exception("OAuth2 request failed: " + await response.Content.ReadAsStringAsync().ConfigureAwait(false)); 
      } 
     } 
     return "success"; 
    } 

上面的代碼片段工作在得到我的用戶詳細信息。現在,當我嘗試在隨後的調用中使用相同的標記時,我得到一個404:

 public async Task<bool> Authenticate(string token) 
    { 
     string message = string.Empty; 
     var success = false; 
     JObject objToken = new JObject(); 
     //objToken.Add("access_token", token); //for facebook and google 
     objToken.Add("authenticationToken", token); //for microsoft 

     try 
     { 
      // Sign in with Facebook login using a server-managed flow. 
      if (user == null) 
      { 
       //ProviderAuth("MICROSOFT"); 
       user = await syncMgr.CurrentClient 
        .LoginAsync(MobileServiceAuthenticationProvider.MicrosoftAccount, objToken); 
       if (user != null) 
       { 
        success = true; 
        message = string.Format("You are now signed-in as {0}.", user.UserId); 
       } 
      } 

     } 
     catch (Exception ex) 
     { 
      message = string.Format("Authentication Failed: {0}", ex.Message); 
     } 

     // Display the success or failure message. 
    //  await new MessageDialog(message, "Sign-in result").ShowAsync(); 

     return success; 
    } 

有什麼我做錯了嗎?任何和所有的援助表示讚賞。

+0

什麼是您的應用程序服務的身份驗證的配置是什麼樣子? –

回答

0

根據您的描述,我遵循此Git sample關於Microsoft Graph Connect Sample for UWP(REST)。我可以得到access_token,它可以像Microsoft Graph API一樣按預期工作(例如Get a user)。但是當我使用這個access_token作爲authenticationToken令牌對象MobileServiceClient.LoginAsync時,我也可以得到401未授權

然後我檢查了託管客戶端的Azure移動應用程序約Authenticate users。對於客戶管理的認證流程,我發現,有關使用Microsoft帳戶的官方代碼示例使用Live SDK的工作如下:

// Request the authentication token from the Live authentication service. 
// The wl.basic scope should always be requested. Other scopes can be added 
LiveLoginResult result = await liveIdClient.LoginAsync(new string[] { "wl.basic" }); 
if (result.Status == LiveConnectSessionStatus.Connected) 
{ 
    session = result.Session; 

    // Get information about the logged-in user. 
    LiveConnectClient client = new LiveConnectClient(session); 
    LiveOperationResult meResult = await client.GetAsync("me"); 

    // Use the Microsoft account auth token to sign in to App Service. 
    MobileServiceUser loginResult = await App.MobileService 
     .LoginWithMicrosoftAccountAsync(result.Session.AuthenticationToken); 
} 

注:由於LiveConnectSession規定有關AuthenticationToken

認證令牌爲登錄和連接的用戶。

雖然檢查authentication with Microsoft Graph,我只能找到access_token而不是AuthenticationToken

UPDATE:

我已經通過檢查提琴手和LiveLogin for WP8Microsoft Account Authentication for Mobile Apps捕捉授權請求。我發現MS帳戶身份驗證與Live SDK具有類似的授權請求。

enter image description here

我認爲你需要利用現場SDK使用微軟帳戶客戶端身份驗證時,對用戶進行認證。我發現Live SDK下載頁面不存在,您可以按照Live SDK for WP8開始使用Live SDK。

UPDATE2:

,對客戶端流量的認證(微軟賬戶),你可以利用MobileServiceClient.LoginWithMicrosoftAccountAsync("{Live-SDK-session-authentication-token}"),也可以使用LoginAsync與價值{"access_token":"{the_access_token}"}{"authenticationToken":"{Live-SDK-session-authentication-token}"}的令牌參數。我從MSA測試LoginAsyncaccess_token和檢索記錄的信息如下:

+0

謝謝布魯斯。你能解決這個問題嗎?如果是這樣,你可以分享代碼嗎?特別是,我對使用LiveLoginResult使用哪些庫感到困惑。 – sidsud

+0

我已經更新了我的回覆,你可以參考它。 –

+0

謝謝布魯斯。我注意到你使用了response_type = code而不是response_type = token。一旦你得到了代碼,你是否會在單獨的調用中獲得令牌?我問的原因是我需要令牌在LoginAsync調用中發回它。 – sidsud

相關問題