Search code examples
c#.netoauthcallbackvisual-studio-extensions

callback function not working visual studio extension c#


in my extension development, i want to authenticate GItlab to get the accesstoken. I added my redirecturl (might be wrong - unable to find correct redirecturl). Gitlab browser was opening after if i click on authorize callback is not getting (any authorisation code). Please help me on this , im very new to extension development

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}");
        }
    }
}

I tried above code , im expecting like callback showuld work properly & access token i want to get it access token,


Solution

  • The issue seems to be that you are not handling the callback to retrieve the authorization code. In the OAuth flow, after the user authorizes your application, GitLab redirects back to your specified redirect URI with the authorization code appended as a query parameter.

    //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);
    

    in this modification introduces an HttpListener to listen for the callback on the specified redirect URI. After the user authorizes the application on the GitLab site, GitLab will redirect to the specified redirectUri, and the HttpListener will capture the authorization code from the query parameters.