You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在C#中使用OAuth 2.0认证令牌调用REST API

使用C#实现OAuth2.0客户端凭证模式调用REST API

Postman 配置参考步骤

  • 进入Authorization选项卡
  • 从Type下拉菜单选择OAuth 2.0
  • 从Add authorization data to下拉菜单选择Request Headers
  • 在Configure New Token区域填写以下信息:
    • Token Name:My OAuth2 token(可自定义名称)
    • Grant Type:Client Credentials
    • Access Token URL:https://service.endpoint.com/api/oauth2/token
    • Client ID:之前生成的Client_Id(示例:ABCD)
    • Client Secret:之前生成的Client_Secret(示例:1234f)
  • 点击Get New Access Token按钮

配置完成后即可使用Bearer令牌发起GET请求,以下是对应的C#实现代码:


C# 实现代码

1. 获取OAuth2.0访问令牌

using System;
using System.Net.Http;
using System.Collections.Generic;
using System.Threading.Tasks;
using System.Net.Http.Json;

public class OAuthTokenService
{
    private readonly HttpClient _httpClient;
    private readonly string _tokenUrl;
    private readonly string _clientId;
    private readonly string _clientSecret;

    public OAuthTokenService(string tokenUrl, string clientId, string clientSecret)
    {
        _httpClient = new HttpClient();
        _tokenUrl = tokenUrl;
        _clientId = clientId;
        _clientSecret = clientSecret;
    }

    public async Task<string> GetAccessTokenAsync()
    {
        var requestData = new Dictionary<string, string>
        {
            { "grant_type", "client_credentials" },
            { "client_id", _clientId },
            { "client_secret", _clientSecret }
        };

        var content = new FormUrlEncodedContent(requestData);
        var response = await _httpClient.PostAsync(_tokenUrl, content);
        
        response.EnsureSuccessStatusCode();
        
        var tokenResponse = await response.Content.ReadFromJsonAsync<TokenResponse>();
        return tokenResponse?.AccessToken ?? throw new InvalidOperationException("获取访问令牌失败");
    }
}

// 适配令牌响应的模型类(根据实际接口返回字段调整)
public class TokenResponse
{
    public string AccessToken { get; set; }
    public string TokenType { get; set; }
    public int ExpiresIn { get; set; }
}

2. 使用访问令牌调用受保护的REST API

public class ApiClient
{
    private readonly HttpClient _httpClient;
    private readonly OAuthTokenService _tokenService;

    public ApiClient(OAuthTokenService tokenService)
    {
        _httpClient = new HttpClient();
        _tokenService = tokenService;
    }

    public async Task<string> CallProtectedApiAsync(string apiUrl)
    {
        var accessToken = await _tokenService.GetAccessTokenAsync();
        
        // 设置Bearer令牌请求头
        _httpClient.DefaultRequestHeaders.Authorization = 
            new System.Net.Http.Headers.AuthenticationHeaderValue("Bearer", accessToken);
        
        var response = await _httpClient.GetAsync(apiUrl);
        response.EnsureSuccessStatusCode();
        
        return await response.Content.ReadAsStringAsync();
    }
}

// 调用示例
class Program
{
    static async Task Main(string[] args)
    {
        var tokenService = new OAuthTokenService(
            tokenUrl: "https://service.endpoint.com/api/oauth2/token",
            clientId: "ABCD",
            clientSecret: "1234f"
        );

        var apiClient = new ApiClient(tokenService);
        try
        {
            var apiResult = await apiClient.CallProtectedApiAsync("https://your-api-endpoint.com/protected-resource");
            Console.WriteLine("API响应结果:");
            Console.WriteLine(apiResult);
        }
        catch (HttpRequestException ex)
        {
            Console.WriteLine("请求出错:" + ex.Message);
        }
    }
}

注意事项

  • 实际项目中建议复用HttpClient实例,避免频繁创建释放造成资源浪费
  • 如果接口返回的令牌字段名称为下划线格式(如access_token),需为TokenResponse类添加JsonProperty特性适配
  • 需确保项目已安装System.Net.Http.Json NuGet包,用于JSON反序列化

内容的提问来源于stack exchange,提问作者Ahsanur Rabbi Rahat

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.31 23:55:23