.NET 8下使用Azure AD B2C保护Web API遇配置问题求助
Azure AD B2C 集成 ASP.NET Core 8 Web API 认证问题
我正在Azure上搭建包含后端Web API和前端WebApp的新项目,已在AD B2C下完成两个应用注册(分别对应Web API和WebApp)。
在执行身份验证库初始化步骤时,发现新建的Asp.NET Core Web API项目(.NET版本8.0.200)没有Startup.cs文件,手动创建并粘贴ConfigureServices()代码后出现报错,导致进度卡住。
更新1:采用@AsleshaKantamsetti建议的代码后,所有端点返回500状态码。
更新2:修正appsettings.json中的配置节名称错误后,仍出现401未授权错误。
相关代码与配置
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<WeatherForecastController> _logger; public WeatherForecastController(ILogger<WeatherForecastController> logger) { _logger = logger; } [HttpGet(Name = "GetWeatherForecast")] public IEnumerable<WeatherForecast> 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://<mydomain>.b2clogin.com/", "Domain": "<mydomain>.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": "*" }
恳请微软团队或有相关经验的人士提供解决方案。
内容的提问来源于stack exchange,提问作者Franva
相关产品推荐
相关产品推荐

