Search code examples
rubygitlab-api

Accessing GitLab via API with Ruby


Trying to access my university's GitLab for the first time via API (I'm the repo owner but have no access to the console and can not edit config files or restart the server), I seem to lack some mandatory basics. Tried to use Ruby (no rails) with the Narkoz API wrapper. Unfortunately, there are no tutorials available which explain the very first step:

How to connect to the server and authenticate using UID+passwd?

Can anybody explain the process in human-readable instructions? The GitLab Manual was not helpful for me.

I hope that I could then figure out how to add GitLab users to my repository. Don't want to add 100 users using the web interface.


Solution

  • The manual entry you linked is for signing into GitLab with a third-party OAuth provider, which doesn't sound like what you're trying to do. What it sounds like you're trying to do is request an OAuth token which you can then use to access GitLab's API.

    From the documentation:

    In this flow, a token is requested in exchange for the resource owner credentials (username and password). The credentials should only be used when there is a high degree of trust between the resource owner and the client (e.g. the client is part of the device operating system or a highly privileged application), and when other authorization grant types are not available (such as an authorization code).

    Which sounds like what you're trying to do.

    One important thing of note from the documentation:

    Deprecation notice: Starting in GitLab 8.11, the Resource Owner Password Credentials has been disabled for users with two-factor authentication turned on. These users can access the API using personal access tokens instead.

    If this is the case for you, the following won't work and you'll need to generate an access token instead.

    1. Requesting access token

    POST request to /oauth/token with parameters:

    {
      "grant_type"    : "password",
      "username"      : "user@example.com",
      "password"      : "secret"
    }
    

    Then, you'll receive the access token back in the response:

    {
      "access_token": "1f0af717251950dbd4d73154fdf0a474a5c5119adad999683f5b450c460726aa",
      "token_type": "bearer",
      "expires_in": 7200
    }
    

    You would then assign this token as your GitLab.private_token.