您可以在没有 STS 的情况下在 MVC 中使用 WIF。
我使用了默认的 MVC2 模板,但它也应该适用于 MVC 3。
你需要:
1- 插入 WIF 的 SessionAuthenticationModule (web.config)
< add name="SessionAuthenticationModule" type="Microsoft.IdentityModel.Web.SessionAuthenticationModule, Microsoft.IdentityModel, Version=3.5.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35" />
2- 无论您在何处验证您的用户,创建一个 ClaimsPrincipal,添加所有必需的声明,然后创建一个 SessionSecurityToken强>。这是 MVC 创建的 AccountController 中的 LogOn Action:
[HttpPost]
public ActionResult LogOn(LogOnModel model, string returnUrl)
{
if (ModelState.IsValid)
{
if (MembershipService.ValidateUser(model.UserName, model.Password))
{
var cp = new ClaimsPrincipal();
cp.Identities.Add(new ClaimsIdentity());
IClaimsIdentity ci = (cp.Identity as IClaimsIdentity);
ci.Claims.Add(new Claim(ClaimTypes.Name, model.UserName));
SessionSecurityToken sst = FederatedAuthentication
.SessionAuthenticationModule
.CreateSessionSecurityToken(cp,
"MVC Test",
DateTime.
UtcNow,
DateTime.
UtcNow.
AddHours
(1),
true);
FederatedAuthentication.SessionAuthenticationModule.CookieHandler.RequireSsl = false;
FederatedAuthentication.SessionAuthenticationModule.AuthenticateSessionSecurityToken(sst, true);
//FormsService.SignIn(model.UserName, model.RememberMe);
if (!String.IsNullOrEmpty(returnUrl))
{
return Redirect(returnUrl);
}
else
{
return RedirectToAction("Index", "Home");
}
}
else
{
ModelState.AddModelError("", "The user name or password provided is incorrect.");
}
}
// If we got this far, something failed, redisplay form
return View(model);
}
我只是添加了所需的行,其他所有内容都保持不变。所以可能需要进行一些重构。
从那时起,您的应用现在将收到 ClaimsPrincipal。全部由 WIF 自动处理。
CookieHandler.RequiresSsl = false 只是因为它是开发机器,我没有部署在 IIS 上。也可以在配置中定义。