Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save mingyuchoo/9461e4e6f9974a7bd52848408b35c502 to your computer and use it in GitHub Desktop.
Save mingyuchoo/9461e4e6f9974a7bd52848408b35c502 to your computer and use it in GitHub Desktop.
How to connect GitLab and Backstage locally

How to connect GitLab and Backstage locally

Prerequsites

Prepare GitLab server locally

Prepare Backstage locally

  • Before creating Backstage project, install node and yarn first.
  • Create Backstage project.
$ npx @backstage/create-app
Need to install the following packages:
@backstage/create-app@0.5.8
Ok to proceed? (y) y
? Enter a name for the app [required] dev-backstage
$ cd dev-backstage
$ yarn dev
  • Connect to http://localhost:3000 in your web browser.

Set up GitLab

Create application(a.k.a client) for Backstage

  • Login your GitLab as root
  • Avatar > Preferences > Applications > 'Add new application' button
    • Name: dev-backstage
    • Redirect URI: http://localhost:7007/api/auth/gitlab/handler/frame Please refer here
    • Scopes: api, read_api, read_user, read_repository, write_repository, openid, profile, email
  • 'Save application' button
  • Copy Informations
    • 'Application ID': will be used as 'ClientId' in Backstage configuration
    • 'Secret': will be used as 'ClientSecret' in Backstage configuration.
  • 'Continue' button

Ok! Done

Set up Backstage

You should modify at least 3 files to connect GitLab and Backstage

Backstage configurations file

  • Please refer here
  • Edit ${PROJECT_HOME}/app-config.yaml file as show below.
# ...
auth:
  # see https://backstage.io/docs/auth/ to learn about auth providers
  environment: development
  providers:
    gitlab:
      development:
        clientId: ${GITLAB_APPLICATION_ID}
        clientSecret: ${GITLAB_SECRET_OF_APPLICATION}
        audience: http://127.0.0.1:9080 # when run container, use not domain but IP.
# ...

Backstage server file

  • Please refer here
  • Edit ${PROJECT_HOME}/packages/backend/src/plugins/auth.ts file as show below.
// ...

import { stringifyEntityRef, DEFAULT_NAMESPACE } from '@backstage/catalog-model';

export default async function createPlugin(
  env: PluginEnvironment,
): Promise<Router> {
  return await createRouter({
    logger: env.logger,
    config: env.config,
    database: env.database,
    discovery: env.discovery,
    tokenManager: env.tokenManager,
    providerFactories: {
      ...defaultAuthProviderFactories,
      gitlab : providers.gitlab.create({
        signIn: {
          resolver: async ({ profile }, ctx) => {
            if (!profile.email) {
              throw new Error(
                'Login failed, user profile does not contain an email',
              );
            }
            const [localPart, domain] = profile.email.split('@');

            // If your Gitlab user's email domain is diffrent from 'example.com'
            // you should change below.
            if (domain !== 'example.com') {
              throw new Error(
                `Login failed, this email ${profile.email} does not belong to the expected domain`,
              );
            }
            const userEntity = stringifyEntityRef({
              kind: 'User',
              name: localPart,
              namespace: DEFAULT_NAMESPACE,
            });
            return ctx.issueToken({
              claims: {
                sub: userEntity,
                ent: [userEntity],
              },
            });
          },
        },
      }),
    },
  });
}

Backstage client file

  • Please refer here
  • Edit ${PROJECT_HOME}/packages/app/src/App.tsx file as show below.
// ...
const app = createApp({
  components: {
    SignInPage: props => (
      <SignInPage
        {...props}
        provider={{
          id: 'gitlab-auth-provider',
          title: 'GitLb',
          message: 'Sign in using GitLab',
          apiRef: gitlabAuthApiRef,
        }}
      />
    ),
  },
// ...

Check connectivity

  • When you connect to http://localhost:3000 in your web browser, you can see GitLab 'SIGN IN' button.
  • When you click the 'SIGN IN' button, you can see popup window for login.
  • When you type in you credential (id, password) you can login to your local Backstage
@mingyuchoo
Copy link
Author

mingyuchoo commented Dec 23, 2023

Other GitLab examples

// pakcages/backend/src/plugins/auth.ts

gitlab: providers.gitlab.create({
  signIn: {
    async resolver({ result: { fullProfile }}, ctx) {
      return ctx.signInWithCatalogUser({
        entryRef: {
          name: fullProfile.id,
        },
      });
    },
  },
}),

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment