.NET Core Web 应用程序与 Azure AD 显示 404

问题描述 投票:0回答:1

我正在按照此 Microsoft 教程将 Web 应用程序与 azure 广告集成以进行登录/注销。
https://learn.microsoft.com/en-us/entra/identity-platform/tutorial-web-app-dotnet-call-api?tabs=visual-studio%2Cdotnet6

我创建了一个示例 .net core razor 页面 Web 应用程序,并使用 https localhost:7100 运行该 Web 应用程序,并且运行良好。
然后我按照教程中给出的方式修改了应用程序。删除了虚拟代码并添加了示例代码、设置客户端 ID、租户 ID、认证密钥等。我已遵循文档中给出的所有步骤。

问题是当我以 https 方式运行 Web 应用程序时,它给了我 404 错误。

asp.net-core azure-active-directory adal msal
1个回答
0
投票

让我们创建一个新的 .net core Web 应用程序,请不要忘记选择

Microsoft Identity platform
作为身份验证类型。

然后我们需要按照教程将

builder.Services.AddAuthentication
替换为下面的代码。

IEnumerable<string>? initialScopes = builder.Configuration["DownstreamApi:Scopes"]?.Split(' ');
builder.Services.AddMicrosoftIdentityWebAppAuthentication(builder.Configuration, "AzureAd")
    .EnableTokenAcquisitionToCallDownstreamApi(initialScopes)
        .AddDownstreamApi("DownstreamApi", builder.Configuration.GetSection("DownstreamApi"))
        .AddInMemoryTokenCaches();

这会在

AddDownstreamApi
上带来构建错误,让我们安装
Microsoft.Identity.Web.DownstreamApi" Version="2.15.2" />
nuget 包来解决它,顺便说一下,我们也可以升级其他包。打开csproj文件(在vs中双击项目名称),现在的内容应该是这样的。修改文件并重建应用程序以解决错误。

<ItemGroup>
  <PackageReference Include="Microsoft.AspNetCore.Authentication.JwtBearer" Version="7.0.13" NoWarn="NU1605" />
  <PackageReference Include="Microsoft.AspNetCore.Authentication.OpenIdConnect" Version="7.0.13" NoWarn="NU1605" />
  <PackageReference Include="Microsoft.Identity.Web" Version="2.15.2" />
  <PackageReference Include="Microsoft.Identity.Web.UI" Version="2.15.2" />
    <PackageReference Include="Microsoft.Identity.Web.DownstreamApi" Version="2.15.2" />
</ItemGroup>

修改Index.cshtml和Index.cshtml.cs,添加API调用代码和显示API响应的html内容。

[AuthorizeForScopes(ScopeKeySection = "DownstreamApi:Scopes")]
public class IndexModel : PageModel
{
    private readonly ILogger<IndexModel> _logger;
    private readonly IDownstreamApi _downstreamWebApi;

    public IndexModel(ILogger<IndexModel> logger,
                    IDownstreamApi downstreamWebApi)
    {
        _logger = logger;
        _downstreamWebApi = downstreamWebApi;
    }

    public async Task OnGet()
    {
        using var response = await _downstreamWebApi.CallApiForUserAsync("DownstreamApi").ConfigureAwait(false);
        if (response.StatusCode == System.Net.HttpStatusCode.OK)
        {
            var apiResult = await response.Content.ReadFromJsonAsync<JsonDocument>().ConfigureAwait(false);
            ViewData["ApiResult"] = JsonSerializer.Serialize(apiResult, new JsonSerializerOptions { WriteIndented = true });
        }
        else
        {
            var error = await response.Content.ReadAsStringAsync().ConfigureAwait(false);
            throw new HttpRequestException($"Invalid status code in the HttpResponseMessage: {response.StatusCode}: {error}");
        }
    }
}

<p><pre><code class="language-js">@ViewData["ApiResult"]</code></pre></p>

然后我们需要修改appsettings.json文件来完成配置。在这里,我们需要一个已配置重定向 url 并创建客户端密钥的 Azure AD 应用程序。在 Azure AD -> 您的注册应用程序 -> 身份验证刀片中,我们应该将

https://localhost/signin-oidc
添加到
Web
平台。在
Certificates & secrets
刀片中,我们应该创建客户端密钥,然后 appsettings.json 应修改为

"AzureAd": {
  "Instance": "https://login.microsoftonline.com/",
  "Domain": "tenant_id",
  "TenantId": "tenant_id",
  "ClientId": "client_id",
  "ClientSecret": "client_secret",
  "CallbackPath": "/signin-oidc", 
  "SignedOutCallbackPath ": "/signout-callback-oidc"
},
"DownstreamApi": {
  "BaseUrl": "https://graph.microsoft.com/v1.0",
  "Scopes": "User.Read"
},

然后运行您的应用程序,系统会要求您登录,登录后进入主页下方。

© www.soinside.com 2019 - 2024. All rights reserved.