ASP.NET Identity 学习
private IAuthenticationManager AuthenticationManager
{
get { return HttpContext.GetOwinContext().Authentication; }
}
private async Task SignInAsync()
{
// 1. 利用ASP.NET Identity获取用户对象
var user = await UserManager.FindAsync("UserName", "Password");
// 2. 利用ASP.NET Identity获取identity 对象
var identity = await UserManager.CreateIdentityAsync(user, DefaultAuthenticationTypes.ApplicationCookie);
// 3. 将上面拿到的identity对象登录
AuthenticationManager.SignIn(new AuthenticationProperties() { IsPersistent = true }, identity);
}
实现登陆,UserManager.CreateIdentityAsync返回给我们的对象是ClaimsIdentity
Claims-based认证和授权在国外被广泛使用,包括微软的ADFS,Google,Facebook,等。
claims-based认证这种方式将认证和授权与登录代码分开,将认证和授权拆分为另外的web服务。
claims-based认证的主要特点:
将认证与授权拆分成的独立的服务
认证源和方法不需关注
用户登录成功的话,认证服务会返回给我们一个令牌(包含用户名,角色信息,密码。。。。)
流程分析:
检测到用户未登陆,跳转到可登陆的 身份信息源 登陆成功,跳转回来(带着身份信息),建立ClaimsPrinpica和ClaimsIdentity对象,生成cookie等。
简单来说,就是把登录的代码(验证用户,获取用户信息)拆分成独立的服务或组件。
asp.net下的claims-based认证实现
ClaimsIdentity以及ClaimsPrincpal这俩个类 ,它们分别继承了接口IIdentity和IPrincipal
IIdentity封装用户信息。
public interface IIdentity{
string AuthenticationType{get;}
bool IsAuthenticated{get;}
string Name{get;}
}
IPrincipal代表着安全上下文
它包含了Identity以及一些角色和组的信息,每一个线程都会关联一个Principal的对象,但是这个对象是属性线程或者AppDomain级别的.
给 Controller方法添加 Authorize(Roles="权限级别"),来限制方法的使用。
手动创建ClaimsIdentity和ClaimsPrincipal对象,然后将Principal对象指定给当前的HttpContext.Current.User.
protected void Application_AuthenticateRequest()
{
var claims =new List<Claim> ();
claims.Add(new Claim(ClaimTypes.Name,"Test"));//添加名称
claims.Add(new Claim(ClaimTypes.Role,"Users")); //添加权限级别
var identity = new ClaimsIdentity(claims,"MyClaimsLogin");
ClaimsPrincipal principal = new ClaimsPrincipal(identity);
HttpContext.Current.User = principal;
}
在Global.asax中添加Application_AuthenticateRequest方法。
var identity = await UserManager.CreateIdentityAsync(user,本地化资源字符串)
UserManager封装了CreateIdentityAsync()方法
OWin如何做到解耦
我们上面说Owin是一套定义,它通过将服务器与应用程序之间的交互归纳为一个方法签名,称之为“应用程序代理”(application delegate) 尼玛,这不是委托吗???
AppFunc = Func<IDictionary<string,object>,Task>;
在一个基于Owin的应用程序中的每一个组件都可以通过这样的一个代理来与服务器进行交互。这里的交互其实是与服务器一起来处理http request,比如说asp.net管道模型中事件,认证,授权等等,原先我们是通过自定义的http module,在里面拿到包含了request和response的HttpContext对象,进行处理。而现在我们能拿到的就是一个Dictionary.
这人个dictionary会在Owin处理request的管道中进行传递,有了Owin之后,页面就和Owin的管道进行交互了。
Microsoft.OWin包括以下4个组件:
Application:当前应用程序或者说网站
Middleware:这个中间层处理OWin管道中处理请求,它会被注册到OWin管道中一起处理 http request
Server:暴露TCP端口,维护字典数据,处理http请求
Host:托管物品的应用程序的进程,主要是用来开启,加载OWin组件,以及合理的关闭他们
Start up类
每一个OWin的应用程序都需要有一个Start up的类,用来声明我们要使用的中间件。
声明方式:
1.命名约定:Owin会扫描在程序集根下名叫startup的类作为默认启动配置类
2.OwinStartup标签
[assembly:OwinStartup(typeof(StartupDemo.TestStartup))]
3.config文件
<add key="owin:AutomaticAppStartup" value="false">