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();
相关推荐
向前看-3 小时前
验证码机制
前端·后端
超爱吃士力架5 小时前
邀请逻辑
java·linux·后端
AskHarries7 小时前
Spring Cloud OpenFeign快速入门demo
spring boot·后端
数据的世界017 小时前
.NET开发人员学习书籍推荐
学习·.net
isolusion8 小时前
Springboot的创建方式
java·spring boot·后端
zjw_rp8 小时前
Spring-AOP
java·后端·spring·spring-aop
TodoCoder9 小时前
【编程思想】CopyOnWrite是如何解决高并发场景中的读写瓶颈?
java·后端·面试
paixiaoxin9 小时前
CV-OCR经典论文解读|An Empirical Study of Scaling Law for OCR/OCR 缩放定律的实证研究
人工智能·深度学习·机器学习·生成对抗网络·计算机视觉·ocr·.net
凌虚9 小时前
Kubernetes APF(API 优先级和公平调度)简介
后端·程序员·kubernetes
机器之心10 小时前
图学习新突破:一个统一框架连接空域和频域
人工智能·后端