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();

相关推荐

  1. ASP.NET Core 6 (.NET 6) 快速开发简单登陆功能

    2024-02-21 12:04:03       23 阅读
  2. AuthController用户后台登录/

    2024-02-21 12:04:03       17 阅读
  3. .net core 6 集成使用 mongodb

    2024-02-21 12:04:03       36 阅读

最近更新

  1. TCP协议是安全的吗?

    2024-02-21 12:04:03       18 阅读
  2. 阿里云服务器执行yum,一直下载docker-ce-stable失败

    2024-02-21 12:04:03       19 阅读
  3. 【Python教程】压缩PDF文件大小

    2024-02-21 12:04:03       18 阅读
  4. 通过文章id递归查询所有评论(xml)

    2024-02-21 12:04:03       20 阅读

热门阅读

  1. ARP攻击原理

    2024-02-21 12:04:03       27 阅读
  2. MYSQL 根据条件假删除多余的重复数据

    2024-02-21 12:04:03       29 阅读
  3. 面试浏览器框架八股文十问十答第三期

    2024-02-21 12:04:03       32 阅读
  4. package.json文件详解

    2024-02-21 12:04:03       36 阅读
  5. 纯css实现文字左右循环滚动播放效果

    2024-02-21 12:04:03       28 阅读
  6. 有哪几种行为会导致服务器被入侵

    2024-02-21 12:04:03       28 阅读
  7. 【Spring Boot Bean 注入详解】

    2024-02-21 12:04:03       25 阅读
  8. 12.27 校招 实习 内推 面经

    2024-02-21 12:04:03       36 阅读
  9. 编程笔记 Golang基础 011 控制台输入与输出

    2024-02-21 12:04:03       27 阅读
  10. 浙大版C语言题目集-函数题6

    2024-02-21 12:04:03       31 阅读
  11. uniapp 放大中间图标

    2024-02-21 12:04:03       33 阅读
  12. SpringBoot整理-Actuator

    2024-02-21 12:04:03       30 阅读