从应用程序设置中访问客户端密钥(Azure AD身份验证).NET 6应用程序

huangapple go评论109阅读模式
英文:

Access client secret (Azure AD auth) from app settings .net 6 app

问题

我有一个使用 Azure AD 进行身份验证的 .NET 6 应用程序。以下是详细信息:

appsettings.json

  1. "AzureAd": {
  2. "Instance": "https://login.microsoftonline.com/",
  3. "Domain": "",
  4. "ClientId": "",
  5. "TenantId": "",
  6. "CallbackPath": "/signin-oidc",
  7. "SignedOutCallbackPath": "/signout-oidc",
  8. "ClientSecret": "@Microsoft.KeyVault(SecretUri=https://mykv.vault.azure.net/secrets/myclientsecret/)"
  9. }

Program.cs

  1. services.AddAuthentication(OpenIdConnectDefaults.AuthenticationScheme)
  2. .AddMicrosoftIdentityWebApp(Configuration)
  3. .EnableTokenAcquisitionToCallDownstreamApi()
  4. .AddInMemoryTokenCaches()
  5. .AddDownstreamApi("MyService", Configuration.GetSection("MyService")); // MyService 也在 appsettings 中包含 baseurl 和 scopes

该应用程序已部署到应用服务,并具有以下应用程序设置:
名称:AzureAd__ClientSecret
值:@Microsoft.KeyVault(SecretUri=https://mykv.vault.azure.net/secrets/myclientsecret/)

我期望从 KeyVault 中读取 ClientSecret 的值,而其余部分从 appsettings.json 中读取。我该如何实现这一点?如果在 appsettings 中硬编码客户端密钥,它可以正常工作。我不明白为什么这样做会导致登录问题?

此外,已添加 RedirectURI。

App Service 配置快照:

从应用程序设置中访问客户端密钥(Azure AD身份验证).NET 6应用程序

英文:

I have a .net 6 app using azure ad for authentication. Below are the details:

appsettings.json

  1. "AzureAd": {
  2. "Instance": "https://login.microsoftonline.com/",
  3. "Domain": "",
  4. "ClientId": "",
  5. "TenantId": "",
  6. "CallbackPath": "/signin-oidc",
  7. "SignedOutCallbackPath ": "/signout-oidc"
  8. "ClientSecret": "@Microsoft.KeyVault(SecretUri=https://mykv.vault.azure.net/secrets/myclientsecret/)"

Program.cs

  1. services.AddAuthentication(OpenIdConnectDefaults.AuthenticationScheme)
  2. .AddMicrosoftIdentityWebApp(Configuration)
  3. .EnableTokenAcquisitionToCallDownstreamApi()
  4. .AddInMemoryTokenCaches()
  5. .AddDownstreamApi("MyService", Configuration.GetSection("MyService")); //MyService is also present in appsetting with baseurl and scopes

The app is deployed in app service and has the following app setting:
Name: AzureAd__ClientSecret
Value: @Microsoft.KeyVault(SecretUri=https://mykv.vault.azure.net/secrets/myclientsecret/)

I expect the ClientSecret value read from keyvault and the rest to be read from the appsettings json. How can I make this happen? If I hardcode client secret in appsetting it works. I am struggling to understand why this is not allowing sign in?

Also RedirectURI has been added.

Snap of App Service Configuration

从应用程序设置中访问客户端密钥(Azure AD身份验证).NET 6应用程序

答案1

得分: 1

I am able to authenticate and login even without the Client Secret.

>I expect the ClientSecret value read from keyvault and the rest to be read from the appsettings json.

I have set the key ClientSecret without any value in appsettings.json file.

My appsettings.json:

  1. {
  2. "AzureAd": {
  3. "Instance": "https://login.microsoftonline.com/",
  4. "Domain": "*****.onmicrosoft.com",
  5. "TenantId": "**********",
  6. "ClientId": "**********",
  7. "CallbackPath": "/signin-oidc",
  8. "ClientSecret": ""
  9. },
  10. "Logging": {
  11. "LogLevel": {
  12. "Default": "Information",
  13. "Microsoft.AspNetCore": "Warning"
  14. }
  15. },
  16. "AllowedHosts": "*",
  17. "KeyVault": {
  18. "URI": "https://HarshuKV8June.vault.azure.net/"
  19. }
  20. }

My .csproj file:

  1. <Project Sdk="Microsoft.NET.Sdk.Web">
  2. <PropertyGroup>
  3. <TargetFramework>net6.0</TargetFramework>
  4. <Nullable>enable</Nullable>
  5. <ImplicitUsings>enable</ImplicitUsings>
  6. <UserSecretsId>aspnet-WebApplication2-f96bb6f0-eef0-4193-a9b3-6a006134f076</UserSecretsId>
  7. </PropertyGroup>
  8. <ItemGroup>
  9. <PackageReference Include="Microsoft.AspNetCore.Authentication.JwtBearer" Version="6.0.16" NoWarn="NU1605" />
  10. <PackageReference Include="Microsoft.AspNetCore.Authentication.OpenIdConnect" Version="6.0.16" NoWarn="NU1605" />
  11. <PackageReference Include="Microsoft.Identity.Web" Version="2.7.0" />
  12. <PackageReference Include="Microsoft.Identity.Web.UI" Version="2.7.0" />
  13. </ItemGroup>
  14. </Project>

Use the below code to retrieve the Client Secret from Azure Key Vault.

Use, any one line of below code to retrieve the secret value from KeyVault.

  1. var ClientSecret = secretClient.GetSecret("ClientSecret").Value.Value;

OR

  1. var secretValue = await secretClient.GetSecretAsync("ClientSecret");

My Program.cs file:

  1. using Azure.Identity;
  2. using Azure.Security.KeyVault.Secrets;
  3. using Microsoft.AspNetCore.Authentication;
  4. using Microsoft.AspNetCore.Authentication.OpenIdConnect;
  5. using Microsoft.AspNetCore.Authorization;
  6. using Microsoft.AspNetCore.Mvc.Authorization;
  7. using Microsoft.Extensions.Configuration;
  8. using Microsoft.Identity.Web;
  9. using Microsoft.Identity.Web.UI;
  10. using System.ComponentModel;
  11. var builder = WebApplication.CreateBuilder(args);
  12. var KV = builder.Configuration["KeyVault:URI"];
  13. var cred = new DefaultAzureCredential();
  14. var secretClient = new SecretClient(new Uri(KV), cred);
  15. var ClientSecret = secretClient.GetSecret("ClientSecret").Value.Value;
  16. var secretValue = await secretClient.GetSecretAsync("ClientSecret");
  17. //Setting the ClientSecret to the key in `appsettings.json` file
  18. builder.Configuration["AzureAD:ClientSecret"] = ClientSecret;
  19. //Retrieving the value from `appsettings.json` file
  20. var setClientSecret = builder.Configuration.GetValue<string>("AzureAD:ClientSecret");
  21. // Add services to the container.
  22. builder.Services.AddAuthentication(OpenIdConnectDefaults.AuthenticationScheme)
  23. .AddMicrosoftIdentityWebApp(builder.Configuration.GetSection("AzureAd"));
  24. builder.Services.AddAuthorization(options =>
  25. {
  26. options.FallbackPolicy = options.DefaultPolicy;
  27. });
  28. builder.Services.AddRazorPages()
  29. .AddMicrosoftIdentityUI();
  30. var app = builder.Build();
  31. if (!app.Environment.IsDevelopment())
  32. {
  33. app.UseExceptionHandler("/Error");
  34. app.UseHsts();
  35. }
  36. app.UseHttpsRedirection();
  37. app.UseStaticFiles();
  38. app.UseRouting();
  39. app.UseAuthentication();
  40. app.UseAuthorization();
  41. app.MapRazorPages();
  42. app.MapControllers();
  43. app.Run();

ClientSecret Value from KeyVault:

从应用程序设置中访问客户端密钥(Azure AD身份验证).NET 6应用程序

Redirect URI in AAD:

从应用程序设置中访问客户端密钥(Azure AD身份验证).NET 6应用程序

Output:

从应用程序设置中访问客户端密钥(Azure AD身份验证).NET 6应用程序

Localhost:

从应用程序设置中访问客户端密钥(Azure AD身份验证).NET 6应用程序

Deployed App:

从应用程序设置中访问客户端密钥(Azure AD身份验证).NET 6应用程序

英文:

Iam able to authenticate and login even without the Client Secret.

>I expect the ClientSecret value read from keyvault and the rest to be read from the appsettings json.

I have set the key ClientSecret without any value in appsettings.json file.

My appsettings.json:

  1. {
  2. &quot;AzureAd&quot;: {
  3. &quot;Instance&quot;: &quot;https://login.microsoftonline.com/&quot;,
  4. &quot;Domain&quot;: &quot;*****.onmicrosoft.com&quot;,
  5. &quot;TenantId&quot;: &quot;**********&quot;,
  6. &quot;ClientId&quot;: &quot;**********&quot;,
  7. &quot;CallbackPath&quot;: &quot;/signin-oidc&quot;,
  8. &quot;ClientSecret&quot;: &quot;&quot;
  9. },
  10. &quot;Logging&quot;: {
  11. &quot;LogLevel&quot;: {
  12. &quot;Default&quot;: &quot;Information&quot;,
  13. &quot;Microsoft.AspNetCore&quot;: &quot;Warning&quot;
  14. }
  15. },
  16. &quot;AllowedHosts&quot;: &quot;*&quot;,
  17. &quot;KeyVault&quot;: {
  18. &quot;URI&quot;: &quot;https://HarshuKV8June.vault.azure.net/&quot;
  19. }
  20. }

My .csproj file:

  1. &lt;Project Sdk=&quot;Microsoft.NET.Sdk.Web&quot;&gt;
  2. &lt;PropertyGroup&gt;
  3. &lt;TargetFramework&gt;net6.0&lt;/TargetFramework&gt;
  4. &lt;Nullable&gt;enable&lt;/Nullable&gt;
  5. &lt;ImplicitUsings&gt;enable&lt;/ImplicitUsings&gt;
  6. &lt;UserSecretsId&gt;aspnet-WebApplication2-f96bb6f0-eef0-4193-a9b3-6a006134f076&lt;/UserSecretsId&gt;
  7. &lt;/PropertyGroup&gt;
  8. &lt;ItemGroup&gt;
  9. &lt;PackageReference Include=&quot;Microsoft.AspNetCore.Authentication.JwtBearer&quot; Version=&quot;6.0.16&quot; NoWarn=&quot;NU1605&quot; /&gt;
  10. &lt;PackageReference Include=&quot;Microsoft.AspNetCore.Authentication.OpenIdConnect&quot; Version=&quot;6.0.16&quot; NoWarn=&quot;NU1605&quot; /&gt;
  11. &lt;PackageReference Include=&quot;Microsoft.Identity.Web&quot; Version=&quot;2.7.0&quot; /&gt;
  12. &lt;PackageReference Include=&quot;Microsoft.Identity.Web.UI&quot; Version=&quot;2.7.0&quot; /&gt;
  13. &lt;/ItemGroup&gt;
  14. &lt;/Project&gt;

Use the below code to retrieve the Client Secret from Azure Key Vault.

Use, any one line of below code to retrieve teh secret value from KeyVault.

  1. var ClientSecret = secretClient.GetSecret(&quot;ClientSecret&quot;).Value.Value;

OR

  1. var secretValue = await secretClient.GetSecretAsync(&quot;ClientSecret&quot;);

My Program.cs file:

  1. using Azure.Identity;
  2. using Azure.Security.KeyVault.Secrets;
  3. using Microsoft.AspNetCore.Authentication;
  4. using Microsoft.AspNetCore.Authentication.OpenIdConnect;
  5. using Microsoft.AspNetCore.Authorization;
  6. using Microsoft.AspNetCore.Mvc.Authorization;
  7. using Microsoft.Extensions.Configuration;
  8. using Microsoft.Identity.Web;
  9. using Microsoft.Identity.Web.UI;
  10. using System.ComponentModel;
  11. var builder = WebApplication.CreateBuilder(args);
  12. var KV = builder.Configuration[&quot;KeyVault:URI&quot;];
  13. var cred = new DefaultAzureCredential();
  14. var secretClient = new SecretClient(new Uri(KV), cred);
  15. var ClientSecret = secretClient.GetSecret(&quot;ClientSecret&quot;).Value.Value;
  16. var secretValue = await secretClient.GetSecretAsync(&quot;ClientSecret&quot;);
  17. //Setting the ClientSecret to the key in `appsettings.json` file
  18. builder.Configuration[&quot;AzureAD:ClientSecret&quot;] = ClientSecret;
  19. //Retrieving the value from `appsettings.json` file
  20. var setClientSecret = builder.Configuration.GetValue&lt;string&gt;(&quot;AzureAD:ClientSecret&quot;);
  21. // Add services to the container.
  22. builder.Services.AddAuthentication(OpenIdConnectDefaults.AuthenticationScheme)
  23. .AddMicrosoftIdentityWebApp(builder.Configuration.GetSection(&quot;AzureAd&quot;));
  24. builder.Services.AddAuthorization(options =&gt;
  25. {
  26. options.FallbackPolicy = options.DefaultPolicy;
  27. });
  28. builder.Services.AddRazorPages()
  29. .AddMicrosoftIdentityUI();
  30. var app = builder.Build();
  31. if (!app.Environment.IsDevelopment())
  32. {
  33. app.UseExceptionHandler(&quot;/Error&quot;);
  34. app.UseHsts();
  35. }
  36. app.UseHttpsRedirection();
  37. app.UseStaticFiles();
  38. app.UseRouting();
  39. app.UseAuthentication();
  40. app.UseAuthorization();
  41. app.MapRazorPages();
  42. app.MapControllers();
  43. app.Run();

ClientSecret Value from KeyVault:

从应用程序设置中访问客户端密钥(Azure AD身份验证).NET 6应用程序

Redirect URI in AAD:

从应用程序设置中访问客户端密钥(Azure AD身份验证).NET 6应用程序

Output:

从应用程序设置中访问客户端密钥(Azure AD身份验证).NET 6应用程序

Localhost:
从应用程序设置中访问客户端密钥(Azure AD身份验证).NET 6应用程序

Deployed App:

从应用程序设置中访问客户端密钥(Azure AD身份验证).NET 6应用程序

huangapple
  • 本文由 发表于 2023年6月1日 23:20:48
  • 转载请务必保留本文链接:https://go.coder-hub.com/76383437.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定