【问题标题】:oAuth2 RestClient Get token not working even though Postman works即使邮递员工作,oAuth2 RestClient 获取令牌也不起作用
【发布时间】:2021-08-23 23:33:49
【问题描述】:

以下是在 Postman 中成功获取令牌所需的参数。

令牌名称:Sage 访问令牌

授权类型:授权码

回调网址:https://dummyaddress

使用浏览器授权:未勾选

授权网址:https://dummyaddress

访问令牌网址:https://id.sage.com/oauth/token

客户 ID:您的客户 ID

客户端密码:您的客户端密码

范围:openid 个人资料电子邮件offline_access

客户端身份验证:作为基本身份验证标头发送

当我通过代码尝试时,我得到了 UnAuthorized。

        var client = new RestClient("https://id.sage.com/oauth/token");
        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=Authorization_Code&client_id=DxpXMEWXW1oVjn5l4DwRuw9d0bRzpUlG&client_secret=MlUMsZINFBovHODAjmtfG8rO8kjVyiaDYgvfyeg1lmaMArC2ihyd1jh-5u2GyqU&Scope=openid profile email offline_access&Callback_URL=https://customerdataquestuk--sage--c.visualforce.com/apex/SageCode &Auth_URL=https://id.sage.com/authorize?audience=s200ukipd/sage200", ParameterType.RequestBody);
        request.AddParameter("Grant_Type", "Authorization Code");
        request.AddParameter("Callback_URL", "https://dummyaddress");
        request.AddParameter("Auth_URL", "https://dummyaddress");
        request.AddParameter("Client_ID", your client ID);
        request.AddParameter("Client_Secret", your client secret);
        request.AddParameter("Scope", "openid profile email offline_access");
        IRestResponse response = client.Execute(request);

【问题讨论】:

    标签: c# rest-client


    【解决方案1】:

    您的代码中缺少基本身份验证标头,您可以使用以下 C# 代码手动创建基本身份验证标头:

    var credentials = string.Format("{0}:{1}", clientId, clientSecret);
    var headerValue = Convert.ToBase64String(Encoding.UTF8.GetBytes(credentials));
    
    var client = new HttpClient();
    client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Basic", headerValue);
    

    或者如果你是 RestClient

    var client = new RestClient("http://localhost");
    client.Authenticator = new HttpBasicAuthenticator(clientId,clientSecret);
     
    

    请查看此文档Client Authentication

    【讨论】:

      猜你喜欢
      • 2020-09-18
      • 2020-07-09
      • 2021-05-20
      • 1970-01-01
      • 1970-01-01
      • 2021-11-18
      • 1970-01-01
      • 2020-02-25
      • 2018-11-21
      相关资源
      最近更新 更多