working onelogin auth implementation

This commit is contained in:
Forrest Waters
2020-10-28 18:23:13 -05:00
parent bda622c223
commit 21e071fa6c
13 changed files with 381 additions and 1 deletions
+8
View File
@@ -232,6 +232,14 @@ auth:
$env: AUTH_MICROSOFT_CLIENT_SECRET
tenantId:
$env: AUTH_MICROSOFT_TENANT_ID
onelogin:
development:
clientId:
$env: AUTH_ONELOGIN_CLIENT_ID
clientSecret:
$env: AUTH_ONELOGIN_CLIENT_SECRET
issuer:
$env: AUTH_ONELOGIN_ISSUER
costInsights:
engineerCost: 200000
products:
+7
View File
@@ -21,6 +21,7 @@ import {
githubAuthApiRef,
samlAuthApiRef,
microsoftAuthApiRef,
oneloginAuthApiRef,
} from '@backstage/core';
export const providers = [
@@ -60,4 +61,10 @@ export const providers = [
message: 'Sign In using SAML',
apiRef: samlAuthApiRef,
},
{
id: 'onelogin-auth-provider',
title: 'OneLogin',
message: 'Sign In using OneLogin',
apiRef: oneloginAuthApiRef,
},
];
@@ -320,3 +320,14 @@ export const samlAuthApiRef: ApiRef<
id: 'core.auth.saml',
description: 'Example of how to use SAML custom provider',
});
export const oneloginAuthApiRef: ApiRef<
OAuthApi &
OpenIdConnectApi &
ProfileInfoApi &
BackstageIdentityApi &
SessionApi
> = createApiRef({
id: 'core.auth.onelogin',
description: 'Provides authentication towards OneLogin APIs and identities',
});
@@ -22,3 +22,4 @@ export * from './okta';
export * from './saml';
export * from './auth0';
export * from './microsoft';
export * from './onelogin';
@@ -0,0 +1,61 @@
/*
* Copyright 2020 Spotify AB
*
* 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 OktaAuth from './OktaAuth';
import MockOAuthApi from '../../OAuthRequestApi/MockOAuthApi';
import { UrlPatternDiscovery } from '../../DiscoveryApi';
const PREFIX = 'okta.';
const getSession = jest.fn();
jest.mock('../../../../lib/AuthSessionManager', () => ({
...(jest.requireActual('../../../../lib/AuthSessionManager') as any),
RefreshingAuthSessionManager: class {
getSession = getSession;
},
}));
describe('OktaAuth', () => {
afterEach(() => {
jest.resetAllMocks();
});
it.each([
['openid', ['openid']],
['profile email', ['profile', 'email']],
[`${PREFIX}groups.manage`, [`${PREFIX}groups.manage`]],
['groups.read', [`${PREFIX}groups.read`]],
[
`${PREFIX}groups.manage groups.read, openid`,
[`${PREFIX}groups.manage`, `${PREFIX}groups.read`, 'openid'],
],
[`email\t ${PREFIX}groups.read`, ['email', `${PREFIX}groups.read`]],
// Some incorrect scopes that we don't try to fix
[`${PREFIX}email`, [`${PREFIX}email`]],
[`${PREFIX}profile`, [`${PREFIX}profile`]],
[`${PREFIX}openid`, [`${PREFIX}openid`]],
])(`should normalize scopes correctly - %p`, (scope, scopes) => {
const auth = OktaAuth.create({
oauthRequestApi: new MockOAuthApi(),
discoveryApi: UrlPatternDiscovery.compile('http://example.com'),
});
auth.getAccessToken(scope);
expect(getSession).toHaveBeenCalledWith({ scopes: new Set(scopes) });
});
});
@@ -0,0 +1,82 @@
/*
* Copyright 2020 Spotify AB
*
* 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 OneLoginIcon from '@material-ui/icons/AcUnit';
import { oneloginAuthApiRef } from '@backstage/core-api/src/apis/definitions/auth';
import {
OAuthRequestApi,
AuthProvider,
DiscoveryApi,
} from '@backstage/core-api/src/apis/definitions';
import { OAuth2 } from '@backstage/core-api/src/apis/implementations/auth/oauth2';
type CreateOptions = {
discoveryApi: DiscoveryApi;
oauthRequestApi: OAuthRequestApi;
environment?: string;
provider?: AuthProvider & { id: string };
};
const DEFAULT_PROVIDER = {
id: 'onelogin',
title: 'onelogin',
icon: OneLoginIcon,
};
const OIDC_SCOPES: Set<String> = new Set([
'openid',
'profile',
'email',
'phone',
'address',
'groups',
'offline_access',
]);
const SCOPE_PREFIX: string = 'onelogin.';
class OneLoginAuth {
static create({
discoveryApi,
environment = 'development',
provider = DEFAULT_PROVIDER,
oauthRequestApi,
}: CreateOptions): typeof oneloginAuthApiRef.T {
return OAuth2.create({
discoveryApi,
oauthRequestApi,
provider,
environment,
defaultScopes: ['openid', 'email', 'profile', 'offline_access'],
scopeTransform(scopes) {
return scopes.map(scope => {
if (OIDC_SCOPES.has(scope)) {
return scope;
}
if (scope.startsWith(SCOPE_PREFIX)) {
return scope;
}
return `${SCOPE_PREFIX}${scope}`;
});
},
});
}
}
export default OneLoginAuth;
@@ -0,0 +1,17 @@
/*
* Copyright 2020 Spotify AB
*
* 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 OneLoginAuth } from './OneLoginAuth';
@@ -44,6 +44,8 @@ import {
UrlPatternDiscovery,
samlAuthApiRef,
SamlAuth,
oneloginAuthApiRef,
OneLoginAuth,
} from '@backstage/core-api';
export const defaultApis = [
@@ -142,4 +144,13 @@ export const defaultApis = [
},
factory: ({ discoveryApi }) => SamlAuth.create({ discoveryApi }),
}),
createApiFactory({
api: oneloginAuthApiRef,
deps: {
discoveryApi: discoveryApiRef,
oauthRequestApi: oauthRequestApiRef,
},
factory: ({ discoveryApi, oauthRequestApi }) =>
OneLoginAuth.create({ discoveryApi, oauthRequestApi }),
}),
];
@@ -116,7 +116,6 @@ export const executeFrameHandlerStrategy = async <T, PrivateInfo = never>(
strategy.redirect = () => {
reject(new Error('Unexpected redirect'));
};
strategy.authenticate(req, {});
},
);
@@ -22,6 +22,7 @@ import { createOktaProvider } from './okta';
import { createSamlProvider } from './saml';
import { createAuth0Provider } from './auth0';
import { createMicrosoftProvider } from './microsoft';
import { createOneLoginProvider } from './onelogin';
import { AuthProviderFactory, AuthProviderFactoryOptions } from './types';
const factories: { [providerId: string]: AuthProviderFactory } = {
@@ -33,6 +34,7 @@ const factories: { [providerId: string]: AuthProviderFactory } = {
auth0: createAuth0Provider,
microsoft: createMicrosoftProvider,
oauth2: createOAuth2Provider,
onelogin: createOneLoginProvider,
};
export function createAuthProvider(
@@ -0,0 +1 @@
export { createOneLoginProvider } from './provider';
@@ -0,0 +1,160 @@
//import { Strategy as OneLoginStrategy } from 'passport-openidconnect';
import { Strategy as OneLoginStrategy } from 'passport-onelogin';
import express from 'express';
import {
OAuthAdapter,
OAuthProviderOptions,
OAuthHandlers,
OAuthResponse,
OAuthEnvironmentHandler,
OAuthStartRequest,
encodeState,
OAuthRefreshRequest,
} from '../../lib/oauth';
import passport from 'passport';
import {
executeFrameHandlerStrategy,
executeRedirectStrategy,
executeRefreshTokenStrategy,
makeProfileInfo,
executeFetchUserProfileStrategy,
PassportDoneCallback,
} from '../../lib/passport';
import { RedirectInfo, AuthProviderFactory } from '../types';
type PrivateInfo = {
refreshToken: string;
};
export type OneLoginProviderOptions = OAuthProviderOptions & {
issuer: string
}
export class OneLoginProvider implements OAuthHandlers {
private readonly _strategy: any;
constructor(options: OneLoginProviderOptions) {
this._strategy = new OneLoginStrategy(
{
issuer: options.issuer,
clientID: options.clientId,
clientSecret: options.clientSecret,
callbackURL: options.callbackUrl,
passReqToCallback: false as true,
},
(
accessToken: any,
refreshToken: any,
params: any,
rawProfile: passport.Profile,
done: PassportDoneCallback<OAuthResponse, PrivateInfo>,
) => {
const profile = makeProfileInfo(rawProfile, params.id_token);
done(
undefined,
{
providerInfo: {
idToken: params.id_token,
accessToken,
scope: params.scope,
//scope: 'profile',
expiresInSeconds: params.expires_in,
},
profile,
},
{
refreshToken,
},
);
},
);
}
async start(req: OAuthStartRequest): Promise<RedirectInfo> {
return await executeRedirectStrategy(req, this._strategy, {
accessType: 'offline',
prompt: 'consent',
scope: 'openid',
state: encodeState(req.state),
});
}
async handler(
req: express.Request,
): Promise<{ response: OAuthResponse; refreshToken: string }> {
const { response, privateInfo } = await executeFrameHandlerStrategy<
OAuthResponse,
PrivateInfo
>(req, this._strategy);
return {
response: await this.populateIdentity(response),
refreshToken: privateInfo.refreshToken,
};
}
async refresh(req: OAuthRefreshRequest): Promise<OAuthResponse> {
const { accessToken, params } = await executeRefreshTokenStrategy(
this._strategy,
req.refreshToken,
req.scope,
);
const profile = await executeFetchUserProfileStrategy(
this._strategy,
accessToken,
params.id_token,
);
return this.populateIdentity({
providerInfo: {
accessToken,
idToken: params.id_token,
expiresInSeconds: params.expires_in,
scope: params.scope,
},
profile,
});
}
private async populateIdentity(
response: OAuthResponse,
): Promise<OAuthResponse> {
const { profile } = response;
if (!profile.email) {
throw new Error('OIDC profile contained no email');
}
const id = profile.email.split('@')[0];
return { ...response, backstageIdentity: { id } };
}
}
export const createOneLoginProvider: AuthProviderFactory = ({
globalConfig,
config,
tokenIssuer,
}) =>
OAuthEnvironmentHandler.mapConfig(config, envConfig => {
const providerId = 'onelogin';
const clientId = envConfig.getString('clientId');
const clientSecret = envConfig.getString('clientSecret');
const issuer = envConfig.getString('issuer');
const callbackUrl = `${globalConfig.baseUrl}/${providerId}/handler/frame`;
const provider = new OneLoginProvider({
clientId,
clientSecret,
callbackUrl,
issuer,
});
return OAuthAdapter.fromConfig(globalConfig, provider, {
disableRefresh: false,
providerId,
tokenIssuer,
});
});
+20
View File
@@ -0,0 +1,20 @@
/*
* Copyright 2020 Spotify AB
*
* 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.
*/
declare module 'passport-openidconnect' {
export class Strategy {
constructor(options: any, verify: any);
}
}