This package contains the binaries of the Microsoft Authentication Library for .NET (MSAL.NET).
MSAL.NET makes it easy to obtain tokens from the Microsoft identity platform for developers (formally Azure AD v2.0) signing-in users with work & school accounts, Microsoft personal accounts, and social identities via Azure AD B2C. These tokens provide access to Microsoft Cloud API and any other API secured by the Microsoft identity platform. This version supports adding authentication functionality to your .NET based clients - .NET, .NET Framework, .NET MAUI, Xamarin iOS, Xamarin Android and UWP
namespaceMA531.Helpers;
publicstaticclassConstants
{
//The Application or Client ID will be generated while registering the app in the Azure portal. Copy and paste the GUID.publicstaticreadonlystringClientId="2f43d642-8134-4b0a-9841-2a0b1521f9a4";
//Leaving the scope to its default values.publicstaticreadonlystring[] Scopes=newstring[] { "User.Read", "profile", "openid" ,
"email"};
}
建立支援類別 - Constants.cs
滑鼠右擊專案節點下的 [Helpers] 節點
從彈出視窗中,點選 [加入] > [類別]
當 [新增項目] 對話窗出現之後,在下方 [名稱] 欄位內,輸入 AuthService
最後點選右下方的 [新增] 按鈕
使用底下程式碼替換掉剛剛產生的程式碼
usingMicrosoft.Identity.Client;
usingSystem;
usingSystem.Collections.Generic;
usingSystem.Linq;
usingSystem.Text;
usingSystem.Threading.Tasks;
namespaceMA531.Helpers;
publicclassAuthService
{
privatereadonlyIPublicClientApplicationauthenticationClient;
// Providing the RedirectionUri to receive the token based on success or failure.publicAuthService()
{
authenticationClient=PublicClientApplicationBuilder.Create(Constants.ClientId)
.WithRedirectUri($"msal{Constants.ClientId}://auth")
.Build();
}
publicasyncTaskTest()
{
varfoo=awaitauthenticationClient.GetAccountAsync(Constants.ClientId);
}
// Propagates notification that the operation should be cancelled.publicasyncTask<AuthenticationResult> LoginAsync(CancellationTokencancellationToken)
{
AuthenticationResultresult;
try
{
result=awaitauthenticationClient
.AcquireTokenInteractive(Constants.Scopes)
.WithPrompt(Prompt.ForceLogin) //This is optional. If provided, on each execution, the username and the password must be entered.
#ifANDROID
.WithParentActivityOrWindow(Microsoft.Maui.ApplicationModel.Platform.CurrentActivity)
#endif
.WithUseEmbeddedWebView(true)
.ExecuteAsync(cancellationToken);
returnresult;
}
catch (MsalClientException)
{
returnnull;
}
}
}
<queries>
<packageandroid:name="com.azure.authenticator" />
<packageandroid:name="com.companyname.ma531" />
<!-- This value should be copied from the MauiAuthApp.csproj file -->
<packageandroid:name="com.microsoft.windowsintune.companyportal" />
</queries>