如何在OpenId身份验证后登录用户

问题描述:

如果您不了解OpenId背后的魔法,您将不得不原谅我。在我的流程中;用户从外部站点进行导向并使用OpenId进行验证。他们返回到我的应用程序来创建一个额外的用户名和密码。他们在我的应用程序中注册他们的帐户并登录。如何在OpenId身份验证后登录用户

当他们在注册(外部站点)后从他们的站点启动我的应用程序时,我需要用户自动登录,以遵守OpenId凭据。

我用下面的代码:

internal class ChallengeResult : HttpUnauthorizedResult 
    { 
     public ChallengeResult(string provider, string redirectUri) 
      : this(provider, redirectUri, null) { } 

     public ChallengeResult(string provider, string redirectUri, string userId) 
     { 
      LoginProvider = provider; 
      RedirectUri = redirectUri; 
      UserId = userId; 
     } 

     public string LoginProvider { get; set; } 
     public string RedirectUri { get; set; } 
     public string UserId { get; set; } 

     public override void ExecuteResult(ControllerContext context) 
     { 
      var properties = new AuthenticationProperties { RedirectUri = RedirectUri }; 
      if (UserId != null) 
      { 
       properties.Dictionary[XSRF_KEY] = UserId; 
      } 
      context.HttpContext.GetOwinContext().Authentication.Challenge(properties, LoginProvider); 
     } 

然后重定向到这个功能后:

 var openid = new OpenIdRelyingParty(); 
     var response = openid.GetResponse(); 
     if (response == null) 
     { 
      Identifier id; 
      if (Identifier.TryParse(_identifer, out id)) 
      { 
       try 
       { 
        return openid.CreateRequest(_identifer).RedirectingResponse.AsActionResultMvc5(); 
       } catch (ProtocolException e) 
       { 
        throw new Exception(e.Message); 
       } 
      } 
      return View("Login"); 
     } 
     switch (response.Status) 
     { 
      case AuthenticationStatus.Authenticated: 
       Session["FriendlyIdentifier"] = response.FriendlyIdentifierForDisplay; 
       FormsAuthentication.SetAuthCookie(response.ClaimedIdentifier, false); 
       // Now I need to log in the user 
       break; 
      case AuthenticationStatus.Canceled: 
       break; 
      case AuthenticationStatus.Failed: 
       break; 
     } 

一个响应返回,并从OpenIdRelyingParty身份验证后,我需要登录用户。我是否需要启用表单身份验证才能使其工作?我使用的是MVC Identity 2.0。

这是我在我的public ActionResult ExternalLoginCallback(string returnUrl)方法中的一部分,该方法是从外部OpenId服务器调用的方法(在这种情况下为Intuit,但不应该)。

//Attempt to log the user in if they've already created an account with the external login. 
if (OAuthWebSecurity.Login(result.Provider, result.ProviderUserId, createPersistentCookie: false)) 
{   
    return RedirectToLocal(returnUrl); 
}