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

2024-02-21 05:12

本文主要是介绍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) 快速开发简单登陆和登出功能的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!



http://www.chinasem.cn/article/730667

相关文章

Debian 13升级后网络转发等功能异常怎么办? 并非错误而是管理机制变更

《Debian13升级后网络转发等功能异常怎么办?并非错误而是管理机制变更》很多朋友反馈,更新到Debian13后网络转发等功能异常,这并非BUG而是Debian13Trixie调整... 日前 Debian 13 Trixie 发布后已经有众多网友升级到新版本,只不过升级后发现某些功能存在异常,例如网络转

Python 基于http.server模块实现简单http服务的代码举例

《Python基于http.server模块实现简单http服务的代码举例》Pythonhttp.server模块通过继承BaseHTTPRequestHandler处理HTTP请求,使用Threa... 目录测试环境代码实现相关介绍模块简介类及相关函数简介参考链接测试环境win11专业版python

Python实战之SEO优化自动化工具开发指南

《Python实战之SEO优化自动化工具开发指南》在数字化营销时代,搜索引擎优化(SEO)已成为网站获取流量的重要手段,本文将带您使用Python开发一套完整的SEO自动化工具,需要的可以了解下... 目录前言项目概述技术栈选择核心模块实现1. 关键词研究模块2. 网站技术seo检测模块3. 内容优化分析模

基于Java开发一个极简版敏感词检测工具

《基于Java开发一个极简版敏感词检测工具》这篇文章主要为大家详细介绍了如何基于Java开发一个极简版敏感词检测工具,文中的示例代码简洁易懂,感兴趣的小伙伴可以跟随小编一起学习一下... 目录你是否还在为敏感词检测头疼一、极简版Java敏感词检测工具的3大核心优势1.1 优势1:DFA算法驱动,效率提升10

基于Java和FFmpeg实现视频压缩和剪辑功能

《基于Java和FFmpeg实现视频压缩和剪辑功能》在视频处理开发中,压缩和剪辑是常见的需求,本文将介绍如何使用Java结合FFmpeg实现视频压缩和剪辑功能,同时去除数据库操作,仅专注于视频处理,需... 目录引言1. 环境准备1.1 项目依赖1.2 安装 FFmpeg2. 视频压缩功能实现2.1 主要功

使用Python实现无损放大图片功能

《使用Python实现无损放大图片功能》本文介绍了如何使用Python的Pillow库进行无损图片放大,区分了JPEG和PNG格式在放大过程中的特点,并给出了示例代码,JPEG格式可能受压缩影响,需先... 目录一、什么是无损放大?二、实现方法步骤1:读取图片步骤2:无损放大图片步骤3:保存图片三、示php

Python多线程实现大文件快速下载的代码实现

《Python多线程实现大文件快速下载的代码实现》在互联网时代,文件下载是日常操作之一,尤其是大文件,然而,网络条件不稳定或带宽有限时,下载速度会变得很慢,本文将介绍如何使用Python实现多线程下载... 目录引言一、多线程下载原理二、python实现多线程下载代码说明:三、实战案例四、注意事项五、总结引

深度解析Python yfinance的核心功能和高级用法

《深度解析Pythonyfinance的核心功能和高级用法》yfinance是一个功能强大且易于使用的Python库,用于从YahooFinance获取金融数据,本教程将深入探讨yfinance的核... 目录yfinance 深度解析教程 (python)1. 简介与安装1.1 什么是 yfinance?

Python脚本轻松实现检测麦克风功能

《Python脚本轻松实现检测麦克风功能》在进行音频处理或开发需要使用麦克风的应用程序时,确保麦克风功能正常是非常重要的,本文将介绍一个简单的Python脚本,能够帮助我们检测本地麦克风的功能,需要的... 目录轻松检测麦克风功能脚本介绍一、python环境准备二、代码解析三、使用方法四、知识扩展轻松检测麦

C#使用Spire.XLS快速生成多表格Excel文件

《C#使用Spire.XLS快速生成多表格Excel文件》在日常开发中,我们经常需要将业务数据导出为结构清晰的Excel文件,本文将手把手教你使用Spire.XLS这个强大的.NET组件,只需几行C#... 目录一、Spire.XLS核心优势清单1.1 性能碾压:从3秒到0.5秒的质变1.2 批量操作的优雅