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();
相关推荐
这孩子叫逆8 分钟前
Spring Boot项目的创建与使用
java·spring boot·后端
一丝晨光1 小时前
Java、PHP、ASP、JSP、Kotlin、.NET、Go
java·kotlin·go·php·.net·jsp·asp
coderWangbuer1 小时前
基于springboot的高校招生系统(含源码+sql+视频导入教程+文档+PPT)
spring boot·后端·sql
攸攸太上1 小时前
JMeter学习
java·后端·学习·jmeter·微服务
Kenny.志1 小时前
2、Spring Boot 3.x 集成 Feign
java·spring boot·后端
sky丶Mamba2 小时前
Spring Boot中获取application.yml中属性的几种方式
java·spring boot·后端
yufei-coder2 小时前
C#基础语法
开发语言·c#·.net
千里码aicood3 小时前
【2025】springboot教学评价管理系统(源码+文档+调试+答疑)
java·spring boot·后端·教学管理系统
程序员-珍3 小时前
使用openapi生成前端请求文件报错 ‘Token “Integer“ does not exist.‘
java·前端·spring boot·后端·restful·个人开发
Mudrock__3 小时前
前后端传输文件(图片)
vue·.net