以下是一个使用ASP.NET Core 2进行授权和注销的示例:
首先,确保你的项目引用了以下NuGet包:
在Startup.cs文件的ConfigureServices方法中,添加以下代码来配置授权和注销:
public void ConfigureServices(IServiceCollection services)
{
//...
services.AddAuthentication(options =>
{
options.DefaultAuthenticateScheme = CookieAuthenticationDefaults.AuthenticationScheme;
options.DefaultSignInScheme = CookieAuthenticationDefaults.AuthenticationScheme;
options.DefaultChallengeScheme = OpenIdConnectDefaults.AuthenticationScheme;
})
.AddCookie()
.AddOpenIdConnect(options =>
{
options.ClientId = "your-client-id";
options.ClientSecret = "your-client-secret";
options.Authority = "https://your-identity-server";
options.ResponseType = "code";
options.Scope.Add("openid");
options.Scope.Add("profile");
options.SaveTokens = true;
});
//...
}
在Startup.cs文件的Configure方法中,添加以下代码来启用授权:
public void Configure(IApplicationBuilder app, IHostingEnvironment env)
{
//...
app.UseAuthentication();
//...
}
在控制器中,你可以使用[Authorize]
特性来标记需要授权才能访问的操作。例如:
[Authorize]
public class HomeController : Controller
{
//...
}
要进行注销操作,你可以在控制器中添加一个注销的动作方法。例如:
public class AccountController : Controller
{
[HttpPost]
[ValidateAntiForgeryToken]
public IActionResult Logout()
{
return SignOut(CookieAuthenticationDefaults.AuthenticationScheme, OpenIdConnectDefaults.AuthenticationScheme);
}
}
在视图中,你可以使用Logout
来创建注销的链接。
希望这个示例能够帮助你实现ASP.NET Core 2的授权注销功能。