You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

运行Azure B2C示例代码遇NuGet版本错误,求ASP.NET MVC应用安全方案

Hey there! Let's break this problem down into two clear parts: first fixing that NuGet version error, then securing your ASP.NET MVC app with email-based authentication.

第一步:解决NuGet版本过低的错误

The error you're seeing means your current NuGet client is outdated and can't handle the preview package you're trying to install. Here's how to update it:

  • If you're using Visual Studio:

    1. Open Visual Studio and go to Tools > Extensions and Updates from the top menu.
    2. In the left pane, select Updates > Product Updates.
    3. Look for the NuGet Package Manager update, click Update, then restart Visual Studio to apply changes.
    4. If you don't see an update here, you can also manually download the latest NuGet CLI tool and replace your existing nuget.exe file.
  • Using NuGet CLI directly:

    1. Grab the latest version of the NuGet CLI tool.
    2. Replace your current nuget.exe with the new one, then run nuget update -self in your command line to confirm the update.

Pro tip: Instead of using the preview version of Microsoft.Identity.Client, opt for the latest stable release once NuGet is updated—this will avoid potential compatibility hiccups.

第二步:用邮箱保护你的ASP.NET MVC应用

To secure your app with email-based login (using Azure AD B2C, since that's what your original tutorial covers), follow these steps:

1. Set up Azure AD B2C Tenant & User Flow

  • Create an Azure AD B2C tenant in the Azure portal.
  • Create a Sign-up and sign-in user flow, and configure it to allow only email-based authentication (disable username options if you want to restrict to emails).
  • Register your MVC app in the B2C tenant, set the redirect URI to something like https://localhost:xxxx/signin-oidc (replace xxxx with your app's port), and note down the Client ID, Tenant ID, and user flow name (e.g., B2C_1_signup_signin).

2. Update Your App's Configuration

Add these settings to your Web.config file under <appSettings>:

<add key="AzureAdB2C:Instance" value="https://your-tenant-name.b2clogin.com/" />
<add key="AzureAdB2C:ClientId" value="your-client-id-here" />
<add key="AzureAdB2C:CallbackPath" value="/signin-oidc" />
<add key="AzureAdB2C:Domain" value="your-tenant-name.onmicrosoft.com" />
<add key="AzureAdB2C:SignUpSignInPolicyId" value="B2C_1_signup_signin" />

3. Install Required NuGet Packages

Now that NuGet is updated, install these stable packages via the Package Manager Console or NuGet Package Manager:

Install-Package Microsoft.Owin.Security.OpenIdConnect
Install-Package Microsoft.Owin.Security.Cookies
Install-Package Microsoft.Owin.Host.SystemWeb

4. Configure OWIN Middleware

Add a Startup.cs file to your project (if you don't already have one) with this code to set up authentication:

using Microsoft.Owin;
using Owin;
using Microsoft.Owin.Security.Cookies;
using Microsoft.Owin.Security.OpenIdConnect;
using System.Configuration;
using System.IdentityModel.Tokens;

[assembly: OwinStartup(typeof(YourMvcAppName.Startup))]
namespace YourMvcAppName
{
    public class Startup
    {
        public void Configuration(IAppBuilder app)
        {
            app.SetDefaultSignInAsAuthenticationType(CookieAuthenticationDefaults.AuthenticationType);
            app.UseCookieAuthentication(new CookieAuthenticationOptions());

            app.UseOpenIdConnectAuthentication(
                new OpenIdConnectAuthenticationOptions
                {
                    ClientId = ConfigurationManager.AppSettings["AzureAdB2C:ClientId"],
                    Authority = $"{ConfigurationManager.AppSettings["AzureAdB2C:Instance"]}{ConfigurationManager.AppSettings["AzureAdB2C:Domain"]}/{ConfigurationManager.AppSettings["AzureAdB2C:SignUpSignInPolicyId"]}/v2.0/",
                    RedirectUri = ConfigurationManager.AppSettings["AzureAdB2C:CallbackPath"],
                    PostLogoutRedirectUri = "/",
                    Scope = "openid",
                    ResponseType = "id_token",
                    TokenValidationParameters = new TokenValidationParameters
                    {
                        NameClaimType = "name",
                        RoleClaimType = "role"
                    },
                    Notifications = new OpenIdConnectAuthenticationNotifications
                    {
                        AuthenticationFailed = context =>
                        {
                            context.HandleResponse();
                            context.Response.Redirect("/Error?message=" + context.Exception.Message);
                            return System.Threading.Tasks.Task.FromResult(0);
                        }
                    }
                });
        }
    }
}

Replace YourMvcAppName with your actual project namespace.

5. Protect Your Home Page

Add the [Authorize] attribute to your HomeController's Index action to force authentication before accessing the homepage:

using System.Web.Mvc;

namespace YourMvcAppName.Controllers
{
    public class HomeController : Controller
    {
        [Authorize]
        public ActionResult Index()
        {
            return View();
        }
    }
}

Update your layout file (_Layout.cshtml) to include login/logout options:

<div class="navbar-right">
    @if (User.Identity.IsAuthenticated)
    {
        <p class="navbar-text">Hello, @User.Identity.Name!</p>
        @Html.ActionLink("Sign Out", "SignOut", "Account")
    }
    else
    {
        @Html.ActionLink("Sign In", "SignIn", "Account")
    }
</div>

Then create an AccountController to handle sign-in and sign-out:

using System.Web.Mvc;
using Microsoft.Owin.Security;
using Microsoft.Owin.Security.OpenIdConnect;
using Microsoft.Owin.Security.Cookies;

namespace YourMvcAppName.Controllers
{
    public class AccountController : Controller
    {
        public void SignIn()
        {
            if (!Request.IsAuthenticated)
            {
                HttpContext.GetOwinContext().Authentication.Challenge(
                    new AuthenticationProperties { RedirectUri = "/" },
                    OpenIdConnectAuthenticationDefaults.AuthenticationType);
            }
        }

        public void SignOut()
        {
            HttpContext.GetOwinContext().Authentication.SignOut(
                CookieAuthenticationDefaults.AuthenticationType,
                OpenIdConnectAuthenticationDefaults.AuthenticationType);
        }
    }
}

That's it! Now when users try to access your homepage, they'll be redirected to Azure AD B2C's email-based login page, and only authenticated users can view the protected content.

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.28 06:24:09