我正在嘗試使用AD B2C與我的移動應用程序使用Xamarin.Android,但不是窗體。Xamarin.Android auth AD B2C without forms。使用MSAL還是AppAuth?
所有關於如何在Xamarin中使用AD B2C的示例都使用了MSAL,它似乎依賴於使用Xamarin.Forms。我無法找到有關如何將其集成到Xamarin.Android的示例或文檔。
例子我能找到,但不符合我的需求:
https://github.com/Azure-Samples/active-directory-android-native-appauth-b2c
https://github.com/Azure-Samples/active-directory-b2c-xamarin-native
文檔我閱讀和嘗試應用,但並沒有導致成功的認證或者並不適用於我的情況:
https://developer.xamarin.com/guides/xamarin-forms/cloud-services/authentication/azure/
https://developer.xamarin.com/guides/xamarin-forms/cloud-services/authentication/azure-ad-b2c/
https://developer.xamarin.com/guides/xamarin-forms/cloud-services/authentication/azure-ad-b2c-mobile-app/
有沒有辦法在Xamarin.Android中使用MSAL而不使用窗體,或者是否必須使用其他一些類似AppAuth的庫?
更新: 我如何試圖用MSAL:
public static string ClientId = "MyClientId";
public static string SignUpSignInPolicy = "B2C_1_MyPolicyName";
public static string Authority = "My Authority";
public static string[] Scopes = { ClientId };
private AuthenticationManager()
{
AuthenticationClient = new PublicClientApplication(ClientId, Authority);
}
public async Task<AuthenticationResult> AuthenticateAsync()
{
if (!Initialized)
throw new InvalidOperationException("Cannot authenticate before AuthenticationManager has been initialized.");
AuthResult = await AuthenticationClient.AcquireTokenAsync(Scopes,
"",
UiOptions.SelectAccount,
string.Empty,
null,
Authority,
SignUpSignInPolicy);
return AuthResult;
}
public void Initialize(Activity activity)
{
if (Initialized)
return;
// Load shared prefrences (skipped)
AuthenticationClient.PlatformParameters = new PlatformParameters(activity);
Initialized = true;
}
在呼籲AquireTokenAsync(..),這將導致NullPointerException異常:
「值不能爲空參數名:的clientId」
我使用與示例中相同的參數(並且它們不會崩潰),應該初始化所有內容。 此錯誤的一個原因可能是從Android調用它時,AquireTokenAsync(..)的參數不同。 (請參閱PublicClientApplication的源代碼,並查看預編譯器指令。)
但是,如果是這種情況,我並不真正知道如何構建該項目,以便爲Android選擇正確的版本。
UPDATE2:從活動 添加代碼,應該啓動身份驗證過程:
public class LoginActivity : Activity
{
private async void LoginButtonClicked()
{
try
{
AuthenticationManager.AuthManager.Initialize(this);
await AuthenticationManager.AuthManager.AuthenticateAsync();
}
// Create your application here
catch (Exception e)
{
CreateAndShowDialog(e, Resources.GetString(Resource.String.error_sync));
}
}
protected override void OnActivityResult(int requestCode, Result resultCode, Intent data)
{
base.OnActivityResult(requestCode, resultCode, data);
AuthenticationAgentContinuationHelper.SetAuthenticationAgentContinuationEventArgs(requestCode, resultCode, data);
}
請添加一些代碼從您的嘗試 – brennan
@bren添加的代碼和我什麼我懷疑是我的應用程序崩潰的原因。我首先省略它,因爲我認爲我的答案是,我必須使用與MSAL不同的東西。我真的不明白它是如何能夠啓動一個WebView和所有Xamarin.Android沒有Xamarin.Forms –
內的所有。我發現ClientId的值雖然是在編譯時設置的,但它的值爲null。也許我必須引用AuthenticationManager.ClientId。 這是我沒想到的行爲(來自Java-World)。 明天我會試試這個。如果這能解決我的問題,我會將其作爲解決方案發布。 –