Dela via


Skrivbordsapp som anropar webb-API:er: Kodkonfiguration

Gäller för: grön cirkel med en vit bockmarkeringssymbol. Workforce-arbetstagare vit cirkel med en grå X-symbol. externa hyresgäster (läs mer)

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 om
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 Biblioteket kan begära ID-token för användarinloggning. Biblioteket kan begära åtkomsttoken för skyddade webb-API:er. Offentlig förhandsversion
Java MSAL4J msal4j Biblioteket kan begära ID-token för användarinloggning. Biblioteket kan begära åtkomsttoken för skyddade webb-API:er. Allmän tillgänglighet
macOS (Swift/Obj-C) MSAL för iOS och macOS MSAL Handledning Biblioteket kan begära ID-token för användarinloggning. Biblioteket kan begära åtkomsttoken för skyddade webb-API:er. Allmän tillgänglighet
Universal Windows-plattform (UWP) MSAL.NET Microsoft.Identity.Client Handledning Biblioteket kan begära ID-token för användarinloggning. Biblioteket kan begära åtkomsttoken för skyddade webb-API:er. Allmän tillgänglighet
WPF MSAL.NET Microsoft.Identity.Client Handledning Biblioteket kan begära ID-token för användarinloggning. Biblioteket kan begära åtkomsttoken för skyddade webb-API:er. 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 få tag på token för en B2C-klientorganisation i Azure Active Directory (Azure AD) anger du din klientorganisation 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 till metoden .Build() kan du åsidosätta din konfiguration med anrop till metoderna .WithXXX, som visats tidigare.

Nästa steg

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