我正在尝试使用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)。 明天我会试试这个。如果这能解决我的问题,我会将其作为解决方案发布。 –