运行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.
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:
- Open Visual Studio and go to
Tools>Extensions and Updatesfrom the top menu. - In the left pane, select
Updates>Product Updates. - Look for the NuGet Package Manager update, click
Update, then restart Visual Studio to apply changes. - If you don't see an update here, you can also manually download the latest NuGet CLI tool and replace your existing
nuget.exefile.
- Open Visual Studio and go to
Using NuGet CLI directly:
- Grab the latest version of the NuGet CLI tool.
- Replace your current
nuget.exewith the new one, then runnuget update -selfin 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.
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(replacexxxxwith 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(); } } }
6. Add Login/Logout Links
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

