Created
March 30, 2025 05:29
-
-
Save hatsunea/fd276ba8e194e1da2abd81bef38cfa4f to your computer and use it in GitHub Desktop.
MauiAuthApp.Models.AutenticationModel.AuthenticationService.cs
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
internal class AuthenticationService | |
{ | |
// Azure AD B2CのクライアントID | |
private readonly string ClientId = "17xxxx-xxxx-xxxx-xxxx-xxxxxde"; | |
private readonly string[] Scopes = new string[] { "openid" }; | |
//失敗または成功のトークンを受け取るためのリダイレクトURLを提供します | |
public AuthenticationService() | |
{ | |
var builder = PublicClientApplicationBuilder | |
.Create(this.ClientId) | |
.WithRedirectUri("http://localhost") // Windowsクライアントなので、リダイレクトURLは、localhostである必要があります | |
#if ANDROID | |
.WithParentActivityOrWindow(() => Platform.CurrentActivity) | |
#elif IOS | |
.WithIosKeychainSecurityGroup("com.microsoft.adalcache") | |
#endif | |
.WithAuthority(AzureCloudInstance.AzurePublic, "common"); | |
App.PublicClientApp = builder.Build(); | |
} | |
//認証するためのメソッド | |
public async Task<AuthenticationResult> LoginAsync(CancellationToken cancellationToken) | |
{ | |
AuthenticationResult authResult = null;//認証結果 | |
try | |
{ | |
var accounts = await App.PublicClientApp.GetAccountsAsync().ConfigureAwait(false); | |
authResult = await App.PublicClientApp | |
.AcquireTokenSilent(this.Scopes, accounts.FirstOrDefault()) | |
.ExecuteAsync(); | |
} | |
catch (MsalException ex) | |
{ | |
// UIからログインする | |
if (ex.ErrorCode != "authentication_canceled") | |
{ | |
authResult = await AcquireTokenInteractiveAsync(); | |
} | |
} | |
return authResult;//認証結果を返す | |
} | |
private async Task<AuthenticationResult> AcquireTokenInteractiveAsync() | |
{ | |
#if ANDROID || IOS | |
var auth = App.PublicClientApp | |
.AcquireTokenInteractive(this.Scopes) | |
.WithUseEmbeddedWebView(true) | |
.WithParentActivityOrWindow(App.ParentWindow); | |
#else | |
var auth = App.PublicClientApp | |
.AcquireTokenInteractive(this.Scopes) | |
.WithAccount(null) | |
.WithPrompt(Prompt.SelectAccount); | |
#endif | |
var authResult = await auth.ExecuteAsync().ConfigureAwait(false); | |
return authResult; | |
} | |
/// <summary> | |
/// MSALログアウト | |
/// </summary> | |
/// <returns></returns> | |
internal async Task LogoutAsync() | |
{ | |
if (App.PublicClientApp != null) | |
{ | |
try | |
{ | |
var accounts = await App.PublicClientApp.GetAccountsAsync(); | |
foreach (var account in accounts) | |
{ | |
await App.PublicClientApp.RemoveAsync(account); | |
} | |
} | |
catch { } | |
} | |
App.PublicClientApp = null; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment