.NET 6.0 MVC使用Cookie进行身份验证

news/2024/9/24 6:13:14/

一般而言MVC 是不与其他系统发生数据交互,所以使用Cookie验证即可,无需安装拓展。

1.Program里面注册服务

//1.选择使用那种方式来身份验证
builder.Services.AddAuthentication(option =>
{option.DefaultAuthenticateScheme = CookieAuthenticationDefaults.AuthenticationScheme; //默认身份验证方案option.DefaultChallengeScheme = CookieAuthenticationDefaults.AuthenticationScheme;option.DefaultSignInScheme = CookieAuthenticationDefaults.AuthenticationScheme;option.DefaultForbidScheme = CookieAuthenticationDefaults.AuthenticationScheme;option.DefaultSignOutScheme = CookieAuthenticationDefaults.AuthenticationScheme;
}).AddCookie(CookieAuthenticationDefaults.AuthenticationScheme, option =>
{option.LoginPath = "/Login/Login";//如果没有找到用户信息---身份验证失败--授权也失败了---就跳转到指定的Actionoption.LogoutPath = "/Login/Logout";//登出跳转option.AccessDeniedPath = "/Login/Login";//身份验证失败页面//option.Events.OnRedirectToLogin = context =>//{//    //context.Response.StatusCode = 302; // 设置302重定向状态码//    //context.Response.Headers["Location"] = "/Login/Login"; // 重定向到登录页//    //context.Response.Redirect(context.RedirectUri);//    return Task.CompletedTask;//};
});//2)在 app.UseAuthorization() 代码上添加 UseAuthentication 即 身份验证中间件,
app.UseAuthentication();//身份验证中间件,必须在前
app.UseAuthorization();//授权中间件

2.在用户登录时给添加身份(LoginModel 只是我的接收参数的类,此处改为自己的即可)

public async Task<IActionResult> LoginAction([FromBody] LoginModel model)
{
//.....身份验证逻辑
//.....
//验证成功,创建身份信息var claims = new List<Claim>()//身份验证信息
{new Claim(ClaimTypes.Name,$"{model.Account}"),//用户传过来的账号new Claim(ClaimTypes.Role,model.RoleName),用户传过来的角色,最好根据账号从数据库查询,用于授权new Claim("PassWord",model.PassWord),//用户传过来的密码new Claim("RoleId",RoleId),//可以写入任意数据
};//通过Claim来创建ClaimsIdentity 类似于通过用户的身份来创建身份证
var claimsIdentity = new ClaimsIdentity(claims, CookieAuthenticationDefaults.AuthenticationScheme);var authProperties = new AuthenticationProperties
{//应该允许刷新身份验证会话。AllowRefresh = true,//身份验证票证过期的时间10分钟ExpiresUtc = DateTimeOffset.UtcNow.AddMinutes(30),//允许持久化IsPersistent = true,//cookie过期时间1天IssuedUtc = DateTime.Now.AddDays(1),重定向url地址//RedirectUri = "/Login/Login"
};//授权cookie
await HttpContext.SignInAsync(CookieAuthenticationDefaults.AuthenticationScheme, new ClaimsPrincipal(claimsIdentity), authProperties);var result = new
{success = true,msg = "登录成功",//消息
};
return Json(result);
}

用户退出登录

  /// <summary>/// 退出/// </summary>/// <returns></returns>public async Task<IActionResult> Logout(){await HttpContext.SignOutAsync(CookieAuthenticationDefaults.AuthenticationScheme);return RedirectToAction("Login");}

获取用户信息:

/// <summary>
/// 获取用户信息
/// </summary>
/// <returns></returns>
//[Authorize(AuthenticationSchemes = CookieAuthenticationDefaults.AuthenticationScheme)]
public string GetUser()
{try{if (HttpContext.User.Identity != null){if (HttpContext.User.Identity.IsAuthenticated)  //判断用户是否通过认证{string name = HttpContext.User.Claims.ToList()[0].Value;return name;}else{return "未登录";}}return "无权访问";}catch (Exception ex){return "欢迎";}
}

授权使用方法(注:三种授权方式(Policy、Role、Scheme),这里是通过角色授权):

[Authorize(Roles = "SysAdmin,UserAdmin,RoleAdmin")]//只有角色为SysAdmin,UserAdmin,RoleAdmin其中一个的可访问该控制器
public class RoleController : Controller//你的控制器
{
/// <summary>
/// 用户管理
/// </summary>
/// <returns></returns>
[Authorize(Roles = "SysAdmin,UserAdmin")]//Authorize不传参数的话代表只要验证成功就可访问控制器,容易造成垂直越权行为
public IActionResult UserManager()
{return View();
}
}


http://www.ppmy.cn/news/1529684.html

相关文章

Protobuf:基本概念与使用流程

Protobuf&#xff1a;基本概念与使用流程 基本概念Linux 安装使用流程.proto文件编译使用 运行机制 基本概念 在进行网络编程时&#xff0c;经常需要进行数据传输&#xff0c;只有双方主机都保证数据格式的一致性&#xff0c;才能保证数据被正常解析。这个过程称为序列化与反序…

PDF里怎么直接编辑文字?简单操作指南

PDF作为一种广泛使用的文档格式&#xff0c;因其稳定性和跨平台兼容性而受到欢迎。然而&#xff0c;PDF原生的编辑功能相对有限&#xff0c;尤其是直接编辑其中的文字。但幸运的是&#xff0c;随着技术的发展&#xff0c;我们现在有几种方法可以在PDF中直接编辑文字。在本文中&…

JS巧用.padStart()|.padEnd()方法用另一个字符串填充当前字符串

示例 const sortNum computed(() > No.${${1}.padStart(2, 0)}); // No.01const sortNum computed(() > No.${${1}.padEnd(2, 0)}); // No.10 padStart .padStart() 方法可以用于添加一个字符串作为填充&#xff0c;以使当前字符串达到所需的长度。例如&#xff0c;…

Vue开发前端图片上传给java后端

前端效果图 图片上传演示 1 前端代码 <template><div><!-- 页面标题 --><h1 class"page-title">图片上传演示</h1><div class"upload-container"><!-- 使用 van-uploader 组件进行文件上传&#xff0c;v-model 绑…

开关电源自动测试系统的测试设备与特色

突破传统测试系统的操作维护困难等限制&#xff0c;NSAT-8000开关电源自动测试系统以其开放式架构和0代码模式&#xff0c;带来了不一样的开关电源自动化测试体验。 开关电源自动测试系统的测试设备 开关电源自动测试系统核心硬件包括&#xff1a;可编程交直流电源、电子负载、…

【技术解析】wx.request 封装:优化小程序网络请求的最佳实践

在当今的小程序开发领域&#xff0c;网络请求是构建动态应用的核心。微信小程序提供的 wx.request API 虽然强大&#xff0c;但在面对复杂业务逻辑时&#xff0c;其直接使用方式可能会带来一系列问题。本文将深入探讨封装 wx.request 的必要性&#xff0c;并提供一套实用的封装…

java.nio.ByteBuffer的 capacity, limit, position, mark

java.nio.ByteBuffer的 capacity, limit, position, mark Capacity&#xff08;容量&#xff09; 定义&#xff1a;缓冲区的总容量&#xff0c;即缓冲区中可以容纳的元素的数量。这个容量在缓冲区创建时被设定&#xff0c;并且之后不能被改变。 用途&#xff1a;它定义了缓冲区…

【ShuQiHere】 探索数据挖掘的世界:从概念到应用

&#x1f310; 【ShuQiHere】 数据挖掘&#xff08;Data Mining, DM&#xff09; 是一种从大型数据集中提取有用信息的技术&#xff0c;无论是在商业分析、金融预测&#xff0c;还是医学研究中&#xff0c;数据挖掘都扮演着至关重要的角色。本文将带您深入了解数据挖掘的核心概…