![]()
using System;
using System.Collections.Generic;
using System.Security.Claims;
using System.Security.Principal;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Authentication;
using Microsoft.AspNetCore.Authentication.Cookies;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Http;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;
namespace ConsoleApp2
{
class Program
{
private static readonly Dictionary<string, string> Accounts = new Dictionary<string, string>
{
{"Admin", "123"}, {"UserA", "123"}, {"UserB", "123"}
};
public static void Main(string[] args)
{
Host.CreateDefaultBuilder()
.ConfigureWebHostDefaults(builder => builder
.ConfigureServices(collection => collection
.AddRouting()
.AddAuthentication(options => //注册认证中间件,cook验证权限
options.DefaultScheme = CookieAuthenticationDefaults.AuthenticationScheme)
.AddCookie())
.Configure(app => app
.UseAuthentication() //使用权限
.UseRouting() //使用路由
.UseEndpoints(endpoints =>
{
endpoints.Map("/", RenderHomePageAsync); //委托和路由映射关系,没有登陆到首页
endpoints.Map("Account/Login", SignInAsync); //委托和路由映射关系,登陆,默认路径
endpoints.Map("Account/Logout", SignOutAsync); //委托和路由映射关系,退出
})))
.Build()
.Run();
}
public static async Task RenderHomePageAsync(HttpContext context)
{
if (context?.User?.Identity?.IsAuthenticated == true) //先看看是否存了Authenticated 信息 ,从cookies中找 注释 Determine if this represents the unauthenticated identity
{
await context.Response.WriteAsync( //href='/Account/Logout'>Sign Out</a>,前后端交互
@"<html>
<head><title>Index</title></head>
<body>" +
$"<h3>Welcome {context.User.Identity.Name}</h3>" +
@"<a href='/Account/Logout'>Sign Out</a>
</body>
</html>");
}
else
{
await context.ChallengeAsync(); //cookies 里面如果没有的话,这个跳到SignInAsync函数登陆页面
}
}
public static async Task SignInAsync(HttpContext context) //默认先进这个,主页面没有信息
{
if (string.CompareOrdinal(context.Request.Method, "GET") == 0) //第一次看看get参数是否为空
{
await RenderLoginPageAsync(context, null, null, null); //是空的情况下,跳到登陆页面
}
else //登陆后,有到这个函数内
{
var userName = context.Request.Form["username"]; //读取cookie
var password = context.Request.Form["password"];
if (Accounts.TryGetValue(userName, out var pwd) && pwd == password) //正常应到数据库中验证
{
var identity = new GenericIdentity(userName, "Passord"); //验证成功,IsAuthenticated==true
var principal = new ClaimsPrincipal(identity); //这个应该是把identity转换为ClaimsIdentity,添加到List<ClaimsIdentity> 集合中,带有申明的身份对象
await context.SignInAsync(principal); //context,写入带申明的身份
}
else
{
await RenderLoginPageAsync(context, userName, password, "Invalid user name or password!"); //错了就带一条错误信息到登陆页面
}
}
}
private static Task RenderLoginPageAsync(HttpContext context, string userName, string password,
string errorMessage)
{
context.Response.ContentType = "text/html";
return context.Response.WriteAsync( //type='submit' 就是提交
@"<html>
<head><title>Login</title></head>
<body>
<form method='post'>" +
$"<input type='text' name='username' placeholder='User name' value = '{userName}' /> " +
$"<input type='password' name='password' placeholder='Password' value = '{password}' /> " +
@"<input type='submit' value='Sign In' />
</form>" +
$"<p style='color:red'>{errorMessage}</p>" +
@"</body>
</html>");
}
public static async Task SignOutAsync(HttpContext context)
{
await context.SignOutAsync();
context.Response.Redirect("/"); //跳转到首页
}
}
}