我正在尝试在 IIS 中使用应用程序请求路由 (ARR) 将一组路径传递给 Node.js 网站。我的问题是能够在任一侧获取/设置身份验证票。
我只需要一个简单的加密/解密对示例,它可以在 C# 和 Node.js 中使用,并且开箱即用,两者的结果相同。在接下来的几天里,如果时间允许,我将自己解决这个问题,如果没有人在我之前提出答案,我打算回答。
我的意图是将节点端编写为 Node.js 端的连接/表达模块。我已经在 ASP.Net 解决方案中进行了自定义身份验证,并且可以轻松地将我当前的方法替换为可以在两个平台上都安全的方法(只要它们共享相同的密钥)。
用于创建身份验证 cookie 的当前代码AccountController.cs
private void ProcessUserLogin(MyEntityModel db, SiteUser user, bool remember=false)
{
var roles = String.Join("|", value:user.SiteRoles.Select(sr => sr.Name.ToLowerInvariant().Trim()).Distinct().ToArray());
//update the laston record(s)
user.UserAgent = Request.UserAgent;
user.LastOn = DateTimeOffset.UtcNow;
db.SaveChanges();
// Create and tuck away the cookie
var authTicket = new FormsAuthenticationTicket(
1
,user.Username
,DateTime.Now
,DateTime.Now.AddDays(31) //max 31 days
,remember
,string.IsNullOrWhiteSpace(roles) ? "guest" : roles
);
var ticket = FormsAuthentication.Encrypt(authTicket);
var cookie = new HttpCookie(FormsAuthentication.FormsCookieName, ticket);
if (remember) cookie.Expires = DateTime.Now.AddDays(8);
Response.Cookies.Add(cookie);
}
读取身份验证 cookie 的当前代码Global.asax.cs
void Application_AuthenticateRequest(object sender, EventArgs args)
{
HttpCookie authCookie = Context.Request.Cookies[FormsAuthentication.FormsCookieName];
if (authCookie == null) return;
FormsAuthenticationTicket authTicket = FormsAuthentication.Decrypt(authCookie.Value);
string[] roles = authTicket.UserData.Split(new Char[] { '|' });
//create new generic identity, and corresponding principal...
var g = new GenericIdentity(authTicket.Name);
var up = new GenericPrincipal(g, roles);
//set principal for current request & thread (app will handle transitions from here)
Thread.CurrentPrincipal = Context.User = up;
}
相关部分Web.config
<?xml version="1.0" encoding="utf-8"?>
<configuration>
<system.web>
<membership>
<providers>
<!-- Remove default provider(s), so custom override works -->
<clear />
</providers>
</membership>
</system.web>
</configuration>