【问题标题】:How to get an OAuth 2.0 authentication bearer token in C# for Google AutoML?如何在 C# 中为 Google AutoML 获取 OAuth 2.0 身份验证承载令牌?
【发布时间】:2021-05-17 18:18:13
【问题描述】:

以下代码抛出来自谷歌的返回响应,缺少必需的参数:response_type。该错误可能会误导其他内容,或者该值可能是错误的。这是文档:https://cloud.google.com/docs/authentication/#oauth-2.0-clients

var client = new RestClient("https://accounts.google.com/o/oauth2/auth");
var request = new RestRequest(Method.POST);
request.AddHeader("cache-control", "no-cache");
request.AddHeader("content-type", "application/x-www-form-urlencoded");
request.AddParameter("application/x-www-form-urlencoded", "grant_type=client_credentials&client_id=501819637859-6ng1c949htt0admmpa19vm6tfle04jdc.apps.googleusercontent.com&client_secret=nrrIjxFqugLKd24E8xVesA6f", ParameterType.RequestBody);
IRestResponse response = client.Execute(request);

【问题讨论】:

  • 您从哪里获得的那种资助类型?我不确定是否表明您应该发送帖子正文。有什么理由不想使用客户端库?
  • @DaImTo 我刚刚从这个链接中获取了一个 sn-p,其中提到了 grant_type stackoverflow.com/questions/38494279/…,我们遇到了与其他集成代码库冲突的客户端库问题,所以想使用普通的 vanilla c#休息api
  • @SNew 我建议您解决那些“与其他集成代码库的冲突”,而不是尝试以自己的方式解决官方支持的库。这只会导致应用程序中出现错误和可能的安全漏洞。
  • @Xerillio 谢谢,但其中一些集成使用旧的 .net 框架,由于其他限制而无法升级。我假设在没有任何库的情况下应该可以获取 oAuth 2.0 不记名令牌并对 Google API 进行发布调用以获取 JSON 响应。某些时候,如果它只是一个 REST API 调用,那么为 .net 添加谷歌客户端库就太过分了,因为它需要至少 18 个具有整个谷歌套件包装器的 dll 引用。
  • @DaImTo 由于某种原因,我无法根据您的最新回复将您标记为 cmets

标签: c# authentication postman google-oauth google-cloud-automl


【解决方案1】:

是的,您可以编写自己的 Google Oauth2 流程版本。

第一次通话

第一个调用是 HTTP GET,是向用户显示的同意屏幕的链接。

如果这是已安装的应用程序,例如桌面应用程序或控制台应用程序。然后重定向 uri 应该是 urn:ietf:wg:oauth:2.0:oob。

如果你想要多个范围,应该用 空格 分隔,如果你想取回刷新令牌,请添加离线。

GET https://accounts.google.com/o/oauth2/v2/auth?client_id={clientid}&redirect_uri={RedirectURI}&scope={scopes}&response_type=code

第二次通话

第一次调用的响应是一个身份验证代码,此代码需要与谷歌交换。这是一个 HTTP POST

POST https://oauth2.googleapis.com/token
code=4/X9lG6uWd8-MMJPElWggHZRzyFKtp.QubAT_P-GEwePvB8fYmgkJzntDnaiAI&client_id= 

{ClientId}&client_secret={ClientSecret}&redirect_uri={RedirectURI}&grant_type=authorization_code

此调用的发布数据是一个长字符串,请勿尝试解析它。只需将其发布在您的通话正文中即可。内容类型是“application/x-www-form-urlencoded”是正确的;

对该调用的响应将包含一个访问令牌和一个刷新令牌

{
"access_token" : "ya29.1.AADtN_VSBMC2Ga2lhxsTKjVQ_ROco8VbD6h01aj4PcKHLm6qvHbNtn-_BIzXMw",
"token_type" : "Bearer",
"expires_in" : 3600,
"refresh_token" : "1/J-3zPA8XR1o_cXebV9sDKn_f5MTqaFhKFxH-3PUPiJ4"
}

访问令牌将在一小时后过期,因此您需要刷新它,这就是刷新令牌的用途。

刷新访问令牌

下面的调用也是一个 HTTP POST

https://oauth2.googleapis.com/token
client_id={ClientId}&client_secret={ClientSecret}&refresh_token={Refresh token from previous call}&grant_type=refresh_token

工作示例

class Program
    {
        private const string Clientid = "Add yours";
        private const string Secret = "Add yours.";
        
        static async Task  Main(string[] args)
        {
            Console.WriteLine("Hello World!");
            
            Console.WriteLine($"open the following link in your browser window: {Helper.BuildConsentURL(Clientid, new []{ "profile" })}");
            
            Console.WriteLine("Please paste the Authorization code here:");
            var authorizationCode = Console.ReadLine();

            var tokenResponse = await Helper.ExchangeAuthorizationCode(authorizationCode, Clientid, Secret);

            var refreshTokenResponse = await Helper.ExchangeRefreshToken(tokenResponse.refresh_token, Clientid, Secret);

        }
    }

Helper.cs

 public class Helper
    {
        /// <summary>
        /// 
        /// </summary>
        /// <param name="clientId"></param>
        /// <param name="scope">string array of scopes</param>
        /// <param name="redirectUri">leave empty for installed application</param>
        /// <returns></returns>
        public static string BuildConsentURL(string clientId, string[] scope, string redirectUri = null)
        {
            if (string.IsNullOrEmpty(redirectUri))
            {
                redirectUri = "urn:ietf:wg:oauth:2.0:oob"; // for installed application
            }

            return
                $"https://accounts.google.com/o/oauth2/auth?client_id={clientId}&redirect_uri={redirectUri}&scope={string.Join(" ", scope)}&response_type=code";
        }

        private static string BuildAuthorizationCodeRequest(string code, string clientId, string secret,
            string redirectUri)
        {
            return
                $"code={code}&client_id={clientId}&client_secret={secret}&redirect_uri={redirectUri}&grant_type=authorization_code";
        }
        
        private static string BuildRefreshAccessTokenRequest(string refreshToken, string clientId, string secret)
        {
            return
                $"client_id={clientId}&client_secret={secret}&refresh_token={refreshToken}&grant_type=refresh_token";
        }


        private static async Task<AuthResponse> PostMessage(string postData)
        {
            AuthResponse result;

            var client = new HttpClient();
            client.BaseAddress = new Uri("https://accounts.google.com/");
            var request = new HttpRequestMessage(HttpMethod.Post, "o/oauth2/token");
            request.Content = new StringContent(postData, Encoding.UTF8, "application/x-www-form-urlencoded");
            var response = await client.SendAsync(request);
            using (var content = response.Content)
            {
                var json = content.ReadAsStringAsync().Result;
                result = JsonSerializer.Deserialize<AuthResponse>(json);
            }
            return result;
        }


        public static async Task<AuthResponse> ExchangeAuthorizationCode(string code, string clientId, string secret,
            string redirectUri = null)
        {
            var result = new AuthResponse();

            if (string.IsNullOrEmpty(redirectUri))
            {
                redirectUri = "urn:ietf:wg:oauth:2.0:oob"; // for installed application
            }

            var postData = BuildAuthorizationCodeRequest(code, clientId, secret, redirectUri);

            return await PostMessage(postData);
        }
        
        public static async Task<AuthResponse> ExchangeRefreshToken(string refreshToken, string clientId, string secret)
        {
            var postData = BuildRefreshAccessTokenRequest(refreshToken, clientId, secret);

            return await PostMessage(postData);
        }
        
    }

authresonse.cs

  public class AuthResponse
    {
        public string access_token { get; set; }
        public string token_type { get; set; }
        public int expires_in { get; set; }
        public string refresh_token { get; set; }
    }

【讨论】:

  • 很棒的回复,您的文章显示的正是我正在寻找的内容,但第二次调用抛出错误,提示 URL 无效。有关调用和实际测试值,请参阅此文档。 docs.google.com/document/d/…
  • 我用你古老的示例代码试过了,同样的错误。看起来谷歌发生了一些变化...... System.Net.WebException:'远程服务器返回错误:(400)错误请求。'
  • @DalmTo 我尝试了所有端点oauth2.googleapis.com/token、accounts.google.com/o/oauth2/v2/auth,但都没有工作。
  • 试试新的例子。我想知道您的问题是否是 Encoding.UTF8
  • 你不懂。没有人需要更新刷新令牌所用的授权代码。拥有刷新令牌后,您只需要一个授权码,刷新令牌会为您获取访问令牌,您使用访问令牌发出所有请求。为用户保存刷新令牌,您无需再次要求他们授权。尝试阅读此daimto.com/google-developer-console-oauth2
【解决方案2】:

试试这个。

   String client_id = "<OAUTH_client_id >";
            String client_secret = "<OAUTH_client_secret>";

            var BaseAddress = "https://gateway-stage-core.optum.com";
            var httpClient = new HttpClient() { BaseAddress = new Uri(BaseAddress) };


            var creds = $"client_id={client_id}&client_secret={client_secret}&grant_type=client_credentials";
            httpClient.DefaultRequestHeaders.Accept.Clear();
            httpClient.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/x-www-form-urlencoded"));
            var content = new StringContent(creds, Encoding.UTF8, "application/x-www-form-urlencoded");
            var response = httpClient.PostAsync("/auth/oauth2/cached/token", content).Result;
            var jsonContent = response.Content.ReadAsStringAsync().Result;

            var tokenObj = JsonConvert.DeserializeObject<BearerViewModel>(jsonContent);
            var token = tokenObj.access_token;

【讨论】:

    猜你喜欢
    • 2022-03-03
    • 2014-12-24
    • 2021-01-19
    • 2012-02-12
    • 1970-01-01
    • 2018-05-14
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多