使用ClaimsIdentity来实现登录授权
2024-09-23 10:28:18
背景:以前做登录时用的都是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>
好了,好像就这么多了,结束!!!!!!
最新文章
- 关于ie版本判断
- LeetCode Find All Duplicates in an Array
- Haproxy日志配置
- 调用KEditor批量上传图片
- 进度的Block在子线程调用
- Castle.ActiveRecord (V3.0.0.130)
- char (*(*p[3])( int ))[5] 等等一系列 左右法则
- 工具系列之Sublime Text 3 使用总结
- Windows Azure案例分析: 选择虚拟机或云服务?
- Python里的拷贝=====》很容易错误的
- css学习笔记四
- django开发简易博客(三)
- Java代码检查工具
- 利用id来进行树状数组,而不是离散化以后的val HDU 4417 离线+树状数组
- SQL SERVER大话存储结构(6)_数据库数据文件
- Hadoop启动脚本分析
- base64转码,解码方法
- 在django中访问静态文件(js css img)
- zabbix_agentd-install.sh (脚本部署zabbix_agentd服务)
- Android实战简易教程-第二十三枪(基于Baas的用户注冊验证username是否反复功能!)