.net core .net6 Form Cookie Login 认证

发布于:2023-01-20 ⋅ 阅读:(166) ⋅ 点赞:(0)


本文环境 Visual Studio 2022, .Net6

就是一个最简的登录,访问任意页到登录页,登录后返回

一、新建一个“ASP.NET Core Web 应用”项目

选 .net 6的

二、Program.cs 添加代码

生成代码基本都略

var builder = WebApplication.CreateBuilder(args);
//1)在CreateBuilder后至少添加,如下代码AddAuthentication添加的是默认认证的Scheme
//支持添加多种认证,比如cookie 混合 JWT 这里不展开
builder.Services.AddAuthentication(CookieAuthenticationDefaults.AuthenticationScheme)
	.AddCookie(option => option.LoginPath = "/Home/Login");

//...其余代码略
//...之上代码略
//2)在 app.UseAuthorization() 代码上添加 UseAuthentication 即 身份验证中间件,
app.UseAuthentication();
app.UseAuthorization();

三、HomeController.cs 添加代码

按注释里 1)、2)…n) 这样的顺序看

//1)添加 [Authorize] ,对本Controller开启认证
[Authorize] 
public class HomeController : Controller
{
	//...生成的略

	//2)添加一个 Login 设置 AllowAnonymous 不认证
	[AllowAnonymous] 
	public IActionResult Login(string loginName, string psw, string returnUrl)
	{		
		if (this.CheckLogin(loginName, psw))
		{ 
				/*
					3)编写如下代码,SignIn 函数就是登陆
					上面的 CheckLogin 假定是自己的登陆认证。
					上面的 returnUrl 没用就是为了调试容易看见访问的地址。					
				*/
				var ci = new ClaimsIdentity("Cookie.Form");					
				ci.AddClaim(new Claim(ClaimTypes.Name, loginName));
				var cp = new ClaimsPrincipal(ci);
				return this.SignIn(cp);

				/*
					ClaimsIdentit new 时传的 AuthenticationType 初始值
					不能是空串或空
					后续能取到,可用来区分登录来至自己系统其他系统等
					
					Claim如构如本例后续 User.Identity.Name能取到这个 loginName的值
					Claim 可以有很多类型,见 ClaimTypes
				*/
		}
		return View();
	}
	//测试登陆状态代码,会在F5调试时显示在输出里面
	public override void OnActionExecuting(ActionExecutingContext context)
	{
		var cad= (ControllerActionDescriptor)context.ActionDescriptor;
		//_logger生成代码就有	
		_logger.LogInformation($"{cad.ActionName}"
		+ $" 用户登录状态 {User.Identity?.IsAuthenticated}"
		+ $" 登录名 {User.Identity?.Name}"
		+ $" 认证类型 {User.Identity?.AuthenticationType}");

		base.OnActionExecuting(context);
	}
	//测试用的模拟登陆校验的函数
	bool CheckLogin(string loginName, string psw)
	{		
		var rtn = false;
		if (false == this.User.Identity?.IsAuthenticated && !string.IsNullOrEmpty(loginName))
		{
			if (loginName == "admin" && !string.IsNullOrEmpty(psw))
			{
				rtn = true;
			}
		}
		return rtn;
	}
	//...生成的 Index、Privacy、Error 等Action 略。
}

四、做个有 登录名、密码与登陆按钮 的页

在 Views/Home/ 下添加 Login.cshtml

<!--略-->
<form  method="post" >         
    <div class="form-group">
        <label class="control-label">登录名</label>
        <input class="form-control" name="loginName" />
       
    </div>
    <div class="form-group">
        <label  class="control-label">密码</label>
        <input  class="form-control" type="password" name="psw" />               
    </div>          
    <div class="form-group">
       <br/>
        <input type="submit" value="登录" class="btn btn-primary" />
    </div>
</form>
<!--略-->

五、设启动页,F5调试

本案启动为 Home/Privacy 就是生成的

没认证的会跳转到Login如上;输入用户名密码后,登陆成功如下(admin,密码随意)

调试 输出 信息如下

本文含有隐藏内容,请 开通VIP 后查看