You need to enable JavaScript to run this app. ASP.Net Core 2站点能否同时实现MVC与Azure AD B2C Web API?Startup.cs示例
优惠活动
大模型
产品
解决方案
定价
更多

ASP.Net Core 2站点能否同时实现MVC与Azure AD B2C Web API?Startup.cs示例

Absolutely! You can absolutely run both an Azure AD B2C-protected MVC site and a Web API in the same ASP.NET Core 2 application. The trick is setting up two separate authentication schemes—one for MVC (using cookie auth paired with OpenID Connect for B2C login) and another for the API (using JWT Bearer auth for token validation)—then routing requests to use the right scheme based on whether they're hitting MVC views or API endpoints.

Here's a complete, working Startup.cs example tailored for ASP.NET Core 2, plus explanations of how it all fits together:


Full Startup.cs Implementation

using Microsoft.AspNetCore.Authentication;
using Microsoft.AspNetCore.Authentication.Cookies;
using Microsoft.AspNetCore.Authentication.JwtBearer;
using Microsoft.AspNetCore.Authentication.OpenIdConnect;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.IdentityModel.Tokens;

public class Startup
{
    public Startup(IConfiguration configuration)
    {
        Configuration = configuration;
    }

    public IConfiguration Configuration { get; }

    public void ConfigureServices(IServiceCollection services)
    {
        // Pull Azure AD B2C config from appsettings.json
        var b2cSettings = Configuration.GetSection("AzureAdB2C");
        var tenant = b2cSettings["Tenant"];
        var clientId = b2cSettings["ClientId"];
        var clientSecret = b2cSettings["ClientSecret"];
        var signUpSignInPolicy = b2cSettings["SignUpSignInPolicyId"];
        var apiAudience = b2cSettings["ApiAudience"]; // e.g. "https://yourtenant.onmicrosoft.com/api"

        // 1. Configure cookie authentication (for MVC session management)
        services.AddAuthentication(CookieAuthenticationDefaults.AuthenticationScheme)
            .AddCookie(options =>
            {
                options.LoginPath = "/Account/Login";
                options.AccessDeniedPath = "/Account/AccessDenied";
            })
            // 2. Add OpenID Connect (for MVC users to login via Azure AD B2C)
            .AddOpenIdConnect("AzureADB2C", options =>
            {
                options.Authority = $"https://{tenant}.b2clogin.com/tfp/{tenant}/{signUpSignInPolicy}/v2.0/";
                options.ClientId = clientId;
                options.ClientSecret = clientSecret;
                options.ResponseType = "code id_token";
                options.CallbackPath = "/signin-oidc";
                options.SignedOutCallbackPath = "/signout-callback-oidc";
                options.Scope.Add("openid");
                options.Scope.Add("profile");
                options.Scope.Add(apiAudience); // Request permission to call our API
                options.SaveTokens = true; // Store tokens for later API calls from MVC
                options.TokenValidationParameters = new TokenValidationParameters
                {
                    NameClaimType = "name"
                };
            })
            // 3. Add JWT Bearer authentication (for validating API tokens)
            .AddJwtBearer("AzureADB2C-Jwt", options =>
            {
                options.Authority = $"https://{tenant}.b2clogin.com/tfp/{tenant}/{signUpSignInPolicy}/v2.0/";
                options.Audience = apiAudience;
                options.TokenValidationParameters = new TokenValidationParameters
                {
                    ValidateIssuer = true,
                    ValidIssuer = $"https://{tenant}.b2clogin.com/{b2cSettings["TenantId"]}/v2.0/",
                    ValidateAudience = true,
                    ValidateLifetime = true,
                    ValidateIssuerSigningKey = true
                };
            });

        // 4. Define authorization policies (optional but simplifies controller usage)
        services.AddAuthorization(options =>
        {
            options.AddPolicy("MvcAuth", policy =>
                policy.RequireAuthenticatedUser()
                      .AddAuthenticationSchemes(CookieAuthenticationDefaults.AuthenticationScheme));
            
            options.AddPolicy("ApiAuth", policy =>
                policy.RequireAuthenticatedUser()
                      .AddAuthenticationSchemes("AzureADB2C-Jwt"));
        });

        // 5. Enable MVC and API support
        services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_2);
    }

    public void Configure(IApplicationBuilder app, IHostingEnvironment env)
    {
        if (env.IsDevelopment())
        {
            app.UseDeveloperExceptionPage();
        }
        else
        {
            app.UseExceptionHandler("/Home/Error");
            app.UseHsts();
        }

        app.UseHttpsRedirection();
        app.UseStaticFiles();
        app.UseCookiePolicy();

        // Critical: Authentication middleware must run before MVC routing
        app.UseAuthentication();

        app.UseMvc(routes =>
        {
            // MVC route pattern
            routes.MapRoute(
                name: "default",
                template: "{controller=Home}/{action=Index}/{id?}");

            // Separate route for API endpoints
            routes.MapRoute(
                name: "api",
                template: "api/{controller}/{id?}");
        });
    }
}

How to Use in Controllers

MVC Controllers (Protected via Cookie Auth)

You can either use the pre-defined policy or directly specify the authentication scheme:

[Authorize(Policy = "MvcAuth")]
public class HomeController : Controller
{
    public IActionResult Index()
    {
        return View();
    }
}

API Controllers (Protected via JWT Bearer Auth)

For API endpoints, use the API-specific policy or scheme:

[Authorize(Policy = "ApiAuth")]
[Route("api/[controller]")]
[ApiController]
public class ProductsController : ControllerBase
{
    [HttpGet]
    public IActionResult Get()
    {
        return Ok(new[] { "Product 1", "Product 2" });
    }
}

Key Setup Notes

  1. Azure AD B2C App Registration:
    • Configure a Web platform with your MVC redirect URI (e.g., https://localhost:5001/signin-oidc)
    • Configure a Web API platform with your API scope (e.g., https://yourtenant.onmicrosoft.com/api/read) and grant admin consent
  2. Appsettings.json Configuration:
    Make sure your config file includes all required B2C values:
    {
      "AzureAdB2C": {
        "Tenant": "yourtenant.onmicrosoft.com",
        "TenantId": "your-tenant-guid-here",
        "ClientId": "your-app-client-id-here",
        "ClientSecret": "your-app-client-secret-here",
        "SignUpSignInPolicyId": "B2C_1_SignUpSignIn",
        "ApiAudience": "https://yourtenant.onmicrosoft.com/api"
      }
    }
    

内容的提问来源于stack exchange,提问作者Andy Edmonds

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.15 06:50:44