DotNetOpenAuth谷歌OAuth2

DotNetOpenAuth谷歌OAuth2,oauth,oauth-2.0,dotnetopenauth,Oauth,Oauth 2.0,Dotnetopenauth,在上一个DotNetOpenAuth包中,GoogleClient扩展了OpenIdClient,有人知道在哪里可以找到google Oauth2的实现,它扩展了DotNetOpenAuth OAuth2Client? 公共类GoogleOAuth2Client:OAuth2Client { #区域常数和字段 /// ///授权端点。 /// 私有常量字符串授权端点=”https://accounts.google.com/o/oauth2/auth"; /// ///令牌终结点。 ///

在上一个DotNetOpenAuth包中,GoogleClient扩展了OpenIdClient,有人知道在哪里可以找到google Oauth2的实现,它扩展了DotNetOpenAuth OAuth2Client?

公共类GoogleOAuth2Client:OAuth2Client
{
#区域常数和字段
/// 
///授权端点。
/// 
私有常量字符串授权端点=”https://accounts.google.com/o/oauth2/auth";
/// 
///令牌终结点。
/// 
私有常量字符串标记端点=”https://accounts.google.com/o/oauth2/token";
/// 
///_应用程序id。
/// 
私有只读字符串\u clientId;
/// 
///应用程序的秘密。
/// 
私有只读字符串_clientSecret;
#端区
public const string provider appendix=“\uuuu provider\uuuuu=google”;
公共GoogleOAuth2Client(string clientId,string clientSecret)
:base(“谷歌”)
{
if(string.IsNullOrWhiteSpace(clientId))抛出新的ArgumentNullException(“clientId”);
if(string.IsNullOrWhiteSpace(clientSecret))抛出新的ArgumentNullException(“clientSecret”);
这个._clientId=clientId;
这个._clientSecret=clientSecret;
}
受保护的覆盖Uri GetServiceLoginUrl(Uri返回URL)
{
StringBuilder serviceUrl=新的StringBuilder();
serviceUrl.AppendFormat(“{0}?scope=https%3A%2F%2Fwww.googleapis.com%2Fauth%2Fuserinfo.email+https%3A%2F%2Fwww.googleapis.com%2Fauth%2Fuserinfo.profile”,AuthorizationEndpoint);
Append(“&state=google”);
AppendFormat(“&redirect_uri={0}”,returnUrl.ToString().ToLower());
Append(“&response_type=code”);
AppendFormat(“&client_id={0}”,_clientId);
返回新的Uri(serviceUrl.ToString());
}
受保护的重写IDictionary GetUserData(字符串accessToken)
{
var client=新的RestClient(“https://www.googleapis.com");
var request=new RestRequest(String.Format(“/oauth2/v1/userinfo?access_token={0}”,accessToken),Method.GET);
IDictionary extraData=新字典();
var response=client.Execute(请求);
if(null!=response.ErrorException)
{
返回null;
}
其他的
{
尝试
{
var json=JObject.Parse(response.Content);
string firstName=(string)json[“给定名称”];
string lastName=(string)json[“family_name”];
字符串emailAddress=(字符串)json[“email”];
字符串id=(字符串)json[“id”];
extraData=新字典
{
{“accesstoken”,accesstoken},
{“name”,String.Format(“{0}{1}”,firstName,lastName)},
{“firstname”,firstname},
{“lastname”,lastname},
{“email”,emailAddress},
{“id”,id}
};
}
捕获(例外情况除外)
{
Ccl.Log.Logging.Error(“从Google请求OAuth用户数据时出错”,例如);
返回null;
}
返回外部数据;
}
}
受保护的覆盖字符串QueryAccessToken(Uri返回URL,字符串授权代码)
{
StringBuilder postData=新建StringBuilder();
AppendFormat(“client_id={0}”,this.\u clientId);
appendData.AppendFormat(“&redirect_uri={0}”,HttpUtility.UrlEncode(returnUrl.ToString().ToLower());
appendData.AppendFormat(“&client\u secret={0}”,this.\u clientSecret);
AppendFormat(“&grant_type={0}”,“授权码”);
AppendFormat(“&code={0}”,authorizationCode);
字符串响应=”;
字符串accessToken=“”;
var webRequest=(HttpWebRequest)webRequest.Create(TokenEndpoint);
webRequest.Method=“POST”;
webRequest.ContentType=“application/x-www-form-urlencoded”;
尝试
{
使用(streams=webRequest.GetRequestStream())
{
使用(StreamWriter sw=新StreamWriter)
Write(postData.ToString());
}
使用(WebResponse WebResponse=webRequest.GetResponse())
{
使用(var reader=newstreamreader(webResponse.GetResponseStream())
{
response=reader.ReadToEnd();
}
}
var json=JObject.Parse(响应);
accessToken=(字符串)json[“访问令牌”];
}
捕获(例外情况除外)
{
Ccl.Log.Logging.Error(“从Google请求OAuth访问令牌时出错”,例如);
返回null;
}
返回accessToken;
}
公共覆盖身份验证结果验证身份验证(HttpContextBase上下文,Uri returnPageUrl)
{
字符串代码=context.Request.QueryString[“code”];
if(string.IsNullOrEmpty(代码))
{
返回AuthenticationResult。失败;
}
string accessToken=this.QueryAccessToken(返回页面URL,代码);
if(accessToken==null)
{
返回AuthenticationResult。失败;
}
IDictionary userData=this.GetUserData(accessToken);
if(userData==null)
{
返回AuthenticationResult。失败;
}
字符串id=userData[“id”];
字符串名;
//某些oAuth提供程序不返回“username”属性的值。
//在这种情况下,请尝试“name”属性。如果该属性仍然不可用,请返回到“id”
如果(!userData.TryGetValue(“用户名”,输出名称)和&!userData.TryGetValue(“名称”,输出名称))
{
姓名=身份证;
}
//将访问令牌添加到用户数据字典中,以防页面开发人员想要使用它
userData[“accesstoken”]=accesstoken;
返回新的AuthenticationRe
public class GoogleOAuth2Client : OAuth2Client
{
    #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 const string ProviderAppendix = "__provider__=google";

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

        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().ToLower());
        serviceUrl.Append("&response_type=code");
        serviceUrl.AppendFormat("&client_id={0}", _clientId);

        return new Uri(serviceUrl.ToString());
    }

    protected override IDictionary<string, string> GetUserData(string accessToken)
    {
        var 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)
            {
                Ccl.Log.Logging.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().ToLower()));
        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 (var reader = new StreamReader(webResponse.GetResponseStream()))
                {
                    response = reader.ReadToEnd();
                }
            }

            var json = JObject.Parse(response);
            accessToken = (string)json["access_token"];
        }
        catch (Exception ex)
        {
            Ccl.Log.Logging.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);
    }
}