Я следовал этому официальному документу, чтобы создать 2 зарегистрированных приложения в AD B2C, одно для WebAPI и один для WebApp.
Затем, когда я перешел к шагу 3: Запуск библиотеки аутентификации
, я обнаружил, что Startup.cs отсутствует во вновь созданном проекте Asp.NET Core WebAPI. Даже я вручную создал Startup.cs и вставил в ConfigurationServices(), он выдает ошибки. Итак, я застрял здесь.

Моя версия .NET — 8.0.200.
Есть предложения от команды Microsoft или от тех, у кого была такая же проблема?< /p>
Обновление 1
Я использовал код, предложенный @AsleshaKantamsetti, а затем все мои конечные точки начинают выходить из строя с кодом состояния 500

Обновление 2
Я только что обнаружил, что предоставил неверную информацию. имя раздела в appsettings.json, затем я исправил имя, но ошибка 401 по-прежнему выдается.
[img]https://i. stack.imgur.com/QMxZ2.png[/img]
Вот Program.cs
using Microsoft.AspNetCore.Authentication.JwtBearer;
using Microsoft.Identity.Web;
using Microsoft.OpenApi.Models;
using System.Security.Claims;
var builder = WebApplication.CreateBuilder(args);
// Add services to the container.
builder.Services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme)
.AddMicrosoftIdentityWebApi(options =>
{
builder.Configuration.Bind("AzureAd", options);
options.TokenValidationParameters.NameClaimType = ClaimTypes.Name;
},
options =>
{
builder.Configuration.Bind("AzureAd", options);
}
);
//builder.Services.AddMicrosoftIdentityWebApiAuthentication(builder.Configuration.GetSection("AzureAd"));
// End of the Microsoft Identity platform block
// builder.Services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme)
// .AddMicrosoftIdentityWebApi(builder.Configuration.GetSection("AzureAd"));
builder.Services.AddControllers();
// Learn more about configuring Swagger/OpenAPI at https://aka.ms/aspnetcore/swashbuckle
builder.Services.AddEndpointsApiExplorer();
builder.Services.AddSwaggerGen(c => {
c.SwaggerDoc("v1", new Microsoft.OpenApi.Models.OpenApiInfo
{
Title = "JWTToken_Auth_API",
Version = " v1"
});
c.AddSecurityDefinition("Bearer", new Microsoft.OpenApi.Models.OpenApiSecurityScheme()
{
Name = "Authorization",
Type = Microsoft.OpenApi.Models.SecuritySchemeType.ApiKey,
Scheme = "Bearer",
BearerFormat = "JWT",
In = Microsoft.OpenApi.Models.ParameterLocation.Header,
Description = "Wahaha"
});
c.AddSecurityRequirement(new OpenApiSecurityRequirement {
{
new OpenApiSecurityScheme {
Reference = new OpenApiReference {
Type = ReferenceType.SecurityScheme,
Id = "Bearer"
}
},
new string[] {}
}
});
});
var app = builder.Build();
// Configure the HTTP request pipeline.
if (app.Environment.IsDevelopment())
{
app.UseSwagger();
app.UseSwaggerUI();
}
app.UseHttpsRedirection();
app.UseAuthentication();
app.UseAuthorization();
app.MapControllers();
app.Run();
WeatherForecastController.cs
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Identity.Web.Resource;
namespace MyBackend.Controllers
{
[Authorize]
[ApiController]
[Route("[controller]")]
[RequiredScope(RequiredScopesConfigurationKey = "AzureAd:Scopes")]
public class WeatherForecastController : ControllerBase
{
private static readonly string[] Summaries = new[]
{
"Freezing", "Bracing", "Chilly", "Cool", "Mild", "Warm", "Balmy", "Hot", "Sweltering", "Scorching"
};
private readonly ILogger _logger;
public WeatherForecastController(ILogger logger)
{
_logger = logger;
}
[HttpGet(Name = "GetWeatherForecast")]
public IEnumerable Get()
{
return Enumerable.Range(1, 5).Select(index => new WeatherForecast
{
Date = DateOnly.FromDateTime(DateTime.Now.AddDays(index)),
TemperatureC = Random.Shared.Next(-20, 55),
Summary = Summaries[Random.Shared.Next(Summaries.Length)]
})
.ToArray();
}
}
}
appsettings.json и его версия разработки совпадают:
{
"AzureAd": {
"Instance": "https://.b2clogin.com/",
"Domain": ".onmicrosoft.com",
"TenantId": "...",
"ClientId": "...",
"CallbackPath": "/signin-oidc",
"Scopes": ".default",
"SignUpSignInPolicyId": "B2C_1_susi",
"SignedOutCallbackPath": "/signout/B2C_1_susi",
"ResetPasswordPolicyId": "b2c_1_reset",
"EditProfilePolicyId": "b2c_1_edit_profile",
"EnablePiiLogging": true
},
"Logging": {
"LogLevel": {
"Default": "Information",
"Microsoft.AspNetCore": "Warning"
}
},
"AllowedHosts": "*"
}
Подробнее здесь: https://stackoverflow.com/questions/781 ... ut-of-date
Мобильная версия