我一直在考虑重构我的登录控制器,以获得更好的代码可读性。这样做的时候,我发现
Programmatic OpenID Relying Party example
看起来像这样
using DotNetOpenAuth.Messaging;
public ActionResult LogOn()
{
var openid = new OpenIdRelyingParty();
IAuthenticationResponse response = openid.GetResponse();
if (response != null)
{
switch (response.Status)
{
case AuthenticationStatus.Authenticated:
FormsAuthentication.RedirectFromLoginPage(
response.ClaimedIdentifier, false);
break;
case AuthenticationStatus.Canceled:
ModelState.AddModelError("loginIdentifier",
"Login was cancelled at the provider");
break;
case AuthenticationStatus.Failed:
ModelState.AddModelError("loginIdentifier",
"Login failed using the provided OpenID identifier");
break;
}
}
return View();
}
[System.Web.Mvc.AcceptVerbs(HttpVerbs.Post)]
public ActionResult LogOn(string loginIdentifier)
{
if (!Identifier.IsValid(loginIdentifier))
{
ModelState.AddModelError("loginIdentifier",
"The specified login identifier is invalid");
return View();
}
else
{
var openid = new OpenIdRelyingParty();
IAuthenticationRequest request = openid.CreateRequest(
Identifier.Parse(loginIdentifier));
// Require some additional data
request.AddExtension(new ClaimsRequest
{
BirthDate = DemandLevel.NoRequest,
Email = DemandLevel.Require,
FullName = DemandLevel.Require
});
return request.RedirectingResponse.AsActionResult();
}
}
现在这看起来比我从可下载的示例中使用的更干净、更容易阅读。(我下载了最新版本,这是他们给出的示例——这与我5个月前构建应用程序的示例相同。)
[ValidateInput(false)]
public ActionResult Authenticate(string returnUrl) {
var response = openid.GetResponse();
if (response == null) {
// Stage 2: user submitting Identifier
Identifier id;
if (Identifier.TryParse(Request.Form["openid_identifier"], out id)) {
try {
return openid.CreateRequest(Request.Form["openid_identifier"]).RedirectingResponse.AsActionResult();
} catch (ProtocolException ex) {
ViewData["Message"] = ex.Message;
return View("Login");
}
} else {
ViewData["Message"] = "Invalid identifier";
return View("Login");
}
} else {
// Stage 3: OpenID Provider sending assertion response
switch (response.Status) {
case AuthenticationStatus.Authenticated:
Session["FriendlyIdentifier"] = response.FriendlyIdentifierForDisplay;
FormsAuthentication.SetAuthCookie(response.ClaimedIdentifier, false);
if (!string.IsNullOrEmpty(returnUrl)) {
return Redirect(returnUrl);
} else {
return RedirectToAction("Index", "Home");
}
case AuthenticationStatus.Canceled:
ViewData["Message"] = "Canceled at provider";
return View("Login");
case AuthenticationStatus.Failed:
ViewData["Message"] = response.Exception.Message;
return View("Login");
}
}
return new EmptyResult();
}
现在这个例子有太多我喜欢的if语句,并且需要额外的处理(
activity logging
和
checking for new user
或
add to existing account
),它开始变得非常混乱非常迅速。
不幸的是,如果我要重构我的代码,使其看起来更像第一个示例,我会遇到一个小问题。视图如何与此交互?我是说,它在寻找
openid.GetResponse()
,但如何提交该响应?
就像我说的,如果我能把它弄好,它看起来会比我现在的方式干净得多。