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

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

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

问题

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

appsettings.json

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

Program.cs

services.AddAuthentication(OpenIdConnectDefaults.AuthenticationScheme)
    .AddMicrosoftIdentityWebApp(Configuration)
    .EnableTokenAcquisitionToCallDownstreamApi()
    .AddInMemoryTokenCaches()
    .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

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

Program.cs

services.AddAuthentication(OpenIdConnectDefaults.AuthenticationScheme)
                            .AddMicrosoftIdentityWebApp(Configuration)
                            .EnableTokenAcquisitionToCallDownstreamApi()
                            .AddInMemoryTokenCaches()
                            .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:

{
  "AzureAd": {
    "Instance": "https://login.microsoftonline.com/",
    "Domain": "*****.onmicrosoft.com",
    "TenantId": "**********",
    "ClientId": "**********",
    "CallbackPath": "/signin-oidc",
    "ClientSecret": ""
  },
  "Logging": {
    "LogLevel": {
      "Default": "Information",
      "Microsoft.AspNetCore": "Warning"
    }
  },
  "AllowedHosts": "*",
  "KeyVault": {
    "URI": "https://HarshuKV8June.vault.azure.net/"
  }
}

My .csproj file:

<Project Sdk="Microsoft.NET.Sdk.Web">

  <PropertyGroup>
    <TargetFramework>net6.0</TargetFramework>
    <Nullable>enable</Nullable>
    <ImplicitUsings>enable</ImplicitUsings>
    <UserSecretsId>aspnet-WebApplication2-f96bb6f0-eef0-4193-a9b3-6a006134f076</UserSecretsId>
  </PropertyGroup>

  <ItemGroup>
    <PackageReference Include="Microsoft.AspNetCore.Authentication.JwtBearer" Version="6.0.16" NoWarn="NU1605" />
    <PackageReference Include="Microsoft.AspNetCore.Authentication.OpenIdConnect" Version="6.0.16" NoWarn="NU1605" />
    <PackageReference Include="Microsoft.Identity.Web" Version="2.7.0" />
    <PackageReference Include="Microsoft.Identity.Web.UI" Version="2.7.0" />
  </ItemGroup>
</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.

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

OR

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

My Program.cs file:

using Azure.Identity;
using Azure.Security.KeyVault.Secrets;
using Microsoft.AspNetCore.Authentication;
using Microsoft.AspNetCore.Authentication.OpenIdConnect;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc.Authorization;
using Microsoft.Extensions.Configuration;
using Microsoft.Identity.Web;
using Microsoft.Identity.Web.UI;
using System.ComponentModel;

var builder = WebApplication.CreateBuilder(args);

var KV = builder.Configuration["KeyVault:URI"];
var cred = new DefaultAzureCredential();
var secretClient = new SecretClient(new Uri(KV), cred);

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

//Setting the ClientSecret to the key in `appsettings.json` file
builder.Configuration["AzureAD:ClientSecret"] = ClientSecret;

//Retrieving the value from `appsettings.json` file
var setClientSecret = builder.Configuration.GetValue<string>("AzureAD:ClientSecret");

// Add services to the container.
builder.Services.AddAuthentication(OpenIdConnectDefaults.AuthenticationScheme)
    .AddMicrosoftIdentityWebApp(builder.Configuration.GetSection("AzureAd"));

builder.Services.AddAuthorization(options =>
{   
    options.FallbackPolicy = options.DefaultPolicy;
});
builder.Services.AddRazorPages()
    .AddMicrosoftIdentityUI();

var app = builder.Build();

if (!app.Environment.IsDevelopment())
{
    app.UseExceptionHandler("/Error");  
    app.UseHsts();
}

app.UseHttpsRedirection();
app.UseStaticFiles();
app.UseRouting();
app.UseAuthentication();
app.UseAuthorization();
app.MapRazorPages();
app.MapControllers();
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:

{
  &quot;AzureAd&quot;: {
    &quot;Instance&quot;: &quot;https://login.microsoftonline.com/&quot;,
    &quot;Domain&quot;: &quot;*****.onmicrosoft.com&quot;,
    &quot;TenantId&quot;: &quot;**********&quot;,
    &quot;ClientId&quot;: &quot;**********&quot;,
    &quot;CallbackPath&quot;: &quot;/signin-oidc&quot;,
    &quot;ClientSecret&quot;: &quot;&quot;
  },
  &quot;Logging&quot;: {
    &quot;LogLevel&quot;: {
      &quot;Default&quot;: &quot;Information&quot;,
      &quot;Microsoft.AspNetCore&quot;: &quot;Warning&quot;
    }
  },
  &quot;AllowedHosts&quot;: &quot;*&quot;,
  &quot;KeyVault&quot;: {
    &quot;URI&quot;: &quot;https://HarshuKV8June.vault.azure.net/&quot;
  }
}

My .csproj file:

&lt;Project Sdk=&quot;Microsoft.NET.Sdk.Web&quot;&gt;

  &lt;PropertyGroup&gt;
    &lt;TargetFramework&gt;net6.0&lt;/TargetFramework&gt;
    &lt;Nullable&gt;enable&lt;/Nullable&gt;
    &lt;ImplicitUsings&gt;enable&lt;/ImplicitUsings&gt;
    &lt;UserSecretsId&gt;aspnet-WebApplication2-f96bb6f0-eef0-4193-a9b3-6a006134f076&lt;/UserSecretsId&gt;
  &lt;/PropertyGroup&gt;

  &lt;ItemGroup&gt;
    &lt;PackageReference Include=&quot;Microsoft.AspNetCore.Authentication.JwtBearer&quot; Version=&quot;6.0.16&quot; NoWarn=&quot;NU1605&quot; /&gt;
    &lt;PackageReference Include=&quot;Microsoft.AspNetCore.Authentication.OpenIdConnect&quot; Version=&quot;6.0.16&quot; NoWarn=&quot;NU1605&quot; /&gt;
    &lt;PackageReference Include=&quot;Microsoft.Identity.Web&quot; Version=&quot;2.7.0&quot; /&gt;
    &lt;PackageReference Include=&quot;Microsoft.Identity.Web.UI&quot; Version=&quot;2.7.0&quot; /&gt;
  &lt;/ItemGroup&gt;
&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.

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

OR

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

My Program.cs file:

using Azure.Identity;
using Azure.Security.KeyVault.Secrets;
using Microsoft.AspNetCore.Authentication;
using Microsoft.AspNetCore.Authentication.OpenIdConnect;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc.Authorization;
using Microsoft.Extensions.Configuration;
using Microsoft.Identity.Web;
using Microsoft.Identity.Web.UI;
using System.ComponentModel;

var builder = WebApplication.CreateBuilder(args);


var KV = builder.Configuration[&quot;KeyVault:URI&quot;];
var cred = new DefaultAzureCredential();
var secretClient = new SecretClient(new Uri(KV), cred);

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

//Setting the ClientSecret to the key in `appsettings.json` file
builder.Configuration[&quot;AzureAD:ClientSecret&quot;] = ClientSecret;

//Retrieving the value from `appsettings.json` file
var setClientSecret = builder.Configuration.GetValue&lt;string&gt;(&quot;AzureAD:ClientSecret&quot;);

// Add services to the container.
builder.Services.AddAuthentication(OpenIdConnectDefaults.AuthenticationScheme)
    .AddMicrosoftIdentityWebApp(builder.Configuration.GetSection(&quot;AzureAd&quot;));

builder.Services.AddAuthorization(options =&gt;
{   
    options.FallbackPolicy = options.DefaultPolicy;
});
builder.Services.AddRazorPages()
    .AddMicrosoftIdentityUI();

var app = builder.Build();

if (!app.Environment.IsDevelopment())
{
    app.UseExceptionHandler(&quot;/Error&quot;);  
    app.UseHsts();
}

app.UseHttpsRedirection();
app.UseStaticFiles();
app.UseRouting();
app.UseAuthentication();
app.UseAuthorization();
app.MapRazorPages();
app.MapControllers();
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:

确定