MVC 使用ClaimsIdentity来实现登录授权
背景:以前做登录时用的都是FormsAuthentication.SetAuthCookie(model.UID, IsRemeber),但是有一个不好,不能存储多个值,有时候我们既想存储登录用户的UID又想存储用户名,以前都是将两者拼接成字符串,用的时候在split出来,比较麻烦,现在用ClaimsIdentity就很方便。
1、登录时验证通过存储
ClaimsIdentity ci = new ClaimsIdentity(DefaultAuthenticationTypes.ApplicationCookie);
ci.AddClaim(new Claim(ClaimsIdentity.DefaultNameClaimType, model.UserName));
ci.AddClaim(new Claim(ClaimTypes.NameIdentifier, model.UID));
ci.AddClaim(new Claim("HspUID", model.HspUID));
AuthenticationManager.SignIn(new AuthenticationProperties { IsPersistent = IsRemeber }, ci);
需要用到下面的
private IAuthenticationManager AuthenticationManager
{
get
{
return HttpContext.GetOwinContext().Authentication;
}
}
2、获取值
//获取UID
User.Identity.GetUserId();
//获取Name
User.Identity.Name;
//获取HspUID
var claimIdentity = (ClaimsIdentity)User.Identity;
var HspUID = claimIdentity.FindFirstValue("HspUID");
3、App_Start里创建Startup.Auth.cs
using Microsoft.AspNet.Identity;
using Microsoft.Owin;
using Microsoft.Owin.Security.Cookies;
using Owin;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
namespace Yuwell.PressureManage.Web
{
public partial class Startup
{
public void ConfigureAuth(IAppBuilder app)
{
// 使应用程序可以使用 Cookie 来存储已登录用户的信息
// 并使用 Cookie 来临时存储有关使用第三方登录提供程序登录的用户的信息
// 配置登录 Cookie
app.UseCookieAuthentication(new CookieAuthenticationOptions
{
AuthenticationType = DefaultAuthenticationTypes.ApplicationCookie,
LoginPath = new PathString("/Account/Login"),
});
}
}
}
4、Web项目里添加Startup类
using Hangfire;
using Hangfire.MemoryStorage;
using Microsoft.Owin;
using Owin;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
[assembly: OwinStartupAttribute(typeof(Test.Web.Startup))]
namespace Yuwell.PressureManage.Web
{
public partial class Startup
{
public void Configuration(IAppBuilder app)
{
ConfigureAuth(app);
GlobalConfiguration.Configuration.UseMemoryStorage();
app.UseHangfireServer();
app.UseHangfireDashboard();
}
}
}
需要用到的包
记得Web.config里configSections节点下加下面的配置
<system.webServer>
<modules>
<remove name="FormsAuthentication" />
</modules>
</system.webServer>
好了,好像就这么多了,结束!!!!!!
————————————————
版权声明:本文为CSDN博主「Archy_Wang_1」的原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接及本声明。
原文链接:https://blog.csdn.net/u011966339/article/details/88791524
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 记一次.NET内存居高不下排查解决与启示
· 探究高空视频全景AR技术的实现原理
· 理解Rust引用及其生命周期标识(上)
· 浏览器原生「磁吸」效果!Anchor Positioning 锚点定位神器解析
· 没有源码,如何修改代码逻辑?
· 分享4款.NET开源、免费、实用的商城系统
· 全程不用写代码,我用AI程序员写了一个飞机大战
· MongoDB 8.0这个新功能碉堡了,比商业数据库还牛
· 白话解读 Dapr 1.15:你的「微服务管家」又秀新绝活了
· 上周热点回顾(2.24-3.2)