2011-01-17 13 views
3

Ich habe Nerd Dinner 2.0 und ich sehe, dass für ihre Openid sie eine Ajax Anfrage mögen. Ich weiß, dass Sie nicht vollen Ajax-Stil gehen können (dh ich kann die Webseite nicht in einem jquery ui-Dialog halten), aber Sie können ein anderes Fenster öffnen.dotnetopenauth Ajax Beitrag Tutorial

Nach einiger Zeit Blick auf den Nerd Dinner-Code kann ich nicht scheinen, herauszufinden, wie sie es tun. Ich frage mich, ob jemand eine Schritt-für-Schritt-Anleitung hat, wie man diesen Ajax-Stil openid macht?

Dank

Antwort

5

Ich weiß nicht, wie es in NerdDinner getan wird, aber hier ist eine Schritt für Schritt Anleitung schrieb ich zu zeigen, wie Sie diese mit jQuery und ASP.NET 3 (Razor-Ansicht-Engine) MVC erreichen konnte:

  1. Erstellen Sie ein neues ASP.NET MVC 3-Projekt mit der leeren Vorlage.
  2. Verwenden von NuGet Bibliothekspaket hinzufügen Verweis auf das Modul DotNetOpenAuth (dies verweist auf die richtige Baugruppe aus dem Internet und fügt der web.config die erforderlichen Konfigurationsabschnitte hinzu).
  3. hinzufügen Homecontroller:

    public class HomeController : Controller 
    { 
        public ActionResult Index() 
        { 
         return View(); 
        } 
    } 
    
  4. und die entsprechende ~/Views/Home/Index.cshtml Ansicht:

    @{ 
        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. Als nächstes kommt die wichtige Rolle der LoginController, die die Authentifizierung behandelt:

    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. Und die entsprechende ~/Views/Login/Index.cshtml Teilansicht:

    @{ 
        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" /> 
    } 
    

Das Beispiel könnte leicht zu Web-Formulare angepasst werden sehen Motor ab, wenn das ist, was Sie verwenden. Ich habe absichtlich auch die ausgefallenen Animationen und CSS-Sachen gelassen, um die Grundlagen zu zeigen.

+0

Wow nugget ist süß. Ich schaue immer noch auf Ihre Lösung, obwohl ich nicht viel Zeit hatte. – chobo2

+0

Hey, ich war in der Lage, deinen Code zu testen und ich bin sehr nah an dem, was ich erwarten möchte. Ich wollte, dass es ein neues Fenster öffnet, anstatt das aktuelle Fenster zu ersetzen, genau wie in http://nerddinner.com/Account/LogOn?returnUrl=%2F. Also habe ich window.open (reponse.url, '', 'width = 550; height = 525'); und das bekommt was Nerddinner hat aber von da an werden alle Ansichten in dieses neue Fenster geladen. Ich bin mir nicht sicher, wie ich das stoppen kann. – chobo2