ob7777
ob7777

Reputation: 1

Maui app auth via MSAL to get token for SQL connection for Android device

Hi I am running very similar code to the above in Maui app when trigger a method to call this code, I am prompted in android device to select my loged in corp ad account, then I am asked if I want to continue to use my named app name on same android device it gets triggered when it comes to

using Microsoft.Data.SqlClient;
using Microsoft.Identity.Client;
using System;
using System.Linq;
using System.Threading.Tasks;

public static class AzureSqlService
{
    private static readonly string _clientId = "your-client-id";
    private static readonly string _tenantId = "your-tenant-id";
    private static readonly string _sqlConnectionString = "Server=tcp:your-server.database.windows.net,1433;Database=your-database;";
    private static readonly string[] _scopes = new[] { "https://database.windows.net/.default" };

    public static async Task InitializeAsync()
    {
        // Initialize your database here if needed
    }

    public static async Task<SqlConnection> GetSqlConnectionAsync()
    {
        var app = PublicClientApplicationBuilder.Create(_clientId)
            .WithAuthority(new Uri($"https://login.microsoftonline.com/{_tenantId}"))
            .WithRedirectUri($"msal{_clientId}://auth")
            .WithLogging((level, message, containsPii) =>
            {
                System.Diagnostics.Debug.WriteLine($"MSAL: {level} {message} ");
            }, LogLevel.Verbose, enablePiiLogging: false, enableDefaultPlatformLogging: true)
            .Build();

        var accounts = await app.GetAccountsAsync();
        AuthenticationResult result;

        try
        {
            result = await app.AcquireTokenSilent(_scopes, accounts.FirstOrDefault())
                .ExecuteAsync();
        }
        catch (MsalUiRequiredException)
        {
            var currentActivity = PlatformService.GetCurrentActivity();
            try
            {
                result = await app.AcquireTokenInteractive(_scopes)
                    .WithParentActivityOrWindow(() => currentActivity)
                    .ExecuteAsync();
            }
            catch (Exception ex)
            {
                System.Diagnostics.Debug.WriteLine($"MSAL Exception: {ex.Message}");
                throw;
            }
        }

        if (result == null)
        {
            System.Diagnostics.Debug.WriteLine("MSAL: Token acquisition failed, result is null.");
            throw new InvalidOperationException("Token acquisition failed.");
        }

        System.Diagnostics.Debug.WriteLine($"MSAL: Token acquired successfully. Access Token: {result.AccessToken}");

        var connection = new SqlConnection(_sqlConnectionString)
        {
            AccessToken = result.AccessToken
        };

        return connection;
    }
}


Upvotes: -1

Views: 61

Answers (0)

Related Questions