我有一个应用程序在Windows Phone 8.1设备上运行,它访问ASP.NET MVC WebAPI上的后端构建。使用FormsAuthentication进行身份验证,因为WindowsAuthentication在此设置中不可用。我可以让它运行:用户在手机上的自定义登录表单中输入她的凭证,在服务器端凭据根据Active Directory进行验证。之后,客户端获得一个AuthenticationToken。在ASP.NET MVC中用WindowsIdentity替换FormsIdentity
这个片段是从的LoginController:
if (Membership.ValidateUser(username, password))
{
FormsAuthentication.SetAuthCookie(username, false);
return Request.CreateResponse(HttpStatusCode.OK);
}
else
return Request.CreateResponse(HttpStatusCode.Unauthorized);
而这个片段展示了验证在web.config配置:
<system.web>
<authentication mode="Forms" />
<authorization>
<allow users="*" />
</authorization>
<membership defaultProvider="MembershipADProvider">
<providers>
<add name="MembershipADProvider"
type="System.Web.Security.ActiveDirectoryMembershipProvider, System.Web, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a"
connectionStringName="ADConnectionString"/>
</providers>
</membership>
</system.web>
我的问题是,FormsIdentity仅公开用户名。但后端需要包含AD用户的SID的WindowsIdentity。后端最初是为基于浏览器的客户端构建的,并不意味着要为移动设备提供服务。
var windowsId = User.Identity as WindowsIdentity;
if (windowsId == null) return null;
var sid = windowsId.User;
我的想法是在身份验证发生后用WindowsIdentity替换FormsIdentity。为了做到这一点,我挂钩到ASP.NET管道PostAuthenticateRequest事件:
using System;
using System.Web;
namespace MyApp
{
public class FromToWindowsAuthenticationModule : IHttpModule
{
public void Init(HttpApplication context)
{
context.PostAuthenticateRequest += PostAuthenticateRequest;
}
public void Dispose()
{
}
private void PostAuthenticateRequest(object sender, EventArgs e)
{
var ctx = HttpContext.Current;
if (ctx.Request.IsAuthenticated)
{
var principal = ctx.User;
var formsIdentity = principal.Identity as FormsIdentity;
if (formsIdentity != null)
{
var username = formsIdentity.Name;
var ident = new WindowsIdentity(...); // ???????????????????
var newUser = new WindowsPrincipal(ident);
ctx.User = Thread.CurrentPrincipal = newUser
}
}
}
}
}
要激活模块,这些线必须添加到Web.config:
<system.webServer>
<modules>
<add name="FormToWindowsAuthenticationModule"
type="MyApp.FormToWindowsAuthenticationModule"
preCondition="managedHandler" />
</modules>
</system.webServer>
的唯一缺少的是从ActiveDirectory检索WindowsIdentifier的部分。我怎样才能做到这一点?
我的方法是否可行?替换Identity对象是否会干扰ASP.NET管道的其余元素?