Merge pull request #7570 from rv-ddeloff/atlassian-auth
Atlassian auth provider
This commit is contained in:
@@ -0,0 +1,12 @@
|
||||
---
|
||||
'@backstage/core-app-api': patch
|
||||
'@backstage/core-plugin-api': patch
|
||||
'@backstage/plugin-auth-backend': patch
|
||||
'@backstage/plugin-user-settings': patch
|
||||
---
|
||||
|
||||
Atlassian auth provider
|
||||
|
||||
- AtlassianAuth added to core-app-api
|
||||
- Atlassian provider added to plugin-auth-backend
|
||||
- Updated user-settings with Atlassian connection
|
||||
@@ -8,6 +8,7 @@ apis
|
||||
args
|
||||
asciidoc
|
||||
async
|
||||
Atlassian
|
||||
automations
|
||||
autoscaling
|
||||
Autoscaling
|
||||
|
||||
@@ -364,6 +364,11 @@ auth:
|
||||
development:
|
||||
clientId: ${AUTH_BITBUCKET_CLIENT_ID}
|
||||
clientSecret: ${AUTH_BITBUCKET_CLIENT_SECRET}
|
||||
atlassian:
|
||||
development:
|
||||
clientId: ${AUTH_ATLASSIAN_CLIENT_ID}
|
||||
clientSecret: ${AUTH_ATLASSIAN_CLIENT_SECRET}
|
||||
scopes: ${AUTH_ATLASSIAN_SCOPES}
|
||||
costInsights:
|
||||
engineerCost: 200000
|
||||
products:
|
||||
|
||||
@@ -0,0 +1,64 @@
|
||||
---
|
||||
id: provider
|
||||
title: Atlassian Authentication Provider
|
||||
sidebar_label: Atlassian
|
||||
description: Adding Atlassian as an authentication provider in Backstage
|
||||
---
|
||||
|
||||
The Backstage `core-plugin-api` package comes with an Atlassian authentication
|
||||
provider that can authenticate users using Atlassian products. This auth
|
||||
**only** provides scopes for the following APIs:
|
||||
|
||||
- Confluence API
|
||||
- User REST API
|
||||
- Jira platform REST API
|
||||
- Jira Service Desk API
|
||||
- Personal data reporting API
|
||||
- User identity API
|
||||
|
||||
## Create an OAuth 2.0 (3LO) app in the Atlassian developer console
|
||||
|
||||
To add Atlassian authentication, you must create an OAuth 2.0 (3LO) app.
|
||||
|
||||
Go to `https://developer.atlassian.com/console/myapps/`.
|
||||
|
||||
Click on the drop down `Create`, and choose `OAuth 2.0 integration`.
|
||||
|
||||
Name your integration and click on the `Create` button.
|
||||
|
||||
Settings for local development:
|
||||
|
||||
- Callback URL: `http://localhost:7000/api/auth/atlassian`
|
||||
- Use rotating refresh tokens
|
||||
- For permissions, you **must** enable `View user profile` for the currently
|
||||
logged-in user, under `User identity API`
|
||||
|
||||
## Configuration
|
||||
|
||||
The provider configuration can then be added to your `app-config.yaml` under the
|
||||
root `auth` configuration:
|
||||
|
||||
```yaml
|
||||
auth:
|
||||
environment: development
|
||||
providers:
|
||||
atlassian:
|
||||
development:
|
||||
clientId: ${AUTH_ATLASSIAN_CLIENT_ID}
|
||||
clientSecret: ${AUTH_ATLASSIAN_CLIENT_SECRET}
|
||||
scopes: ${AUTH_ATLASSIAN_SCOPES}
|
||||
```
|
||||
|
||||
The Atlassian provider is a structure with three configuration keys:
|
||||
|
||||
- `clientId`: The Key you generated in the developer console.
|
||||
- `clientSecret`: The Secret tied to the generated Key.
|
||||
- `scopes`: List of scopes the app has permissions for, separated by spaces.
|
||||
|
||||
**NOTE:** the scopes `offline_access` and `read:me` are provided by default.
|
||||
|
||||
## Adding the provider to the Backstage frontend
|
||||
|
||||
To add the provider to the frontend, add the `atlassianAuthApi` reference and
|
||||
`SignInPage` component as shown in
|
||||
[Adding the provider to the sign-in page](../index.md#adding-the-provider-to-the-sign-in-page).
|
||||
@@ -213,6 +213,7 @@
|
||||
"label": "Included providers",
|
||||
"ids": [
|
||||
"auth/auth0/provider",
|
||||
"auth/atlassian/provider",
|
||||
"auth/bitbucket/provider",
|
||||
"auth/microsoft/provider",
|
||||
"auth/github/provider",
|
||||
|
||||
@@ -15,6 +15,7 @@ import { ApiRef } from '@backstage/core-plugin-api';
|
||||
import { AppConfig } from '@backstage/config';
|
||||
import { AppTheme } from '@backstage/core-plugin-api';
|
||||
import { AppThemeApi } from '@backstage/core-plugin-api';
|
||||
import { atlassianAuthApiRef } from '@backstage/core-plugin-api';
|
||||
import { auth0AuthApiRef } from '@backstage/core-plugin-api';
|
||||
import { AuthProvider } from '@backstage/core-plugin-api';
|
||||
import { AuthRequester } from '@backstage/core-plugin-api';
|
||||
@@ -236,12 +237,25 @@ export class AppThemeSelector implements AppThemeApi {
|
||||
setActiveThemeId(themeId?: string): void;
|
||||
}
|
||||
|
||||
// Warning: (ae-missing-release-tag) "AtlassianAuth" is exported by the package, but it is missing a release tag (@alpha, @beta, @public, or @internal)
|
||||
//
|
||||
// @public (undocumented)
|
||||
export class AtlassianAuth {
|
||||
// Warning: (ae-forgotten-export) The symbol "OAuthApiCreateOptions" needs to be exported by the entry point index.d.ts
|
||||
//
|
||||
// (undocumented)
|
||||
static create({
|
||||
discoveryApi,
|
||||
environment,
|
||||
provider,
|
||||
oauthRequestApi,
|
||||
}: OAuthApiCreateOptions): typeof atlassianAuthApiRef.T;
|
||||
}
|
||||
|
||||
// Warning: (ae-missing-release-tag) "Auth0Auth" is exported by the package, but it is missing a release tag (@alpha, @beta, @public, or @internal)
|
||||
//
|
||||
// @public (undocumented)
|
||||
export class Auth0Auth {
|
||||
// Warning: (ae-forgotten-export) The symbol "OAuthApiCreateOptions" needs to be exported by the entry point index.d.ts
|
||||
//
|
||||
// (undocumented)
|
||||
static create({
|
||||
discoveryApi,
|
||||
|
||||
@@ -0,0 +1,44 @@
|
||||
/*
|
||||
* Copyright 2020 The Backstage Authors
|
||||
*
|
||||
* Licensed under the Apache License, Version 2.0 (the "License");
|
||||
* you may not use this file except in compliance with the License.
|
||||
* You may obtain a copy of the License at
|
||||
*
|
||||
* http://www.apache.org/licenses/LICENSE-2.0
|
||||
*
|
||||
* Unless required by applicable law or agreed to in writing, software
|
||||
* distributed under the License is distributed on an "AS IS" BASIS,
|
||||
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
* See the License for the specific language governing permissions and
|
||||
* limitations under the License.
|
||||
*/
|
||||
|
||||
import AtlassianIcon from '@material-ui/icons/AcUnit';
|
||||
import { atlassianAuthApiRef } from '@backstage/core-plugin-api';
|
||||
import { OAuth2 } from '../oauth2';
|
||||
import { OAuthApiCreateOptions } from '../types';
|
||||
|
||||
const DEFAULT_PROVIDER = {
|
||||
id: 'atlassian',
|
||||
title: 'Atlassian',
|
||||
icon: AtlassianIcon,
|
||||
};
|
||||
|
||||
class AtlassianAuth {
|
||||
static create({
|
||||
discoveryApi,
|
||||
environment = 'development',
|
||||
provider = DEFAULT_PROVIDER,
|
||||
oauthRequestApi,
|
||||
}: OAuthApiCreateOptions): typeof atlassianAuthApiRef.T {
|
||||
return OAuth2.create({
|
||||
discoveryApi,
|
||||
oauthRequestApi,
|
||||
provider,
|
||||
environment,
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
export default AtlassianAuth;
|
||||
@@ -0,0 +1,17 @@
|
||||
/*
|
||||
* Copyright 2020 The Backstage Authors
|
||||
*
|
||||
* Licensed under the Apache License, Version 2.0 (the "License");
|
||||
* you may not use this file except in compliance with the License.
|
||||
* You may obtain a copy of the License at
|
||||
*
|
||||
* http://www.apache.org/licenses/LICENSE-2.0
|
||||
*
|
||||
* Unless required by applicable law or agreed to in writing, software
|
||||
* distributed under the License is distributed on an "AS IS" BASIS,
|
||||
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
* See the License for the specific language governing permissions and
|
||||
* limitations under the License.
|
||||
*/
|
||||
|
||||
export { default as AtlassianAuth } from './AtlassianAuth';
|
||||
@@ -24,3 +24,4 @@ export * from './auth0';
|
||||
export * from './microsoft';
|
||||
export * from './onelogin';
|
||||
export * from './bitbucket';
|
||||
export * from './atlassian';
|
||||
|
||||
@@ -33,6 +33,7 @@ import {
|
||||
SamlAuth,
|
||||
OneLoginAuth,
|
||||
UnhandledErrorForwarder,
|
||||
AtlassianAuth,
|
||||
} from '../apis';
|
||||
|
||||
import {
|
||||
@@ -55,6 +56,7 @@ import {
|
||||
oneloginAuthApiRef,
|
||||
oidcAuthApiRef,
|
||||
bitbucketAuthApiRef,
|
||||
atlassianAuthApiRef,
|
||||
} from '@backstage/core-plugin-api';
|
||||
|
||||
import OAuth2Icon from '@material-ui/icons/AcUnit';
|
||||
@@ -244,4 +246,19 @@ export const defaultApis = [
|
||||
environment: configApi.getOptionalString('auth.environment'),
|
||||
}),
|
||||
}),
|
||||
createApiFactory({
|
||||
api: atlassianAuthApiRef,
|
||||
deps: {
|
||||
discoveryApi: discoveryApiRef,
|
||||
oauthRequestApi: oauthRequestApiRef,
|
||||
configApi: configApiRef,
|
||||
},
|
||||
factory: ({ discoveryApi, oauthRequestApi, configApi }) => {
|
||||
return AtlassianAuth.create({
|
||||
discoveryApi,
|
||||
oauthRequestApi,
|
||||
environment: configApi.getOptionalString('auth.environment'),
|
||||
});
|
||||
},
|
||||
}),
|
||||
];
|
||||
|
||||
@@ -211,6 +211,13 @@ export type AppThemeApi = {
|
||||
// @public (undocumented)
|
||||
export const appThemeApiRef: ApiRef<AppThemeApi>;
|
||||
|
||||
// Warning: (ae-missing-release-tag) "atlassianAuthApiRef" is exported by the package, but it is missing a release tag (@alpha, @beta, @public, or @internal)
|
||||
//
|
||||
// @public
|
||||
export const atlassianAuthApiRef: ApiRef<
|
||||
OAuthApi & ProfileInfoApi & BackstageIdentityApi & SessionApi
|
||||
>;
|
||||
|
||||
// Warning: (ae-missing-release-tag) "attachComponentData" is exported by the package, but it is missing a release tag (@alpha, @beta, @public, or @internal)
|
||||
//
|
||||
// @public (undocumented)
|
||||
|
||||
@@ -352,3 +352,15 @@ export const bitbucketAuthApiRef: ApiRef<
|
||||
> = createApiRef({
|
||||
id: 'core.auth.bitbucket',
|
||||
});
|
||||
|
||||
/**
|
||||
* Provides authentication towards Atlassian APIs.
|
||||
*
|
||||
* See https://developer.atlassian.com/cloud/jira/platform/scopes-for-connect-and-oauth-2-3LO-apps/
|
||||
* for a full list of supported scopes.
|
||||
*/
|
||||
export const atlassianAuthApiRef: ApiRef<
|
||||
OAuthApi & ProfileInfoApi & BackstageIdentityApi & SessionApi
|
||||
> = createApiRef({
|
||||
id: 'core.auth.atlassian',
|
||||
});
|
||||
|
||||
@@ -16,6 +16,35 @@ import { PluginEndpointDiscovery } from '@backstage/backend-common';
|
||||
import { Profile } from 'passport';
|
||||
import { UserEntity } from '@backstage/catalog-model';
|
||||
|
||||
// Warning: (ae-missing-release-tag) "AtlassianAuthProvider" is exported by the package, but it is missing a release tag (@alpha, @beta, @public, or @internal)
|
||||
//
|
||||
// @public (undocumented)
|
||||
export class AtlassianAuthProvider implements OAuthHandlers {
|
||||
// Warning: (ae-forgotten-export) The symbol "AtlassianAuthProviderOptions" needs to be exported by the entry point index.d.ts
|
||||
constructor(options: AtlassianAuthProviderOptions);
|
||||
// (undocumented)
|
||||
handler(req: express.Request): Promise<{
|
||||
response: OAuthResponse;
|
||||
refreshToken: string;
|
||||
}>;
|
||||
// (undocumented)
|
||||
refresh(req: OAuthRefreshRequest): Promise<OAuthResponse>;
|
||||
// Warning: (ae-forgotten-export) The symbol "RedirectInfo" needs to be exported by the entry point index.d.ts
|
||||
//
|
||||
// (undocumented)
|
||||
start(req: OAuthStartRequest): Promise<RedirectInfo>;
|
||||
}
|
||||
|
||||
// Warning: (ae-missing-release-tag) "AtlassianProviderOptions" is exported by the package, but it is missing a release tag (@alpha, @beta, @public, or @internal)
|
||||
//
|
||||
// @public (undocumented)
|
||||
export type AtlassianProviderOptions = {
|
||||
authHandler?: AuthHandler<OAuthResult>;
|
||||
signIn?: {
|
||||
resolver: SignInResolver<OAuthResult>;
|
||||
};
|
||||
};
|
||||
|
||||
// Warning: (ae-missing-release-tag) "AuthProviderFactory" is exported by the package, but it is missing a release tag (@alpha, @beta, @public, or @internal)
|
||||
//
|
||||
// @public (undocumented)
|
||||
@@ -146,6 +175,13 @@ export const bitbucketUserIdSignInResolver: SignInResolver<BitbucketOAuthResult>
|
||||
// @public (undocumented)
|
||||
export const bitbucketUsernameSignInResolver: SignInResolver<BitbucketOAuthResult>;
|
||||
|
||||
// Warning: (ae-missing-release-tag) "createAtlassianProvider" is exported by the package, but it is missing a release tag (@alpha, @beta, @public, or @internal)
|
||||
//
|
||||
// @public (undocumented)
|
||||
export const createAtlassianProvider: (
|
||||
options?: AtlassianProviderOptions | undefined,
|
||||
) => AuthProviderFactory;
|
||||
|
||||
// Warning: (ae-missing-release-tag) "createAwsAlbProvider" is exported by the package, but it is missing a release tag (@alpha, @beta, @public, or @internal)
|
||||
//
|
||||
// @public (undocumented)
|
||||
@@ -388,7 +424,6 @@ export interface OAuthHandlers {
|
||||
// Warning: (tsdoc-param-tag-missing-hyphen) The @param block should be followed by a parameter name and then a hyphen
|
||||
// Warning: (tsdoc-param-tag-with-invalid-type) The @param block should not include a JSDoc-style '{type}'
|
||||
// Warning: (tsdoc-param-tag-missing-hyphen) The @param block should be followed by a parameter name and then a hyphen
|
||||
// Warning: (ae-forgotten-export) The symbol "RedirectInfo" needs to be exported by the entry point index.d.ts
|
||||
start(req: OAuthStartRequest): Promise<RedirectInfo>;
|
||||
}
|
||||
|
||||
@@ -544,9 +579,9 @@ export type WebMessageResponse =
|
||||
//
|
||||
// src/identity/types.d.ts:25:5 - (ae-forgotten-export) The symbol "TokenParams" needs to be exported by the entry point index.d.ts
|
||||
// src/identity/types.d.ts:31:9 - (ae-forgotten-export) The symbol "AnyJWK" needs to be exported by the entry point index.d.ts
|
||||
// src/providers/aws-alb/provider.d.ts:77:5 - (ae-forgotten-export) The symbol "AuthHandler" needs to be exported by the entry point index.d.ts
|
||||
// src/providers/atlassian/provider.d.ts:37:5 - (ae-forgotten-export) The symbol "AuthHandler" needs to be exported by the entry point index.d.ts
|
||||
// src/providers/atlassian/provider.d.ts:42:9 - (ae-forgotten-export) The symbol "SignInResolver" needs to be exported by the entry point index.d.ts
|
||||
// src/providers/aws-alb/provider.d.ts:77:5 - (ae-forgotten-export) The symbol "AwsAlbResult" needs to be exported by the entry point index.d.ts
|
||||
// src/providers/aws-alb/provider.d.ts:85:9 - (ae-forgotten-export) The symbol "SignInResolver" needs to be exported by the entry point index.d.ts
|
||||
// src/providers/types.d.ts:99:5 - (ae-forgotten-export) The symbol "AuthProviderConfig" needs to be exported by the entry point index.d.ts
|
||||
// src/providers/types.d.ts:121:8 - (tsdoc-missing-deprecation-message) The @deprecated block must include a deprecation message, e.g. describing the recommended alternative
|
||||
```
|
||||
|
||||
@@ -0,0 +1,21 @@
|
||||
/*
|
||||
* Copyright 2020 The Backstage Authors
|
||||
*
|
||||
* Licensed under the Apache License, Version 2.0 (the "License");
|
||||
* you may not use this file except in compliance with the License.
|
||||
* You may obtain a copy of the License at
|
||||
*
|
||||
* http://www.apache.org/licenses/LICENSE-2.0
|
||||
*
|
||||
* Unless required by applicable law or agreed to in writing, software
|
||||
* distributed under the License is distributed on an "AS IS" BASIS,
|
||||
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
* See the License for the specific language governing permissions and
|
||||
* limitations under the License.
|
||||
*/
|
||||
|
||||
export { createAtlassianProvider } from './provider';
|
||||
export type {
|
||||
AtlassianAuthProvider,
|
||||
AtlassianProviderOptions,
|
||||
} from './provider';
|
||||
@@ -0,0 +1,146 @@
|
||||
/*
|
||||
* Copyright 2020 The Backstage Authors
|
||||
*
|
||||
* Licensed under the Apache License, Version 2.0 (the "License");
|
||||
* you may not use this file except in compliance with the License.
|
||||
* You may obtain a copy of the License at
|
||||
*
|
||||
* http://www.apache.org/licenses/LICENSE-2.0
|
||||
*
|
||||
* Unless required by applicable law or agreed to in writing, software
|
||||
* distributed under the License is distributed on an "AS IS" BASIS,
|
||||
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
* See the License for the specific language governing permissions and
|
||||
* limitations under the License.
|
||||
*/
|
||||
|
||||
import { AtlassianAuthProvider } from './provider';
|
||||
import * as helpers from '../../lib/passport/PassportStrategyHelper';
|
||||
import { getVoidLogger } from '@backstage/backend-common';
|
||||
import { TokenIssuer } from '../../identity';
|
||||
import { CatalogIdentityClient } from '../../lib/catalog';
|
||||
import { OAuthResult } from '../../lib/oauth';
|
||||
import { PassportProfile } from '../../lib/passport/types';
|
||||
|
||||
const mockFrameHandler = jest.spyOn(
|
||||
helpers,
|
||||
'executeFrameHandlerStrategy',
|
||||
) as unknown as jest.MockedFunction<() => Promise<{ result: OAuthResult }>>;
|
||||
|
||||
describe('createAtlassianProvider', () => {
|
||||
const tokenIssuer = {
|
||||
issueToken: jest.fn(),
|
||||
listPublicKeys: jest.fn(),
|
||||
};
|
||||
const catalogIdentityClient = {
|
||||
findUser: jest.fn(),
|
||||
};
|
||||
|
||||
const provider = new AtlassianAuthProvider({
|
||||
logger: getVoidLogger(),
|
||||
catalogIdentityClient:
|
||||
catalogIdentityClient as unknown as CatalogIdentityClient,
|
||||
tokenIssuer: tokenIssuer as unknown as TokenIssuer,
|
||||
authHandler: async ({ fullProfile }) => ({
|
||||
profile: {
|
||||
email: fullProfile.emails![0]!.value,
|
||||
displayName: fullProfile.displayName,
|
||||
picture: 'http://google.com/lols',
|
||||
},
|
||||
}),
|
||||
clientId: 'mock',
|
||||
clientSecret: 'mock',
|
||||
callbackUrl: 'mock',
|
||||
scopes: 'scope',
|
||||
});
|
||||
|
||||
it('should auth', async () => {
|
||||
mockFrameHandler.mockResolvedValueOnce({
|
||||
result: {
|
||||
fullProfile: {
|
||||
photos: [
|
||||
{
|
||||
value:
|
||||
'https://a1cf74336522e87f135f-2f21ace9a6cf0052456644b80fa06d4f.ssl.cf2.rackcdn.com/images/characters_opt/p-mystic-river-sean-penn.jpg',
|
||||
},
|
||||
],
|
||||
emails: [{ value: 'conrad@example.com' }],
|
||||
displayName: 'Conrad',
|
||||
id: 'conrad',
|
||||
provider: 'google',
|
||||
},
|
||||
params: {
|
||||
id_token: 'idToken',
|
||||
scope: 'scope',
|
||||
expires_in: 123,
|
||||
},
|
||||
accessToken: 'accessToken',
|
||||
refreshToken: 'wacka',
|
||||
},
|
||||
});
|
||||
const { response } = await provider.handler({} as any);
|
||||
expect(response).toEqual({
|
||||
providerInfo: {
|
||||
accessToken: 'accessToken',
|
||||
expiresInSeconds: 123,
|
||||
idToken: 'idToken',
|
||||
scope: 'scope',
|
||||
refreshToken: 'wacka',
|
||||
},
|
||||
profile: {
|
||||
email: 'conrad@example.com',
|
||||
displayName: 'Conrad',
|
||||
picture: 'http://google.com/lols',
|
||||
},
|
||||
});
|
||||
});
|
||||
|
||||
it('should forward a new refresh token on refresh', async () => {
|
||||
const mockRefreshToken = jest.spyOn(
|
||||
helpers,
|
||||
'executeRefreshTokenStrategy',
|
||||
) as unknown as jest.MockedFunction<() => Promise<{}>>;
|
||||
|
||||
mockRefreshToken.mockResolvedValueOnce({
|
||||
accessToken: 'a.b.c',
|
||||
refreshToken: 'dont-forget-to-send-refresh',
|
||||
params: {
|
||||
id_token: 'my-id',
|
||||
scope: 'read_user',
|
||||
},
|
||||
});
|
||||
|
||||
const mockUserProfile = jest.spyOn(
|
||||
helpers,
|
||||
'executeFetchUserProfileStrategy',
|
||||
) as unknown as jest.MockedFunction<() => Promise<PassportProfile>>;
|
||||
|
||||
mockUserProfile.mockResolvedValueOnce({
|
||||
id: 'uid-my-id',
|
||||
username: 'mockuser',
|
||||
provider: 'atlassian',
|
||||
displayName: 'Mocked User',
|
||||
emails: [
|
||||
{
|
||||
value: 'mockuser@gmail.com',
|
||||
},
|
||||
],
|
||||
});
|
||||
|
||||
const response = await provider.refresh({} as any);
|
||||
|
||||
expect(response).toEqual({
|
||||
profile: {
|
||||
displayName: 'Mocked User',
|
||||
email: 'mockuser@gmail.com',
|
||||
picture: 'http://google.com/lols',
|
||||
},
|
||||
providerInfo: {
|
||||
accessToken: 'a.b.c',
|
||||
idToken: 'my-id',
|
||||
refreshToken: 'dont-forget-to-send-refresh',
|
||||
scope: 'read_user',
|
||||
},
|
||||
});
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,238 @@
|
||||
/*
|
||||
* Copyright 2020 The Backstage Authors
|
||||
*
|
||||
* Licensed under the Apache License, Version 2.0 (the "License");
|
||||
* you may not use this file except in compliance with the License.
|
||||
* You may obtain a copy of the License at
|
||||
*
|
||||
* http://www.apache.org/licenses/LICENSE-2.0
|
||||
*
|
||||
* Unless required by applicable law or agreed to in writing, software
|
||||
* distributed under the License is distributed on an "AS IS" BASIS,
|
||||
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
* See the License for the specific language governing permissions and
|
||||
* limitations under the License.
|
||||
*/
|
||||
|
||||
import AtlassianStrategy from './strategy';
|
||||
import {
|
||||
encodeState,
|
||||
OAuthAdapter,
|
||||
OAuthEnvironmentHandler,
|
||||
OAuthHandlers,
|
||||
OAuthProviderOptions,
|
||||
OAuthRefreshRequest,
|
||||
OAuthResponse,
|
||||
OAuthResult,
|
||||
OAuthStartRequest,
|
||||
} from '../../lib/oauth';
|
||||
import passport from 'passport';
|
||||
import {
|
||||
executeFetchUserProfileStrategy,
|
||||
executeFrameHandlerStrategy,
|
||||
executeRedirectStrategy,
|
||||
executeRefreshTokenStrategy,
|
||||
makeProfileInfo,
|
||||
PassportDoneCallback,
|
||||
} from '../../lib/passport';
|
||||
import {
|
||||
AuthHandler,
|
||||
AuthProviderFactory,
|
||||
RedirectInfo,
|
||||
SignInResolver,
|
||||
} from '../types';
|
||||
import express from 'express';
|
||||
import { TokenIssuer } from '../../identity';
|
||||
import { CatalogIdentityClient } from '../../lib/catalog';
|
||||
import { Logger } from 'winston';
|
||||
|
||||
export type AtlassianAuthProviderOptions = OAuthProviderOptions & {
|
||||
scopes: string;
|
||||
signInResolver?: SignInResolver<OAuthResult>;
|
||||
authHandler: AuthHandler<OAuthResult>;
|
||||
tokenIssuer: TokenIssuer;
|
||||
catalogIdentityClient: CatalogIdentityClient;
|
||||
logger: Logger;
|
||||
};
|
||||
|
||||
export const atlassianDefaultAuthHandler: AuthHandler<OAuthResult> = async ({
|
||||
fullProfile,
|
||||
params,
|
||||
}) => ({
|
||||
profile: makeProfileInfo(fullProfile, params.id_token),
|
||||
});
|
||||
|
||||
export class AtlassianAuthProvider implements OAuthHandlers {
|
||||
private readonly _strategy: AtlassianStrategy;
|
||||
private readonly signInResolver?: SignInResolver<OAuthResult>;
|
||||
private readonly authHandler: AuthHandler<OAuthResult>;
|
||||
private readonly tokenIssuer: TokenIssuer;
|
||||
private readonly catalogIdentityClient: CatalogIdentityClient;
|
||||
private readonly logger: Logger;
|
||||
|
||||
constructor(options: AtlassianAuthProviderOptions) {
|
||||
this.catalogIdentityClient = options.catalogIdentityClient;
|
||||
this.logger = options.logger;
|
||||
this.tokenIssuer = options.tokenIssuer;
|
||||
this.authHandler = options.authHandler;
|
||||
this.signInResolver = options.signInResolver;
|
||||
|
||||
this._strategy = new AtlassianStrategy(
|
||||
{
|
||||
clientID: options.clientId,
|
||||
clientSecret: options.clientSecret,
|
||||
callbackURL: options.callbackUrl,
|
||||
scope: options.scopes,
|
||||
},
|
||||
(
|
||||
accessToken: any,
|
||||
refreshToken: any,
|
||||
params: any,
|
||||
fullProfile: passport.Profile,
|
||||
done: PassportDoneCallback<OAuthResult>,
|
||||
) => {
|
||||
done(undefined, {
|
||||
fullProfile,
|
||||
accessToken,
|
||||
refreshToken,
|
||||
params,
|
||||
});
|
||||
},
|
||||
);
|
||||
}
|
||||
|
||||
async start(req: OAuthStartRequest): Promise<RedirectInfo> {
|
||||
return await executeRedirectStrategy(req, this._strategy, {
|
||||
state: encodeState(req.state),
|
||||
});
|
||||
}
|
||||
|
||||
async handler(
|
||||
req: express.Request,
|
||||
): Promise<{ response: OAuthResponse; refreshToken: string }> {
|
||||
const { result } = await executeFrameHandlerStrategy<OAuthResult>(
|
||||
req,
|
||||
this._strategy,
|
||||
);
|
||||
|
||||
return {
|
||||
response: await this.handleResult(result),
|
||||
refreshToken: result.refreshToken ?? '',
|
||||
};
|
||||
}
|
||||
|
||||
private async handleResult(result: OAuthResult): Promise<OAuthResponse> {
|
||||
const { profile } = await this.authHandler(result);
|
||||
|
||||
const response: OAuthResponse = {
|
||||
providerInfo: {
|
||||
idToken: result.params.id_token,
|
||||
accessToken: result.accessToken,
|
||||
refreshToken: result.refreshToken,
|
||||
scope: result.params.scope,
|
||||
expiresInSeconds: result.params.expires_in,
|
||||
},
|
||||
profile,
|
||||
};
|
||||
|
||||
if (this.signInResolver) {
|
||||
response.backstageIdentity = await this.signInResolver(
|
||||
{
|
||||
result,
|
||||
profile,
|
||||
},
|
||||
{
|
||||
tokenIssuer: this.tokenIssuer,
|
||||
catalogIdentityClient: this.catalogIdentityClient,
|
||||
logger: this.logger,
|
||||
},
|
||||
);
|
||||
}
|
||||
|
||||
return response;
|
||||
}
|
||||
|
||||
async refresh(req: OAuthRefreshRequest): Promise<OAuthResponse> {
|
||||
const {
|
||||
accessToken,
|
||||
params,
|
||||
refreshToken: newRefreshToken,
|
||||
} = await executeRefreshTokenStrategy(
|
||||
this._strategy,
|
||||
req.refreshToken,
|
||||
req.scope,
|
||||
);
|
||||
|
||||
const fullProfile = await executeFetchUserProfileStrategy(
|
||||
this._strategy,
|
||||
accessToken,
|
||||
);
|
||||
|
||||
return this.handleResult({
|
||||
fullProfile,
|
||||
params,
|
||||
accessToken,
|
||||
refreshToken: newRefreshToken,
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
export type AtlassianProviderOptions = {
|
||||
/**
|
||||
* The profile transformation function used to verify and convert the auth response
|
||||
* into the profile that will be presented to the user.
|
||||
*/
|
||||
authHandler?: AuthHandler<OAuthResult>;
|
||||
|
||||
/**
|
||||
* Configure sign-in for this provider, without it the provider can not be used to sign users in.
|
||||
*/
|
||||
signIn?: {
|
||||
resolver: SignInResolver<OAuthResult>;
|
||||
};
|
||||
};
|
||||
|
||||
export const createAtlassianProvider = (
|
||||
options?: AtlassianProviderOptions,
|
||||
): AuthProviderFactory => {
|
||||
return ({
|
||||
providerId,
|
||||
globalConfig,
|
||||
config,
|
||||
tokenIssuer,
|
||||
catalogApi,
|
||||
logger,
|
||||
}) =>
|
||||
OAuthEnvironmentHandler.mapConfig(config, envConfig => {
|
||||
const clientId = envConfig.getString('clientId');
|
||||
const clientSecret = envConfig.getString('clientSecret');
|
||||
const scopes = envConfig.getString('scopes');
|
||||
const callbackUrl = `${globalConfig.baseUrl}/${providerId}/handler/frame`;
|
||||
|
||||
const catalogIdentityClient = new CatalogIdentityClient({
|
||||
catalogApi,
|
||||
tokenIssuer,
|
||||
});
|
||||
|
||||
const authHandler: AuthHandler<OAuthResult> =
|
||||
options?.authHandler ?? atlassianDefaultAuthHandler;
|
||||
|
||||
const provider = new AtlassianAuthProvider({
|
||||
clientId,
|
||||
clientSecret,
|
||||
scopes,
|
||||
callbackUrl,
|
||||
authHandler,
|
||||
signInResolver: options?.signIn?.resolver,
|
||||
catalogIdentityClient,
|
||||
logger,
|
||||
tokenIssuer,
|
||||
});
|
||||
|
||||
return OAuthAdapter.fromConfig(globalConfig, provider, {
|
||||
disableRefresh: true,
|
||||
providerId,
|
||||
tokenIssuer,
|
||||
});
|
||||
});
|
||||
};
|
||||
@@ -0,0 +1,113 @@
|
||||
/*
|
||||
* Copyright 2020 The Backstage Authors
|
||||
*
|
||||
* Licensed under the Apache License, Version 2.0 (the "License");
|
||||
* you may not use this file except in compliance with the License.
|
||||
* You may obtain a copy of the License at
|
||||
*
|
||||
* http://www.apache.org/licenses/LICENSE-2.0
|
||||
*
|
||||
* Unless required by applicable law or agreed to in writing, software
|
||||
* distributed under the License is distributed on an "AS IS" BASIS,
|
||||
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
* See the License for the specific language governing permissions and
|
||||
* limitations under the License.
|
||||
*/
|
||||
|
||||
import OAuth2Strategy, { InternalOAuthError } from 'passport-oauth2';
|
||||
import { Profile } from 'passport';
|
||||
|
||||
interface ProfileResponse {
|
||||
account_id: string;
|
||||
email: string;
|
||||
name: string;
|
||||
picture: string;
|
||||
nickname: string;
|
||||
}
|
||||
|
||||
interface AtlassianStrategyOptions {
|
||||
clientID: string;
|
||||
clientSecret: string;
|
||||
callbackURL: string;
|
||||
scope: string;
|
||||
}
|
||||
|
||||
const defaultScopes = ['offline_access', 'read:me'];
|
||||
|
||||
export default class AtlassianStrategy extends OAuth2Strategy {
|
||||
private readonly profileURL: string;
|
||||
|
||||
constructor(
|
||||
options: AtlassianStrategyOptions,
|
||||
verify: OAuth2Strategy.VerifyFunction,
|
||||
) {
|
||||
if (!options.scope) {
|
||||
throw new TypeError('Atlassian requires a scope option');
|
||||
}
|
||||
|
||||
const scopes = options.scope.split(' ');
|
||||
|
||||
const optionsWithURLs = {
|
||||
...options,
|
||||
authorizationURL: `https://auth.atlassian.com/authorize`,
|
||||
tokenURL: `https://auth.atlassian.com/oauth/token`,
|
||||
scope: Array.from(new Set([...defaultScopes, ...scopes])),
|
||||
};
|
||||
|
||||
super(optionsWithURLs, verify);
|
||||
this.profileURL = 'https://api.atlassian.com/me';
|
||||
this.name = 'atlassian';
|
||||
|
||||
this._oauth2.useAuthorizationHeaderforGET(true);
|
||||
}
|
||||
|
||||
authorizationParams() {
|
||||
return {
|
||||
audience: 'api.atlassian.com',
|
||||
prompt: 'consent',
|
||||
};
|
||||
}
|
||||
|
||||
userProfile(
|
||||
accessToken: string,
|
||||
done: (err?: Error | null, profile?: any) => void,
|
||||
): void {
|
||||
this._oauth2.get(this.profileURL, accessToken, (err, body) => {
|
||||
if (err) {
|
||||
return done(
|
||||
new InternalOAuthError(
|
||||
'Failed to fetch user profile',
|
||||
err.statusCode,
|
||||
),
|
||||
);
|
||||
}
|
||||
|
||||
if (!body) {
|
||||
return done(
|
||||
new Error('Failed to fetch user profile, body cannot be empty'),
|
||||
);
|
||||
}
|
||||
|
||||
try {
|
||||
const json = typeof body !== 'string' ? body.toString() : body;
|
||||
const profile = AtlassianStrategy.parse(json);
|
||||
return done(null, profile);
|
||||
} catch (e) {
|
||||
return done(new Error('Failed to parse user profile'));
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
static parse(json: string): Profile {
|
||||
const resp = JSON.parse(json) as ProfileResponse;
|
||||
|
||||
return {
|
||||
id: resp.account_id,
|
||||
provider: 'atlassian',
|
||||
username: resp.nickname,
|
||||
displayName: resp.name,
|
||||
emails: [{ value: resp.email }],
|
||||
photos: [{ value: resp.picture }],
|
||||
};
|
||||
}
|
||||
}
|
||||
@@ -27,6 +27,7 @@ import { createOneLoginProvider } from './onelogin';
|
||||
import { AuthProviderFactory } from './types';
|
||||
import { createAwsAlbProvider } from './aws-alb';
|
||||
import { createBitbucketProvider } from './bitbucket';
|
||||
import { createAtlassianProvider } from './atlassian';
|
||||
|
||||
export const factories: { [providerId: string]: AuthProviderFactory } = {
|
||||
google: createGoogleProvider(),
|
||||
@@ -41,4 +42,5 @@ export const factories: { [providerId: string]: AuthProviderFactory } = {
|
||||
onelogin: createOneLoginProvider(),
|
||||
awsalb: createAwsAlbProvider(),
|
||||
bitbucket: createBitbucketProvider(),
|
||||
atlassian: createAtlassianProvider(),
|
||||
};
|
||||
|
||||
@@ -21,6 +21,7 @@ export * from './microsoft';
|
||||
export * from './oauth2';
|
||||
export * from './okta';
|
||||
export * from './bitbucket';
|
||||
export * from './atlassian';
|
||||
export * from './aws-alb';
|
||||
|
||||
export { factories as defaultAuthProviderFactories } from './factories';
|
||||
|
||||
@@ -25,6 +25,7 @@ import {
|
||||
oktaAuthApiRef,
|
||||
microsoftAuthApiRef,
|
||||
bitbucketAuthApiRef,
|
||||
atlassianAuthApiRef,
|
||||
} from '@backstage/core-plugin-api';
|
||||
|
||||
type Props = {
|
||||
@@ -89,6 +90,14 @@ export const DefaultProviderSettings = ({ configuredProviders }: Props) => (
|
||||
icon={Star}
|
||||
/>
|
||||
)}
|
||||
{configuredProviders.includes('atlassian') && (
|
||||
<ProviderSettingsItem
|
||||
title="Atlassian"
|
||||
description="Provides authentication towards Atlassian APIs"
|
||||
apiRef={atlassianAuthApiRef}
|
||||
icon={Star}
|
||||
/>
|
||||
)}
|
||||
{configuredProviders.includes('oauth2') && (
|
||||
<ProviderSettingsItem
|
||||
title="YourOrg"
|
||||
|
||||
Reference in New Issue
Block a user