ASP.NET Core OAuth 和基本身份验证是两种常用的身份验证方式,可以通过以下步骤进行配置和使用。
首先,在 ASP.NET Core 项目中安装相关的 NuGet 包,可使用以下命令安装:
dotnet add package Microsoft.AspNetCore.Authentication
在 Startup.cs
文件中的 ConfigureServices
方法中添加身份验证服务的配置:
using Microsoft.AspNetCore.Authentication.Cookies;
using Microsoft.AspNetCore.Authentication.OAuth;
public void ConfigureServices(IServiceCollection services)
{
// 添加 Cookie 身份验证服务
services.AddAuthentication(CookieAuthenticationDefaults.AuthenticationScheme)
.AddCookie();
// 添加 OAuth 身份验证服务
services.AddAuthentication(options =>
{
options.DefaultScheme = "YourOAuthScheme";
})
.AddOAuth("YourOAuthScheme", options =>
{
options.ClientId = "YourClientId";
options.ClientSecret = "YourClientSecret";
options.CallbackPath = "/signin-YourOAuthScheme";
// 根据 OAuth 服务商的要求进行配置
options.AuthorizationEndpoint = "https://example.com/oauth/authorize";
options.TokenEndpoint = "https://example.com/oauth/token";
options.UserInformationEndpoint = "https://example.com/api/userinfo";
// 配置回调处理程序
options.Events = new OAuthEvents
{
OnCreatingTicket = async context =>
{
// 在这里可以获取用户信息,并将其存储在身份验证票证中
}
};
});
}
在需要进行身份验证的控制器或页面中添加 [Authorize]
属性来限制访问:
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
[Authorize]
public class HomeController : Controller
{
// 控制器的方法
}
创建登录和注销的处理程序,例如在控制器中添加以下方法:
using Microsoft.AspNetCore.Authentication;
public class AccountController : Controller
{
public IActionResult Login(string returnUrl = "/")
{
// 重定向到 OAuth 服务商的登录页面
return Challenge(new AuthenticationProperties
{
RedirectUri = returnUrl
});
}
public IActionResult Logout()
{
// 注销并重定向到指定页面
return SignOut();
}
}
在视图中添加登录和注销的链接,例如:
登录
注销
通过以上步骤,你就可以在 ASP.NET Core 项目中使用 OAuth 和基本身份验证了。根据你选择的 OAuth 服务商的要求,你需要针对相应的服务商进行配置。在 OnCreatingTicket
事件中,你可以获取用户信息并将其存储在身份验证票证中。