Commits

Jeff Craig  committed 31e075e

Working OpenID authentication. Now to integrate in to User system.

  • Participants
  • Parent commits 865345e
  • Branches openid

Comments (0)

Files changed (7)

File CodeCamp/CodeCamp/CodeCamp.csproj

     <WarningLevel>4</WarningLevel>
   </PropertyGroup>
   <ItemGroup>
+    <Reference Include="DotNetOpenAuth">
+      <HintPath>..\..\Externals\DotNetOpenAuth\DotNetOpenAuth.dll</HintPath>
+    </Reference>
     <Reference Include="System" />
     <Reference Include="System.Data" />
     <Reference Include="System.Data.DataSetExtensions" />
     <Content Include="Views\Account\SignIn.aspx" />
     <Content Include="Views\DevSat\Index.aspx" />
     <Content Include="Views\Home\About.aspx" />
+    <Content Include="Views\Home\Xrds.aspx" />
     <Content Include="Views\Presenters\Add.aspx" />
     <Content Include="Views\Presenters\Details.aspx" />
     <Content Include="Views\Presenters\Edit.aspx" />

File CodeCamp/CodeCamp/Controllers/AccountController.cs

 using System.Web.Mvc;
 using System.Web.Security;
 using System.Web.UI;
+using DotNetOpenAuth.OpenId.RelyingParty;
+using DotNetOpenAuth.OpenId;
+using DotNetOpenAuth.Messaging;
 
 namespace CodeCamp.Controllers
 {
       return View();
     }
 
-    [AcceptVerbs( HttpVerbs.Post )]
-    [System.Diagnostics.CodeAnalysis.SuppressMessage( "Microsoft.Design", "CA1054:UriParametersShouldNotBeStrings",
-        Justification = "Needs to take same parameter type as Controller.Redirect()" )]
-    public ActionResult SignIn( string userName, string password, string returnUrl )
+    [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Design", "CA1054:UriParametersShouldNotBeStrings",
+        Justification = "Needs to take same parameter type as Controller.Redirect()")]
+    public ActionResult Authenticate(string returnUrl)
     {
-
-      if ( !ValidateLogOn( userName, password ) )
-      {
-        return View();
-      }
-
-      FormsAuth.SignIn( userName, false);
-      if ( !String.IsNullOrEmpty( returnUrl ) )
-      {
-        return Redirect( returnUrl );
-      }
-      else
-      {
-        return RedirectToAction( "Index", "Home" );
-      }
+        var response = openid.GetResponse();
+        if (response == null)
+        {
+            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;
+                }
+            }
+            else
+            {
+                ViewData["Message"] = "Invalid Identifier";
+            }
+            return View("SignIn");
+        }
+        else
+        {
+            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("SignIn");
+                case AuthenticationStatus.Failed:
+                    ViewData["Message"] = response.Exception.Message;
+                    return View("SignIn");
+            }
+        }
+        return new EmptyResult();
     }
 
     public ActionResult SignOut()

File CodeCamp/CodeCamp/Controllers/HomeController.cs

 using System.Collections.Generic;
 using System.Web.Mvc;
 using CodeCamp.Models.Home;
+using System;
 
 namespace CodeCamp.Controllers
 {
   {
     public ActionResult Index( string eventName )
     {
+        // Needed for OAuth
+        Response.AppendHeader(
+            "X-XRDS-Location",
+            new Uri(Request.Url, Response.ApplyAppPathModifier("~/Home/xrds")).AbsoluteUri);
+
       (new TransformEntities00ToEntities01()).Execute();
 
       int eventId = EventsHelper.GetEventId( eventName );
 
       return View( model );
     }
+
+    public ActionResult Xrds()
+    {
+        return View();
+    }
   }
 }

File CodeCamp/CodeCamp/Global.asax.cs

       routes.IgnoreRoute( "{resource}.axd/{*pathInfo}" );
       routes.IgnoreRoute( "favicon.ico" );
 
+      routes.MapRoute("Account Routes",
+          "Account/{action}",
+          new
+          {
+              eventName = SiteConfig.DefaultEvent,
+              controller = "Account",
+              action = "SignIn"
+          });
       routes.MapRoute(
         "RouteWithDefaultIndex",                    // route name
         "{eventName}/{controller}/{action}/{id}",   // URL pattern with parameters

File CodeCamp/CodeCamp/Views/Account/SignIn.aspx

     Presenter Sign In
   </h2>
   <%= Html.ValidationSummary("Login was unsuccessful. Please correct the errors and try again.") %>
-    <form action="/Account/SignIn?ReturnUrl=<%=HttpUtility.UrlEncode(Request.QueryString["ReturnUrl"]) %>" method="post" class="openid">
+    <form action="/Account/Authenticate?ReturnUrl=<%=HttpUtility.UrlEncode(Request.QueryString["ReturnUrl"]) %>" method="post" class="openid">
       <div>
           <p>Do you already have an account on one of these sites? You can use that to log on here!</p>
           <ul class="providers">

File CodeCamp/CodeCamp/Views/Home/Xrds.aspx

+<%@ Page Language="C#" Inherits="System.Web.Mvc.ViewPage" ContentType="application/xrds+xml" %><?xml version="1.0" encoding="UTF-8"?>
+<%--
+This page is a required for relying party discovery per OpenID 2.0.
+It allows Providers to call back to the relying party site to confirm the
+identity that it is claiming in the realm and return_to URLs.
+This page should be pointed to by the 'realm' home page, which in this sample
+is default.aspx.
+--%>
+<xrds:XRDS
+	xmlns:xrds="xri://$xrds"
+	xmlns:openid="http://openid.net/xmlns/1.0"
+	xmlns="xri://$xrd*($v*2.0)">
+	<XRD>
+		<Service priority="1">
+			<Type>http://specs.openid.net/auth/2.0/return_to</Type>
+			<%-- Every page with an OpenID login should be listed here. --%>
+			<%-- We use the Authenticate action instead of Login because Authenticate
+			     is the action that receives OpenId assertions. --%>
+			<URI><%=new Uri(Request.Url, Response.ApplyAppPathModifier("~/Account/Authenticate"))%></URI>
+		</Service>
+	</XRD>
+</xrds:XRDS>

File CodeCamp/CodeCamp/Web.config

   -->
 <configuration>
   <configSections>
+    <section name="uri" type="System.Configuration.UriSection, System, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" />
+    <section name="dotNetOpenAuth" type="DotNetOpenAuth.Configuration.DotNetOpenAuthSection" requirePermission="false" allowLocation="true" />
     <sectionGroup name="system.web.extensions" type="System.Web.Configuration.SystemWebExtensionsSectionGroup, System.Web.Extensions, Version=3.5.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35">
       <sectionGroup name="scripting" type="System.Web.Configuration.ScriptingSectionGroup, System.Web.Extensions, Version=3.5.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35">
         <section name="scriptResourceHandler" type="System.Web.Configuration.ScriptingScriptResourceHandlerSection, System.Web.Extensions, Version=3.5.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35" requirePermission="false" allowDefinition="MachineToApplication"/>
       </sectionGroup>
     </sectionGroup>
   </configSections>
+
+  <uri>
+    <idn enabled="All" />
+    <iriParsing enabled="true" />
+  </uri>
+  
   <connectionStrings>
     <!-- If you add items to connectionStrings, be sure to add them to ConfigurationItems.xml also. -->
   <add name="CodeCampConnectionString" connectionString="Data Source=sql2k803.discountasp.net;Initial Catalog=SQL2008_499609_pdxcodecamp;Persist Security Info=True;User ID=SQL2008_499609_pdxcodecamp_user;Password=c0decamp"
       </assemblies>
     </compilation>
     <authentication mode="Forms">
-      <forms loginUrl="~/2010/Account/SignIn" timeout="2880"/>
+      <forms defaultUrl="~/Home" loginUrl="~/2010/Account/SignIn" timeout="2880"/>
     </authentication>
     <membership>
       <providers>