1

我有一個Xamarin.Forms應用程序(iOS,Android,UWP)連接到Azure移動應用程序的身份驗證服務。從我所讀的內容來看,實施起來似乎非常簡單。我在UWP項目和Android中測試,都獲得了相同的結果。身份驗證 - Xamarin.Forms,Azure移動應用程序

登錄時,我覺得這個可愛的「無法連接到你現在需要的服務。」我的代碼中沒有看到任何錯誤。這裏可能會發生什麼?

的Windows UWP:

public async Task<bool> Authenticate() 
{ 
    string message = string.Empty; 
    var success = false; 

    try 
    { 
     // Sign in with Facebook login using a server-managed flow. 
     if (user == null) 
     { 
      user = await TaskService.DefaultService.CurrentClient.LoginAsync(MobileServiceAuthenticationProvider.Facebook); 
      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; 
} 

安卓:

public async Task<bool> Authenticate() 
{ 
    var success = false; 
    var message = string.Empty; 
    try 
    { 
     // Sign in with Facebook login using a server-managed flow. 
     user = await TaskService.DefaultService.CurrentClient.LoginAsync(this, 
      MobileServiceAuthenticationProvider.Facebook); 
     if (user != null) 
     { 
      message = string.Format("you are now signed-in as {0}.", 
       user.UserId); 
      success = true; 
     } 
    } 
    catch (Exception ex) 
    { 
     message = ex.Message; 
    } 

    // Display the success or failure message. 
    AlertDialog.Builder builder = new AlertDialog.Builder(this); 
    builder.SetMessage(message); 
    builder.SetTitle("Sign-in result"); 
    builder.Create().Show(); 

    return success; 
} 

無法連接到服務錯誤: Can't connect to service error in Windows UWP

的在Facebook上的應用程序設置: Facebook App Settings

訪問:

編輯: 我已經試過移動客戶端代碼到App.c S:

private static MobileServiceClient _Client; 
public static MobileServiceClient Client 
{ 
    get 
    { 
     if(_Client == null) _Client = new MobileServiceClient(AppConstants.AzureMobileServiceURL); 
     return _Client; 
    } 
    set { _Client = value; } 
} 

而且在MainPage.xaml.cs中新的呼叫:

uesr = await Slated.App.Client.LoginAsync(MobileServiceAuthenticationProvider.Facebook); 

同樣的結果!

另注:我的Azure的移動服務URL 包括https://開頭

編輯2:下面 代碼登錄後臺,看起來重定向到/登錄/ Facebook的時候是一個問題,認證的其餘部分似乎繼續確定。僅供參考 - 取代了敏感數據____

2016-07-29T18:38:43 PID[6684] Verbose  Received request: GET https://________.azurewebsites.net/login/facebook 
2016-07-29T18:38:43 PID[6684] Information Redirecting: https://www.facebook.com/dialog/oauth?response_type=code&client_id=_____________&redirect_uri=https%3A%2F%2F________.azurewebsites.net%2F.auth%2Flogin%2Ffacebook%2Fcallback&scope=public_profile&state=_____________________________&display=popup 
2016-07-29T18:38:50 PID[6684] Verbose  Received request: GET https://________.azurewebsites.net/.auth/login/facebook/callback?code=____________________ 
2016-07-29T18:38:50 PID[6684] Verbose  Calling into external HTTP endpoint GET https://graph.facebook.com/oauth/access_token. 
2016-07-29T18:38:51 PID[6684] Verbose  Calling into external HTTP endpoint GET https://graph.facebook.com/oauth/access_token. 
2016-07-29T18:38:51 PID[6684] Verbose  Calling into external HTTP endpoint GET https://graph.facebook.com/me. 
2016-07-29T18:38:51 PID[6684] Information Login completed for 'Thomas Gardner'. Provider: 'facebook'. 
2016-07-29T18:38:51 PID[6684] Verbose  Writing 'AppServiceAuthSession' cookie for site '________.azurewebsites.net'. Length: 512. 
2016-07-29T18:38:51 PID[6684] Information Redirecting: https://________.azurewebsites.net/login/facebook 
2016-07-29T18:38:51 PID[6684] Verbose  Received request: GET https://________.azurewebsites.net/login/facebook 
2016-07-29T18:38:51 PID[6684] Verbose  Found 'AppServiceAuthSession' cookie for site '________.azurewebsites.net'. Length: 512. 
2016-07-29T18:38:51 PID[6684] Verbose  Authenticated Thomas Gardner successfully using 'Session Cookie' authentication. 
2016-07-29T18:38:52 PID[6684] Verbose  Received request: GET https://________.azurewebsites.net/login/facebook 
2016-07-29T18:38:52 PID[6684] Verbose  Found 'AppServiceAuthSession' cookie for site '________.azurewebsites.net'. Length: 512. 
2016-07-29T18:38:52 PID[6684] Verbose  Authenticated __________ successfully using 'Session Cookie' authentication. 
2016-07-29T18:38:52 PID[6684] Information Request, Method=GET, Url=https://________.azurewebsites.net/login/facebook, Message='https://________.azurewebsites.net/login/facebook' 
2016-07-29T18:38:52 PID[6684] Information Message='Will use same 'JsonMediaTypeFormatter' formatter', Operation=JsonMediaTypeFormatter.GetPerRequestFormatterInstance 
2016-07-29T18:38:52 PID[6684] Information Message='Selected formatter='JsonMediaTypeFormatter', content-type='application/json; charset=utf-8'', Operation=DefaultContentNegotiator.Negotiate 
2016-07-29T18:38:52 PID[6684] Information Response, Status=404 (NotFound), Method=GET, Url=https://________.azurewebsites.net/login/facebook, Message='Content-type='application/json; charset=utf-8', content-length=unknown' 

後端代碼:它是從MSFT的模板代碼複製。對創業公司做的事情並不多。 Startup.Mobile.App.cs

public partial class Startup 
{ 
    public static void ConfigureMobileApp(IAppBuilder app) 
    { 
     HttpConfiguration config = new HttpConfiguration(); 

     //For more information on Web API tracing, see http://go.microsoft.com/fwlink/?LinkId=620686 
     config.EnableSystemDiagnosticsTracing(); 

     new MobileAppConfiguration() 
      .UseDefaultConfiguration() 
      .ApplyTo(config); 

     // Use Entity Framework Code First to create database tables based on your DbContext 
     Database.SetInitializer(new SlatedInitializer()); 

     // To prevent Entity Framework from modifying your database schema, use a null database initializer 
     // Database.SetInitializer<SlatedContext>(null); 

     MobileAppSettingsDictionary settings = config.GetMobileAppSettingsProvider().GetMobileAppSettings(); 

     if (string.IsNullOrEmpty(settings.HostName)) 
     { 
      // This middleware is intended to be used locally for debugging. By default, HostName will 
      // only have a value when running in an App Service application. 
      app.UseAppServiceAuthentication(new AppServiceAuthenticationOptions 
      { 
       SigningKey = ConfigurationManager.AppSettings["SigningKey"], 
       ValidAudiences = new[] { ConfigurationManager.AppSettings["ValidAudience"] }, 
       ValidIssuers = new[] { ConfigurationManager.AppSettings["ValidIssuer"] }, 
       TokenHandler = config.GetAppServiceTokenHandler() 
      }); 
     } 
     app.UseWebApi(config); 
    } 
} 

public class SlatedInitializer : CreateDatabaseIfNotExists<SlatedContext> 
{ 
    protected override void Seed(SlatedContext context) 
    { 
     /*List<Tasks> todoItems = new List<Tasks> 
     { 
      new Tasks { Id = Guid.NewGuid().ToString(), Text = "First item", Complete = false }, 
      new Tasks { Id = Guid.NewGuid().ToString(), Text = "Second item", Complete = false }, 
     }; 

     foreach (Tasks todoItem in todoItems) 
     { 
      context.Set<Tasks>().Add(todoItem); 
     }*/ 

     base.Seed(context); 
    } 
} 
+0

請您可以打開後端的診斷日誌並查看日誌以查看是否有任何錯誤。另外,您能否提供如何配置身份驗證/授權部分的詳細信息? –

+0

剛剛添加到問題。感謝您的幫助。 – Thomas

+0

您是否可以包含您正在使用的客戶端和服務器軟件包的版本? – brettsam

回答

1

從正在使用中的URI,它看起來像你混合移動服務和移動應用之間的包。這兩個是不是兼容。請參閱Client and server versioning in Mobile Apps and Mobile Services

在服務器上,您應該使用Microsoft.Azure.Mobile.Server。*。確保你沒有WindowsAzure.MobileServices.Backend形式的包。

在客戶端上,您必須使用包Microsoft.Azure.Mobile.Client

+0

完成後,我已經更新它,包括條件,因爲它最初做,但我仍然得到錯誤和後端診斷日誌是相同的。 – Thomas

+0

@Thomas您是否可以使用更新後的代碼更新您的帖子,以便更輕鬆地排除您已採取的措施? –

+0

完成。感謝您的幫助。 – Thomas

0
user = await App.MobileService .LoginAsync(MobileServiceAuthenticationProvider.Facebook); 

試試這行代碼。這應該和用戶ID 你可以簡單地做這樣的:

var userId = user.Id; 
+0

假設你打算將if(user!= null)改爲if(user.UserId!= null),那麼這沒有幫助。同樣的結果。 – Thomas

+0

Nope, 我的意思是替換該行: user = await TaskService.DefaultService.CurrentClient.LoginAsync(MobileServiceAuthenticationProvider.Facebook); 與該行: user = await App.MobileService .LoginAsync(MobileServiceAuthenticationProvider.Facebook); –

+0

並確保您的移動服務網址在app.xaml.cs 中以https開頭。這是必需的。 –

0

那麼這裏我如何做到這一點:在app.xaml.cs

public static MobileServiceClient MobileService = new MobileServiceClient("https://yourmobileservices.azurewebsites.net"); 

然後在後面的代碼:

user = await App.MobileService.LoginAsync(MobileServiceAuthenticationProvider.Facebook); 

和它的作品就像一個魅力對我來說,並確保在標記存儲處於高級設置下的 身份驗證選項卡上的天藍色門戶中。

+0

也做過了。這是所有指南都承諾的。這是我的Facebook身份驗證設置的問題?重定向URL導致服務器響應404(.../login/facebook) – Thomas

+0

@Thomas看到這個UWP [示例](https://code.msdn.microsoft.com/Facebook-authentification-bceea645)我希望它會幫助你。 –

相關問題