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();
相关推荐
customer081 小时前
【开源免费】基于SpringBoot+Vue.JS体育馆管理系统(JAVA毕业设计)
java·vue.js·spring boot·后端·开源
计算机-秋大田4 小时前
基于微信小程序的电子竞技信息交流平台设计与实现(LW+源码+讲解)
spring boot·后端·微信小程序·小程序·课程设计
加油,旭杏6 小时前
【go语言】接口
开发语言·后端·golang
谢大旭7 小时前
ASP.NET Core 中间件
后端·中间件·c#
时光追逐者7 小时前
Visual Studio使用GitHub Copilot提高.NET开发工作效率
c#·github·.net·copilot·ai编程·微软技术·visual studio
customer087 小时前
【开源免费】基于SpringBoot+Vue.JS景区民宿预约系统(JAVA毕业设计)
java·vue.js·spring boot·后端·开源
uzong8 小时前
Java函数式接口:代码艺术的诗意绽放
后端
HelloDam9 小时前
基于 mzt-biz-log 实现接口调用日志记录
后端
唐青枫9 小时前
dotnet LINQ 使用简明教程
c#·.net
SomeB1oody9 小时前
【Rust自学】15.6. RefCell与内部可变性:“摆脱”安全性限制
开发语言·后端·rust