【问题标题】:dotnetopenauth ajax post tutorialdotnetopenauth ajax 后期教程
【发布时间】:2011-01-17 18:25:43
【问题描述】:

我一直在看书呆子晚餐 2.0,我看到他们的 openid 喜欢一个 ajax 请求。我知道你不能使用完整的 ajax 样式(即我不能将网页粘贴在 jquery ui 对话框中),但你可以打开另一个窗口。

看了一段时间的书呆子晚餐代码后,我似乎无法弄清楚他们是如何做到的。我想知道是否有人有关于如何执行这种 ajax 样式 openid 的分步教程?

谢谢

【问题讨论】:

    标签: asp.net-mvc-2 dotnetopenauth nerddinner


    【解决方案1】:

    我不知道它是如何在 NerdDinner 中完成的,但这是我编写的分步教程,以说明如何使用 jQuery 和 ASP.NET MVC 3(Razor 视图引擎)实现这一目标:

    1. 使用 Empty 模板创建一个新的 ASP.NET MVC 3 项目。
    2. 使用 NuGet 将库包引用添加到 DotNetOpenAuth 模块(这将引用来自 Internet 的正确程序集并将必要的配置部分添加到您的 web.config)。
    3. 添加一个 HomeController:

      public class HomeController : Controller
      {
          public ActionResult Index()
          {
              return View();
          }
      }
      
    4. 以及对应的~/Views/Home/Index.cshtml视图:

      @{
          ViewBag.Title = "Index";
          Layout = "~/Views/Shared/_Layout.cshtml";
      }
      <script type="text/javascript">
          $(function () {
              $('a#btnlogin').click(function () {
                  // Ajaxify the btnlogin action link so that
                  // we popup the login form
                  // In this example it is a simple HTML injection
                  // but here you could get fancy with 
                  // animations, CSS, jquery dialogs, 
                  // whatever comes a designer's mind
                  $('#login').load(this.href);
                  return false;
              });
          });
      </script>
      
      <div>
          @TempData["message"]
      </div>
      
      @if (User.Identity.IsAuthenticated)
      {
          <div>
              Welcome @User.Identity.Name. 
              @using (Html.BeginForm("signout", "login", FormMethod.Post))
              {
                  <input type="submit" value="SignOut" />
              }
          </div>
      }
      else
      {
          <div>
              You are not authenticated.
              @Html.ActionLink("Signin using OpenId", "index", "login", null, new { id = "btnlogin" })
          </div>
          <div id="login"></div>    
      }
      
    5. 接下来是处理身份验证的重要部分LoginController

      using System.Net;
      using System.Web.Mvc;
      using System.Web.Security;
      using DotNetOpenAuth.Messaging;
      using DotNetOpenAuth.OpenId;
      using DotNetOpenAuth.OpenId.Extensions.SimpleRegistration;
      using DotNetOpenAuth.OpenId.RelyingParty;
      
      public class LoginController : Controller
      {
          public ActionResult Index()
          {
              using (var openid = new OpenIdRelyingParty())
              {
                  var response = openid.GetResponse();
                  if (response != null)
                  {
                      switch (response.Status)
                      {
                          case AuthenticationStatus.Authenticated:
                          {
                              var claimsResponse = response.GetExtension<ClaimsResponse>();
                              var username = response.ClaimedIdentifier;
                              if (claimsResponse != null && !string.IsNullOrEmpty(claimsResponse.Email))
                              {
                                  username = claimsResponse.Email;
                              }
                              var cookie = FormsAuthentication.GetAuthCookie(username, false);
                              Response.AppendCookie(cookie);
                              break;
                          }
                          case AuthenticationStatus.Canceled:
                          {
                              TempData["message"] = "Login was cancelled at the provider";
                              break;
                          }
                          case AuthenticationStatus.Failed:
                          {
                              TempData["message"] = "Login failed using the provided OpenID identifier";
                              break;
                          }
                      }
                      return RedirectToAction("index", "home");
                  }
                  return View();
              }
          }
      
          [HttpPost]
          public ActionResult Index(string loginIdentifier)
          {
              if (string.IsNullOrEmpty(loginIdentifier) || !Identifier.IsValid(loginIdentifier))
              {
                  ModelState.AddModelError(
                      "loginIdentifier",
                      "The specified login identifier is invalid"
                  );
                  // The login identifier entered by the user was incorrect
                  // redisplay the partial view with error messages so that 
                  // the suer can fix them:
                  return View();
              }
              else
              {
                  using (var openid = new OpenIdRelyingParty())
                  {
                      var request = openid.CreateRequest(
                          Identifier.Parse(loginIdentifier)
                      );
                      request.AddExtension(new ClaimsRequest
                      {
                          Email = DemandLevel.Require
                      });
                      var response = request.RedirectingResponse;
                      if (response.Status == HttpStatusCode.Redirect)
                      {
                          // We need to redirect to the OpenId provider for authentication
                          // but because this action was invoked using AJAX we need
                          // to return JSON here:
                          return Json(new { redirectUrl = response.Headers[HttpResponseHeader.Location] });
                      }
                      return request.RedirectingResponse.AsActionResult();
                  }
              }
          }
      
          [Authorize]        
          [HttpPost]
          public ActionResult SignOut()
          {
              FormsAuthentication.SignOut();
              return RedirectToAction("index", "home");
          }
      }
      
    6. 以及对应的~/Views/Login/Index.cshtml部分视图:

      @{
          Layout = null;
      }
      <!-- Using the jquery form plugin to Ajaxify my form -->
      <!-- Get from here: http://jquery.malsup.com/form/ -->
      <script src="@Url.Content("~/Scripts/jquery.form.js")" type="text/javascript"></script>
      <script type="text/javascript">
          $(function () {
              $('form').ajaxForm({
                  success: function (result) {
                      if (result.redirectUrl) {
                          // if the open id provider was found redirect 
                          // to it so that the user can authenticate
                          window.location.replace(result.redirectUrl);
                      } else {
                          // there was an error => redisplay form
                          $('#login').html(result);
                      }
                  }
              });
          });
      </script>
      @using (Html.BeginForm())
      {
          @Html.Label("loginIdentifier", "OpenId: ")
          @Html.TextBox("loginIdentifier", "https://www.google.com/accounts/o8/id")
          @Html.ValidationMessage("loginIdentifier")
          <input type="submit" value="Login" />
      }
      

    如果您使用的是 Web 表单视图引擎,则该示例可以很容易地适应网络表单视图引擎。我还故意留下了花哨的动画和 CSS 东西,以展示基础知识。

    【讨论】:

    • 哇 nuget 很甜。虽然时间不多,但我仍在查看您的解决方案。
    • 嘿,我能够尝试您的代码,并且非常接近我想要的期望。我希望它打开一个新窗口,而不是像在nerddinner.com/Account/LogOn?returnUrl=%2F 中那样替换当前窗口。所以我做了 window.open(reponse.url,'','width=550;height=525');这得到了 nerddinner 所拥有的,但从那时起,所有视图都被加载到这个新窗口中。我不知道如何阻止这种情况。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-10-25
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多