The key is to use the OAuth2 Implicit Grant Flow to access the GitLab API from a Pages site. Note that Implicit Grant Flow is generally considered insecure.
Registering the application
The first step – one time only – is to register the application. It appears that any user can do this. Just go to the
/profile/application page and fill out the “Add New Application” form. Note that this creates an instance-wide application entry; it is not limited to the current user, despite appearing under user settings.
- Name Just the name of the application, which is what the users who authorize the application will have to authorize.
- Redirect URI: The URI that GitLab will redirect to after authentication happens; this should be a URL within your Pages site; must be a full URI, including the
- Scopes: There are several checkboxes here, but we’ll use the “API” setting for now.
Once you’ve created the application, grab the application ID; you won’t need the secret for the “implicit” approach.
Permitting a user to access it
To authenticate a user, redirect (or link) to the URL described below:
Since that’s a redirect, we can do it in a link (though a button might be better). We need these values:
- client_id: Also called
APP_ID; this is the ID from the registration above
- redirect_uri: The same URI that is registered with the application (or users will get an error)
- state: Any information you need to have passed back to you in the redirect, such as the page the user was on when they started to sign in. See also “Preventing CSRF attacks” below
- scope: I’m just saying “api” for now but you can enable whichever permissions you want to
Preventing CSRF attacks
From the main Supported OAuth flows section:
OAuth specification advises sending the state parameter with each request to /oauth/authorize. We highly recommended sending a unique value with each request and validate it against the one in the redirect request. This is important in order to prevent CSRF attacks. The state parameter really should have been a requirement in the standard!
This site contains an example!
First, sign in to GitLab using the “Sign In” link in the top right corner, if you haven’t already. Authorize this application to access your GitLab account. Doing so will store the authorization token as a cookie in your browser. You can revoke the permission at any time in your GitLab account or by removing the cookie.
Once you’re signed in, click the button below: