Share via


Skrivbordsapp som anropar webb-API:er: Kodkonfiguration

Nu när du har skapat programmet får du lära dig hur du konfigurerar koden med programmets koordinater.

Microsoft-bibliotek som stöder skrivbordsappar

Följande Microsoft-bibliotek stöder skrivbordsappar:

Språk/ramverk Projekt på
GitHub
Paket
komma igång
Logga in användare Åtkomst till webb-API:er Allmänt tillgänglig (GA) eller
Offentlig förhandsversion1
Elektron MSAL-Node.js msal-node Library can request ID tokens for user sign-in. Library can request access tokens for protected web APIs. Offentlig förhandsversion
Java MSAL4J msal4j Library can request ID tokens for user sign-in. Library can request access tokens for protected web APIs. Allmän tillgänglighet
macOS (Swift/Obj-C) MSAL för iOS och macOS MSAL Självstudie Library can request ID tokens for user sign-in. Library can request access tokens for protected web APIs. Allmän tillgänglighet
UWP MSAL.NET Microsoft.Identity.Client Självstudie Library can request ID tokens for user sign-in. Library can request access tokens for protected web APIs. Allmän tillgänglighet
WPF MSAL.NET Microsoft.Identity.Client Självstudie Library can request ID tokens for user sign-in. Library can request access tokens for protected web APIs. Allmän tillgänglighet

1Universella licensvillkor för onlinetjänster gäller för bibliotek i offentlig förhandsversion.

Offentligt klientprogram

Ur kodsynpunkt är skrivbordsprogram offentliga klientprogram. Konfigurationen skiljer sig lite beroende på om du använder interaktiv autentisering eller inte.

Du måste skapa och manipulera MSAL.NET IPublicClientApplication.

IPublicClientApplication

Exklusivt efter kod

Följande kod instansierar ett offentligt klientprogram och loggar in användare i det offentliga Microsoft Azure-molnet med ett arbets- eller skolkonto eller ett personligt Microsoft-konto.

IPublicClientApplication app = PublicClientApplicationBuilder.Create(clientId)
    .Build();

Om du tänker använda interaktiv autentisering eller enhetskodflöde, som du såg tidigare, använder du .WithRedirectUri modifieraren.

IPublicClientApplication app;
app = PublicClientApplicationBuilder.Create(clientId)
        .WithDefaultRedirectUri()
        .Build();

Använda konfigurationsfiler

Följande kod instansierar ett offentligt klientprogram från ett konfigurationsobjekt, som kan fyllas i programmatiskt eller läsas från en konfigurationsfil.

PublicClientApplicationOptions options = GetOptions(); // your own method
IPublicClientApplication app = PublicClientApplicationBuilder.CreateWithApplicationOptions(options)
        .WithDefaultRedirectUri()
        .Build();

Mer detaljerad konfiguration

Du kan utveckla programbygget genom att lägga till ett antal modifierare. Om du till exempel vill att programmet ska vara ett program med flera klientorganisationer i ett nationellt moln, till exempel us government som visas här, kan du skriva:

IPublicClientApplication app;
app = PublicClientApplicationBuilder.Create(clientId)
        .WithDefaultRedirectUri()
        .WithAadAuthority(AzureCloudInstance.AzureUsGovernment,
                         AadAuthorityAudience.AzureAdMultipleOrgs)
        .Build();

MSAL.NET innehåller även en modifierare för Active Directory Federation Services (AD FS) 2019:

IPublicClientApplication app;
app = PublicClientApplicationBuilder.Create(clientId)
        .WithAdfsAuthority("https://consoso.com/adfs")
        .Build();

Om du vill hämta token för en B2C-klientorganisation i Azure Active Directory (Azure AD) anger du klientorganisationen enligt följande kodfragment:

IPublicClientApplication app;
app = PublicClientApplicationBuilder.Create(clientId)
        .WithB2CAuthority("https://fabrikamb2c.b2clogin.com/tfp/{tenant}/{PolicySignInSignUp}")
        .Build();

Läs mer

Mer information om hur du konfigurerar ett MSAL.NET skrivbordsprogram:

Komplett exempel med konfigurationsalternativ

Föreställ dig ett .NET-konsolprogram som har följande appsettings.json konfigurationsfil:

{
  "Authentication": {
    "AzureCloudInstance": "AzurePublic",
    "AadAuthorityAudience": "AzureAdMultipleOrgs",
    "ClientId": "00001111-aaaa-2222-bbbb-3333cccc4444"
  },

  "WebAPI": {
    "MicrosoftGraphBaseEndpoint": "https://graph.microsoft.com"
  }
}

Du har lite kod att läsa i den här filen med hjälp av . Net-tillhandahållet konfigurationsramverk:

public class SampleConfiguration
{
 /// <summary>
 /// Authentication options
 /// </summary>
 public PublicClientApplicationOptions PublicClientApplicationOptions { get; set; }

 /// <summary>
 /// Base URL for Microsoft Graph (it varies depending on whether the application runs
 /// in Microsoft Azure public clouds or national or sovereign clouds)
 /// </summary>
 public string MicrosoftGraphBaseEndpoint { get; set; }

 /// <summary>
 /// Reads the configuration from a JSON file
 /// </summary>
 /// <param name="path">Path to the configuration json file</param>
 /// <returns>SampleConfiguration as read from the json file</returns>
 public static SampleConfiguration ReadFromJsonFile(string path)
 {
  // .NET configuration
  IConfigurationRoot Configuration;
  var builder = new ConfigurationBuilder()
                    .SetBasePath(Directory.GetCurrentDirectory())
                    .AddJsonFile(path);
  Configuration = builder.Build();

  // Read the auth and graph endpoint configuration
  SampleConfiguration config = new SampleConfiguration()
  {
   PublicClientApplicationOptions = new PublicClientApplicationOptions()
  };
  Configuration.Bind("Authentication", config.PublicClientApplicationOptions);
  config.MicrosoftGraphBaseEndpoint =
  Configuration.GetValue<string>("WebAPI:MicrosoftGraphBaseEndpoint");
  return config;
 }
}

Skriv nu följande kod för att skapa ditt program:

SampleConfiguration config = SampleConfiguration.ReadFromJsonFile("appsettings.json");
var app = PublicClientApplicationBuilder.CreateWithApplicationOptions(config.PublicClientApplicationOptions)
           .WithDefaultRedirectUri()
           .Build();

Innan anropet .Build() till metoden kan du åsidosätta konfigurationen med anrop till .WithXXX metoder, som du såg tidigare.

Nästa steg

Gå vidare till nästa artikel i det här scenariot, Hämta en token för skrivbordsappen.