azure - 从应用程序设置 .net 6 应用程序访问客户端 key (Azure AD 身份验证)

标签 azure azure-active-directory azure-keyvault appsettings azure-appservice

我有一个 .net 6 应用程序,使用 azure ad 进行身份验证。详情如下:

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/)"

程序.cs

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

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

我希望从 keyvault 读取 ClientSecret 值,并从 appsettings json 读取其余值。我怎样才能做到这一点?如果我在应用程序设置中对客户端 key 进行硬编码,它就可以工作。我很难理解为什么这不允许登录?

还添加了 RedirectURI。

应用服务配置快照

enter image description here

最佳答案

即使没有客户端 key ,我也能够进行身份验证和登录。

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

我已在 appsettings.json 文件中设置了 key ClientSecret,但没有任何值。

我的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/"
  }
}

我的.csproj文件:

<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>

使用以下代码从 Azure Key Vault 检索客户端 key 。

使用以下任意一行代码从 KeyVault 检索 secret 值。

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

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

我的 Program.cs 文件:

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();

来自 KeyVault 的 ClientSecret 值:

enter image description here

在 AAD 中重定向 URI:

enter image description here

输出:

enter image description here

本地主机: enter image description here

部署的应用程序:

enter image description here

关于azure - 从应用程序设置 .net 6 应用程序访问客户端 key (Azure AD 身份验证),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/76383437/

相关文章:

git - Azure git,将 fork 存储库与主同步

Azure自定义角色: authorize role assignment for a specific set of roles

c# - Azure KeyVault GetSecretAsync.Result.Value 错误处理

Azure 数据工厂 - Web 事件失败,错误代码为 2108

azure - 如果您有 Office 365,可以取消对 Azure Active Directory 的访问吗?

dynamic - azure 上的可插入动态页面

angular - 尝试验证 Azure AD token 时收到错误 "IDX10511: Signature validation failed"

asp.net-mvc - 还有另一种方法可以添加 Azure Active Directory 作为授权方法

Azure Keyvault - "The operation "列表“在此 Key Vault 的访问策略中未启用。”以编程方式创建 KeyVault 时

python - 检索 Azure 服务主体的 object_id