2012-12-05 51 views
15

我有一个问题,实现谷歌自定义OAuth2Client使用DotNetOpenAuth和MVC4。OAuth2和DotNetOpenAuth - 实施谷歌定制客户端

我已经得到的地步,我可以成功地使授权请求谷歌端点 https://accounts.google.com/o/oauth2/auth

和谷歌询问用户是否允许我到他们的帐户应用访问。迄今为止都很好。当用户点击“确定”时,Google会按照预期调用我的回调URL。

问题是,当我呼吁OAuthWebSecurity类VerifyAuthentication方法(Microsoft.Web.WebPages.OAuth)

var authenticationResult = OAuthWebSecurity.VerifyAuthentication(Url.Action("ExternalLoginCallback", new { ReturnUrl = returnUrl })); 

它总是与IsSuccessful = falseProvider = ""

返回一个AuthenticationResult我已经看了为此,OAuthWebSecurity类尝试获取提供者名称

Request.QueryString["__provider__"] 

但Google不会将这些信息发送回查询字符串。我已经实现的另一个提供商(LinkedIn)正在发送提供者名称,并且这一切都可以正常工作。

我不知道我能做什么从这一点上,除了放弃Microsoft.Web.WebPages.OAuth类,只使用DotNetOpenAuth没有他们,但我希望有人可能有另一种解决方案,我可以尝试..

我已经搜索了很多,但似乎找不到任何帮助...我发现它真的很难,即使只是找到人们做同样的事情的例子,这真的让我感到惊讶。

任何帮助非常感谢!

+0

我从来没有用过MS包装,只是直接写了DotNetOpenAuth并没有太多问题,这样做不是很复杂,他们有很多你可以直接投入的例子。 –

+0

你有没有考虑过向Google提交关于缺少的提供商字符串的错误报告? – weismat

+0

@ PaulTyng - 谢谢,是的 - 这是我最终做的。 – soupy1976

回答

11

更新:马特·约翰逊提到下面,他已经打包了一个解决这个你可以从GitHub获得:https://github.com/mj1856/DotNetOpenAuth.GoogleOAuth2

正如他指出: DNOA和OAuthWebSecurity用于ASP.Net MVC 4只随附一个OpenID Google提供商。这是一个OAuth2客户端,您可以使用它。

重要提示 - 如果您使用的是ASP.Net MVC 5,则此软件包不适用。您应该使用Microsoft.Owin.Security.Google。 (它还附带在VS 2013年5 MVC入门模板)


我得到了这一轮最终通过捕捉请求时,它有,并且做我自己检查,看它已经来到哪个供应商从。谷歌允许你发送一个参数给叫做“状态”的OAuth请求,当他们进行回调时,它们会直接回传给你,所以我使用它来传递Google的提供者名称,然后检查缺少"__provider__"

是这样的:

public String GetProviderNameFromQueryString(NameValueCollection queryString) 
    { 
     var result = queryString["__provider__"]; 

     if (String.IsNullOrWhiteSpace(result)) 
     { 
      result = queryString["state"]; 
     } 

     return result; 
    } 

我则实现了自定义OAuth2Client谷歌,和我手动呼吁该VerifyAuthentication方法我自己,绕过微软的包装材料。

if (provider is GoogleCustomClient) 
     { 
      authenticationResult = ((GoogleCustomClient)provider).VerifyAuthentication(context, new Uri(String.Format("{0}/oauth/ExternalLoginCallback", context.Request.Url.GetLeftPart(UriPartial.Authority).ToString()))); 
     } 
     else 
     { 
      authenticationResult = OAuthWebSecurity.VerifyAuthentication(returnUrl); 
     } 

这让我保留了其他供应商使用微软包装的原有功能。

按照要求通过@ 1010100 1001010,这里是我的谷歌定制OAuth2Client(注:它需要一些整理我还没有得到全面整理把程式码但它不工作,虽然!):

public class GoogleCustomClient : OAuth2Client 
{ 
    ILogger _logger; 

    #region Constants and Fields 

    /// <summary> 
    /// The authorization endpoint. 
    /// </summary> 
    private const string AuthorizationEndpoint = "https://accounts.google.com/o/oauth2/auth"; 

    /// <summary> 
    /// The token endpoint. 
    /// </summary> 
    private const string TokenEndpoint = "https://accounts.google.com/o/oauth2/token"; 

    /// <summary> 
    /// The _app id. 
    /// </summary> 
    private readonly string _clientId; 

    /// <summary> 
    /// The _app secret. 
    /// </summary> 
    private readonly string _clientSecret; 

    #endregion 


    public GoogleCustomClient(string clientId, string clientSecret) 
     : base("Google") 
    { 
     if (string.IsNullOrWhiteSpace(clientId)) throw new ArgumentNullException("clientId"); 
     if (string.IsNullOrWhiteSpace(clientSecret)) throw new ArgumentNullException("clientSecret"); 

     _logger = ObjectFactory.GetInstance<ILogger>(); 

     this._clientId = clientId; 
     this._clientSecret = clientSecret; 
    } 

    protected override Uri GetServiceLoginUrl(Uri returnUrl) 
    { 
     StringBuilder serviceUrl = new StringBuilder(); 

     serviceUrl.AppendFormat("{0}?scope=https%3A%2F%2Fwww.googleapis.com%2Fauth%2Fuserinfo.email+https%3A%2F%2Fwww.googleapis.com%2Fauth%2Fuserinfo.profile", AuthorizationEndpoint); 
     serviceUrl.Append("&state=google"); 
     serviceUrl.AppendFormat("&redirect_uri={0}", returnUrl.ToString()); 
     serviceUrl.Append("&response_type=code"); 
     serviceUrl.AppendFormat("&client_id={0}", _clientId); 

     return new Uri(serviceUrl.ToString()); 

    } 

    protected override IDictionary<string, string> GetUserData(string accessToken) 
    { 
     RestClient client = new RestClient("https://www.googleapis.com"); 
     var request = new RestRequest(String.Format("/oauth2/v1/userinfo?access_token={0}", accessToken), Method.GET); 
     IDictionary<String, String> extraData = new Dictionary<String, String>(); 

     var response = client.Execute(request); 
     if (null != response.ErrorException) 
     { 
      return null; 
     } 
     else 
     { 
      try 
      { 
       var json = JObject.Parse(response.Content); 

       string firstName = (string)json["given_name"]; 
       string lastName = (string)json["family_name"]; 
       string emailAddress = (string)json["email"]; 
       string id = (string)json["id"]; 

       extraData = new Dictionary<String, String> 
       { 
        {"accesstoken", accessToken}, 
        {"name", String.Format("{0} {1}", firstName, lastName)}, 
        {"firstname", firstName}, 
        {"lastname", lastName}, 
        {"email", emailAddress}, 
        {"id", id}           
       }; 
      } 
      catch(Exception ex) 
      { 
       _logger.Error("Error requesting OAuth user data from Google", ex); 
       return null; 
      } 
      return extraData; 
     } 

    } 

    protected override string QueryAccessToken(Uri returnUrl, string authorizationCode) 
    { 
     StringBuilder postData = new StringBuilder(); 
     postData.AppendFormat("client_id={0}", this._clientId); 
     postData.AppendFormat("&redirect_uri={0}", HttpUtility.UrlEncode(returnUrl.ToString())); 
     postData.AppendFormat("&client_secret={0}", this._clientSecret); 
     postData.AppendFormat("&grant_type={0}", "authorization_code"); 
     postData.AppendFormat("&code={0}", authorizationCode); 


     string response = ""; 
     string accessToken = ""; 

     var webRequest = (HttpWebRequest)WebRequest.Create(TokenEndpoint); 

     webRequest.Method = "POST"; 
     webRequest.ContentType = "application/x-www-form-urlencoded"; 

     try 
     { 

      using (Stream s = webRequest.GetRequestStream()) 
      { 
       using (StreamWriter sw = new StreamWriter(s)) 
        sw.Write(postData.ToString()); 
      } 

      using (WebResponse webResponse = webRequest.GetResponse()) 
      { 
       using (StreamReader reader = new StreamReader(webResponse.GetResponseStream())) 
       { 
        response = reader.ReadToEnd(); 
       } 
      } 

      var json = JObject.Parse(response); 
      accessToken = (string)json["access_token"]; 
     } 
     catch(Exception ex) 
     { 
      _logger.Error("Error requesting OAuth access token from Google", ex); 
      return null; 
     } 

     return accessToken; 

    } 

    public override AuthenticationResult VerifyAuthentication(HttpContextBase context, Uri returnPageUrl) 
    { 

     string code = context.Request.QueryString["code"]; 
     if (string.IsNullOrEmpty(code)) 
     { 
      return AuthenticationResult.Failed; 
     } 

     string accessToken = this.QueryAccessToken(returnPageUrl, code); 
     if (accessToken == null) 
     { 
      return AuthenticationResult.Failed; 
     } 

     IDictionary<string, string> userData = this.GetUserData(accessToken); 
     if (userData == null) 
     { 
      return AuthenticationResult.Failed; 
     } 

     string id = userData["id"]; 
     string name; 

     // Some oAuth providers do not return value for the 'username' attribute. 
     // In that case, try the 'name' attribute. If it's still unavailable, fall back to 'id' 
     if (!userData.TryGetValue("username", out name) && !userData.TryGetValue("name", out name)) 
     { 
      name = id; 
     } 

     // add the access token to the user data dictionary just in case page developers want to use it 
     userData["accesstoken"] = accessToken; 

     return new AuthenticationResult(
      isSuccessful: true, provider: this.ProviderName, providerUserId: id, userName: name, extraData: userData); 
    } 
+0

顺便说一句 - 我发现很难找到一个自定义的OAuth2Client的例子,如果任何人想看到我的谷歌实施只是给我一个留言。 – soupy1976

+0

在没有任何其他答案的情况下将此标记为正确,如果有更好的情况出现,我会更新。 – soupy1976

+0

我一直在玩,并试图让它工作得很好。你有什么工作正常,但我不喜欢额外的检查,看看回调是否为谷歌,然后手动检查谷歌OAuth2客户端。我一直在查看DNOA代码,看不到它为什么在注册它的时候在自定义Google客户端上不会调用'VerifyAuthentication()'(你有'OAuthWebSecurity.RegisterClient(...)')有什么运气呢? – Brendan