本文主要是介绍ASP.NET Core 6 (.NET 6) 快速开发简单登陆和登出功能,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!
ASP.NET Core 6中的简单登录和登出功能,需要使用身份验证和授权中间件实现,
1、添加引用 Microsoft.AspNetCore.Authentication.Cookies
使用Visual Studio 2022或更高版本开发工具,创建一个ASP.NET Core 6 (.NET 6) 项目,项目添加引用 Microsoft.AspNetCore.Authentication.Cookies
,引用方法可以参考:
1)使用Nuget界面管理器
搜索 "Microsoft.AspNetCore.Authentication.Cookies" 在列表中分别找到它,点击"安装"
2)使用Package Manager命令安装
PM> Install-Package Microsoft.AspNetCore.Authentication.Cookies
3)使用.NET CLI命令安装
> dotnet add package Microsoft.AspNetCore.Authentication.Cookies
2、项目代码
项目中Program.cs的代码如下:
using Microsoft.AspNetCore.Authentication;
using Microsoft.AspNetCore.Authentication.Cookies;
using SpiderContent.Data;
using SpiderContent.Utils;
using System.Security.Claims;
using System.Security.Principal;Dictionary<string, string> _accounts = new Dictionary<string, string>();
async Task RenderHomePageAsync(HttpContext context)
{if (context?.User?.Identity?.IsAuthenticated == true){await context.Response.WriteAsync(@"<html><head><title>Index</title></head><body>" +$"<h3>Welcome {context.User.Identity.Name}</h3>" +@"<a href='Account/Logout'>登出</a></body></html>");}else{await context.ChallengeAsync();}
}async Task SignInAsync(HttpContext context)
{if (string.Compare(context.Request.Method, "GET") == 0){await RenderLoginPageAsync(context, null, null, null);}else{var userName = context.Request.Form["username"];var password = context.Request.Form["password"];if (_accounts.TryGetValue(userName, out var pwd) && pwd == password){var principal = new ClaimsPrincipal(new ClaimsIdentity(new[] { new Claim(ClaimTypes.Name, userName) },CookieAuthenticationDefaults.AuthenticationScheme));await context.SignInAsync(principal);context.Response.Redirect("/");}else{await RenderLoginPageAsync(context, userName, password, "用户名或密码错误!");}}
}
async Task SignOutAsync(HttpContext context)
{await context.SignOutAsync();context.Response.Redirect("/");
}
static Task RenderLoginPageAsync(HttpContext context, string userName, string password, string errorMessage)
{context.Response.ContentType = "text/html";return context.Response.WriteAsync(@"<html><head><title>Login</title></head><body><form method='post'>" +$"<input type='text' name='username' placeholder='用户名' value ='{userName}'/>" +$"<input type='password' name='password' placeholder='密码' value ='{password}'/> " +@"<input type='submit' value='登陆' /></form>" +$"<p style='color:red'>{errorMessage}</p>" +@"</body></html>");
}var builder = WebApplication.CreateBuilder(args);// Add services to the container.builder.Services.AddAuthentication(options => options.DefaultScheme = CookieAuthenticationDefaults.AuthenticationScheme).AddCookie(CookieAuthenticationDefaults.AuthenticationScheme,config=> {config.Cookie.HttpOnly = true;//options.Cookie.SecurePolicy = CookieSecurePolicy.Always;config.Cookie.SameSite = SameSiteMode.Lax;config.Cookie.Name = CookieAuthenticationDefaults.AuthenticationScheme;config.LoginPath = "/Account/Login";});
builder.Services.AddRazorPages();var app = builder.Build();
_accounts.Add("admin", "admin");
_accounts.Add("guest", "guest");
// Configure the HTTP request pipeline.
if (!app.Environment.IsDevelopment())
{app.UseExceptionHandler("/Error");
}
app.UseStaticFiles();app.UseRouting();app.UseAuthentication();app.MapRazorPages();
app.MapControllers();
app.UseEndpoints(endpoints => {endpoints.Map(pattern: "/", RenderHomePageAsync);endpoints.Map("Account/Login", SignInAsync);endpoints.Map("Account/Logout", SignOutAsync);
});
app.Run();
这篇关于ASP.NET Core 6 (.NET 6) 快速开发简单登陆和登出功能的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!