【问题标题】:What OpenID solution is really used by Stack Overflow?Stack Overflow 真正使用了什么 OpenID 解决方案?
【发布时间】:2011-07-05 06:30:05
【问题描述】:

我知道对此还有其他问题,但它们已经过时了,我无法在任何地方找到可靠的答案。

StackOverflow 真正使用什么来验证用户身份?该网站DotNetOpenAuth 声称它是。但对我来说,最(视觉上)相似的外观是 OAuth C# Library。

那么它的真正用途是什么?或者我怎样才能模仿相同的 UI?

我想使用 ASP.NET MVC 创建完全相同的 OpenID 身份验证。

【问题讨论】:

  • 我觉得这个问题需要特殊的评论。自从被问到它被问到它已经移动到 StackOverflow 元,然后回到主 StackOverflow,再次到元并回到主。感觉它属于两个站点还是不属于它们?我相信它属于我最初发布的 StackOverflow main。那是因为我不是因为对 SO 站点本身的好奇而问的,而是因为我想使用相同的解决方案,相同的技术。因此,Lirick 的回答是对我的问题的很好回答,但这样的回答与元无关(技术性太强),所以它留在这里。

标签: oauth openid


【解决方案1】:

我能够在相当短的时间内在我的网站 (www.mydevarmy.com) 上通过 DotNetOpenAuth 获得 OpenID 身份验证(请注意,我是 ASP.NET、MVC、DotNetOpenAuth 等的总 noob)。

DotNetOpenAuth 带有各种示例,他们甚至有一个 ASP.NET MVC 示例,但他们只在该示例中提供了一个视图和控制器,并且他们实际上没有一个模型,即 M MVC 中的强 > :)。随后我就 SO 提出了以下问题:

What are the responsibilities of the components in an MVC pattern for a simple login

那么,非常简单 OpenID 登录在 MVC 中会是什么样子?好吧,让我们来看看……

1.你需要一个模型:

public class User
{
    [DisplayName("User ID")]
    public int UserID{ get; set; }

    [Required]
    [DisplayName("OpenID")]
    public string OpenID { get; set; }
}

public class FormsAuthenticationService : IFormsAuthenticationService
{
    public void SignIn(string openID, bool createPersistentCookie)
    {
        if (String.IsNullOrEmpty(openID)) throw new ArgumentException("OpenID cannot be null or empty.", "OpenID");

        FormsAuthentication.SetAuthCookie(openID, createPersistentCookie);
    }

    public void SignOut()
    {
        FormsAuthentication.SignOut();
    }
}  

2。您将需要一个控制器:

[HandleError]
public class UserController : Controller
{
    private static OpenIdRelyingParty openid = new OpenIdRelyingParty();
    public IFormsAuthenticationService FormsService { get; set; }

    protected override void Initialize(RequestContext requestContext)
    {
        if (FormsService == null) 
        {
            FormsService = new FormsAuthenticationService(); 
        }

        base.Initialize(requestContext);
    }

    // **************************************
    // URL: /User/LogIn
    // **************************************
    public ActionResult LogIn()
    {
        if (User.Identity.IsAuthenticated)
        {
            return RedirectToAction("Profile", "User");
        }

        Identifier openID;
        if (Identifier.TryParse(Request.QueryString["dnoa.userSuppliedIdentifier"], out openID))
        {
            return LogIn(new User { OpenID = openID }, Request.QueryString["ReturnUrl"]);
        }
        else
        {
            return View();
        }
    }

    [HttpPost]
    public ActionResult LogIn(User model, string returnUrl)
    {
        string openID = ModelState.IsValid?model.OpenID:Request.Form["openid_identifier"];

        if (User.Identity.IsAuthenticated)
        {
            return RedirectToAction("Profile", "User");
        }
        else if (!string.IsNullOrEmpty(openID))
        {
            return Authenticate(openID, returnUrl);
        }
        else if(ModelState.IsValid)
        {
            ModelState.AddModelError("error", "The OpenID field is required.");
        }

        // If we got this far, something failed, redisplay form
        return View(model);
    }

    // **************************************
    // URL: /User/LogOut
    // **************************************
    public ActionResult LogOut()
    {
        if (User.Identity.IsAuthenticated)
        {
            FormsService.SignOut();
        }

        return RedirectToAction("Index", "Home");
    }

    // **************************************
    // URL: /User/Profile
    // **************************************
    [Authorize]
    public ActionResult Profile(User model)
    {
        if (User.Identity.IsAuthenticated)
        {
            // ------- YOU CAN SKIP THIS SECTION ----------------
            model = /*some code to get the user from the repository*/;

            // If the user wasn't located in the database
            // then add the user to our database of users
            if (model == null)
            {
                model = RegisterNewUser(User.Identity.Name);
            }
            // --------------------------------------------------

            return View(model);
        }
        else
        {
            return RedirectToAction("LogIn");
        }
    }

    private User RegisterNewUser(string openID)
    {
        User user = new User{OpenID = openID};

        // Create a new user model

        // Submit the user to the database repository

        // Update the user model in order to get the UserID, 
        // which is automatically generated from the DB.
        // (you can use LINQ-to-SQL to map your model to the DB)

        return user;
    }

    [ValidateInput(false)]
    private ActionResult Authenticate(string openID, string returnUrl)
    {
        var response = openid.GetResponse();
        if (response == null)
        {
            // Stage 2: user submitting Identifier
            Identifier id;
            if (Identifier.TryParse(openID, out id))
            {
                try
                {
                    return openid.CreateRequest(openID).RedirectingResponse.AsActionResult();
                }
                catch (ProtocolException ex)
                {
                    ModelState.AddModelError("error", "Invalid OpenID.");

                    ModelState.AddModelError("error", ex.Message);
                    return View("LogIn");
                }
            }
            else
            {
                ModelState.AddModelError("error", "Invalid OpenID.");
                return View("LogIn");
            }
        }
        else
        {
            // Stage 3: OpenID Provider sending assertion response
            switch (response.Status)
            {
                case AuthenticationStatus.Authenticated:
                    Session["FriendlyIdentifier"] = response.FriendlyIdentifierForDisplay;
                    FormsAuthentication.SetAuthCookie(response.FriendlyIdentifierForDisplay, true);
                    if (!string.IsNullOrEmpty(returnUrl))
                    {
                        return Redirect(returnUrl);
                    }
                    else
                    {
                        return RedirectToAction("Profile", "User");
                    }
                case AuthenticationStatus.Canceled:
                    ModelState.AddModelError("error", "Authentication canceled at provider.");
                    return View("LogIn");
                case AuthenticationStatus.Failed:
                    ModelState.AddModelError("error", "Authentication failed: " + response.Exception.Message);
                    return View("LogIn");
            }
        }
        return new EmptyResult();
    }
}

3。你需要一个视图:

<%@ Page Language="C#" MasterPageFile="~/Views/Shared/Site.Master" Inherits="System.Web.Mvc.ViewPage<YourProject.Models.User>" %>

<asp:Content ID="loginTitle" ContentPlaceHolderID="TitleContent" runat="server">
    Log in - YourWebSiteName
</asp:Content>
<asp:Content ID="loginContent" ContentPlaceHolderID="MainContent" runat="server">
        <p>
            <%--- If you have a domain, then you should sign up for an affiliate id with MyOpenID or something like that ---%>
            Please log in with your OpenID or <a href="https://www.myopenid.com/signup?affiliate_id=????">create an
                OpenID with myOpenID</a> if you don't have one.
        </p>
        <% 
        string returnURL = HttpUtility.UrlEncode(Request.QueryString["ReturnUrl"]);
        if (returnURL == null)
        {
            returnURL = string.Empty;
        }

        using (Html.BeginForm("LogIn", "User", returnURL))
        {%>
            <%= Html.LabelFor(m => m.OpenID)%>:
            <%= Html.TextBoxFor(m => m.OpenID)%>
            <input type="submit" value="Log in" />
        <% 
        } %>

        <%--- Display Errors ---%>
        <%= Html.ValidationSummary()%>
</asp:Content>

请注意,我没有为您提供 Profile 视图,但这应该很简单,可以弄清楚。

【讨论】:

  • 谢谢你!这是一个很好的答案!我会试试看,如果它有效,你应该把它写到你的博客上,如果你碰巧有的话。希望这得到更多的投票。我必须接受 Oded 的 andwer,因为我已经答应了。
  • @drasto,没问题...我对在 meta 上获得积分没那么感兴趣,而且 Oded 有更多的赞成票。我只是希望这会有所帮助:)
  • @drasto,我为此创建了一篇博文:codesprout.blogspot.com/2011/03/…
  • 谢谢。我相信一旦谷歌找到它,这将对很多人有用:)
【解决方案2】:

StackOverflow 使用DotNetOpenAuth。

来自blog:

但幸运的是,我们与我们使用的开源 DotNetOpenAuth 库的主要作者 Andrew Arnott 进行了一次精彩的对话

【讨论】:

    猜你喜欢
    • 2012-01-25
    • 2014-04-08
    • 2011-02-14
    • 2019-10-03
    • 2014-11-30
    • 2011-01-08
    • 1970-01-01
    • 2011-04-15
    相关资源
    最近更新 更多