在我的扩展开发中,我想对 GItlab 进行身份验证以获取访问令牌。我添加了我的重定向网址(可能是错误的 - 无法找到正确的重定向网址)。如果我单击授权回调未获取(任何授权代码),Gitlab 浏览器就会打开。请帮助我,我对扩展开发非常陌生
string gitLabClientId = "237e8qwuidhdhjbadduiqwue8uq8wueu";
string redirectUri = "vs://pb.vsextension";
string authorizationEndpoint = "https://gitlab.com/oauth/authorize";
string state = Guid.NewGuid().ToString("N");
string authorizationCode;
string authorizationUrl = $"{authorizationEndpoint}?client_id={gitLabClientId}&redirect_uri={redirectUri}&state={state}&response_type=code&scope=api+read_user";
Process.Start(new ProcessStartInfo { FileName = authorizationUrl, UseShellExecute = true });
string accessToken = await ExchangeAuthorizationCodeForTokenAsync(authorizationCode, gitLabClientId, redirectUri).ConfigureAwait(true);
static async Task<string> ExchangeAuthorizationCodeForTokenAsync(string code, string clientId, string redirectUri)
{
string gitLabTokenEndpoint = "https://gitlab.com/oauth/token";
using (HttpClient client = new HttpClient())
{
var content = new FormUrlEncodedContent(new[]
{
new KeyValuePair<string, string>("client_id", clientId),
//new KeyValuePair<string, string>("client_secret", "YOUR_GITLAB_CLIENT_SECRET"),
//new KeyValuePair<string, string>("code", code),
new KeyValuePair<string, string>("redirect_uri", redirectUri),
new KeyValuePair<string, string>("grant_type", "refresh_token"),
});
HttpResponseMessage response = await client.PostAsync(gitLabTokenEndpoint, content);
if (response.IsSuccessStatusCode)
{
var result = await response.Content.ReadAsStringAsync(); //ReadAsAsync<AuthenticationResponse>();
return result; //result.AccessToken;
}
else
{
throw new Exception($"Token exchange failed. Status code: {response.StatusCode}");
}
}
}
我尝试了上面的代码,我希望回调显示可以正常工作并且访问令牌我想获取它的访问令牌,
问题似乎是您没有处理回调来检索授权代码。在 OAuth 流程中,用户授权您的应用程序后,GitLab 会重定向回您指定的重定向 URI,并附加授权代码作为查询参数。
//Other variables ....
string authorizationUrl = $"{authorizationEndpoint}?client_id={gitLabClientId}&redirect_uri={redirectUri}&state={state}&response_type=code&scope=api+read_user";
Process.Start(new ProcessStartInfo { FileName = authorizationUrl, UseShellExecute = true });
// Implement a callback mechanism to capture the authorization code
HttpListener listener = new HttpListener();
listener.Prefixes.Add(redirectUri + "/");
listener.Start();
// Wait for the callback and extract the authorization code
HttpListenerContext context = await listener.GetContextAsync();
HttpListenerRequest request = context.Request;
authorizationCode = HttpUtility.ParseQueryString(request.Url.Query).Get("code");
// Close the listener once the authorization code is obtained
listener.Stop();
// Exchange authorization code for an access token
string accessToken = await ExchangeAuthorizationCodeForTokenAsync(authorizationCode, gitLabClientId, redirectUri).ConfigureAwait(true);
在此修改中引入了一个 HttpListener 来侦听指定重定向 URI 上的回调。用户在GitLab站点上对应用程序进行授权后,GitLab将重定向到指定的redirectUri,HttpListener将从查询参数中捕获授权码。