You need to enable JavaScript to run this app.
最新活动
大模型
产品
解决方案
定价
生态与合作
支持与服务
开发者
了解我们

求助:如何在C#代码中获取OAuth2.0返回的Access Token?

Got it, let's break this down. Extracting an access token from a callback URL (or even a JSON response, since sometimes OAuth flows return that instead) is a common task in OAuth2 integrations. Here are a few straightforward C# solutions based on your scenario:

1. If you're working in ASP.NET Core (Web Apps/MVC/Razor Pages)

When handling the OAuth callback request directly in your controller, you can pull the access token straight from the query parameters with minimal code:

using Microsoft.AspNetCore.Mvc;

public class OAuthCallbackController : Controller
{
    public IActionResult Index()
    {
        // Grab the access_token from the request's query string
        string accessToken = Request.Query["access_token"];

        if (!string.IsNullOrWhiteSpace(accessToken))
        {
            // Do whatever you need with the token here: store it, use it for API calls, etc.
            return Ok($"Successfully extracted access token: {accessToken}");
        }

        // Handle the case where the token is missing or the callback failed
        return BadRequest("Could not retrieve access token from the callback URL.");
    }
}

2. Manual URL Parsing (for Console/Desktop/Any .NET App)

If you have the callback URL as a string and need to parse it manually, use QueryHelpers (for .NET Core/.NET 5+) or HttpUtility (for .NET Framework) to safely extract the query parameters:

For .NET Core/.NET 5+

using Microsoft.AspNetCore.WebUtilities;
using System;

public static class TokenExtractor
{
    public static string GetAccessTokenFromUrl(string callbackUrl)
    {
        if (Uri.TryCreate(callbackUrl, UriKind.Absolute, out Uri uri))
        {
            // Parse the query string into a key-value collection
            var queryParams = QueryHelpers.ParseQuery(uri.Query);
            
            // Check if the access_token exists and return the first value
            if (queryParams.TryGetValue("access_token", out var tokenValues))
            {
                return tokenValues.FirstOrDefault();
            }
        }

        // Return null or throw an exception based on your error handling preference
        return null;
    }
}

// Usage example
string callbackUrl = "https://yourapp.com/oauth/callback?access_token=eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9...&expires_in=3600";
string accessToken = TokenExtractor.GetAccessTokenFromUrl(callbackUrl);

if (!string.IsNullOrWhiteSpace(accessToken))
{
    Console.WriteLine($"Extracted Access Token: {accessToken}");
}
else
{
    Console.WriteLine("Access token not found in the provided URL.");
}

For .NET Framework

If you're stuck on .NET Framework, use HttpUtility.ParseQueryString from the System.Web assembly:

using System;
using System.Web;

public static string ExtractAccessToken(string callbackUrl)
{
    if (Uri.TryCreate(callbackUrl, UriKind.Absolute, out Uri uri))
    {
        var queryString = HttpUtility.ParseQueryString(uri.Query);
        return queryString["access_token"];
    }

    return null;
}

3. Bonus: If you received a JSON response instead of a URL

Sometimes OAuth2 flows return the token as a JSON payload instead of redirecting to a URL. Here's how to parse that with modern .NET tools:

Using System.Text.Json (.NET Core 3.0+)

using System.Text.Json;

// Define a class to map the JSON response
public class OAuthTokenResponse
{
    [JsonPropertyName("access_token")]
    public string AccessToken { get; set; }

    [JsonPropertyName("token_type")]
    public string TokenType { get; set; }

    [JsonPropertyName("expires_in")]
    public int ExpiresIn { get; set; }
}

// Parse the JSON string
string jsonResponse = "{\"access_token\":\"your-token-here\",\"token_type\":\"Bearer\",\"expires_in\":3600}";
var tokenResponse = JsonSerializer.Deserialize<OAuthTokenResponse>(jsonResponse);
string accessToken = tokenResponse?.AccessToken;

Using Newtonsoft.Json (if you prefer it)

using Newtonsoft.Json;

public class OAuthTokenResponse
{
    [JsonProperty("access_token")]
    public string AccessToken { get; set; }

    [JsonProperty("token_type")]
    public string TokenType { get; set; }

    [JsonProperty("expires_in")]
    public int ExpiresIn { get; set; }
}

string jsonResponse = "{\"access_token\":\"your-token-here\",\"token_type\":\"Bearer\",\"expires_in\":3600}";
var tokenResponse = JsonConvert.DeserializeObject<OAuthTokenResponse>(jsonResponse);
string accessToken = tokenResponse?.AccessToken;

Just a quick note: Always make sure to validate the token and handle edge cases (like missing parameters, invalid URLs, or expired tokens) in your production code!

内容的提问来源于stack exchange,提问作者Akshay SIngh

火山引擎 最新活动