Skip to content

Commit 3a8a5c8

Browse files
authored
feat: re-write authentication to rely on a bff that handles the actual authentication (#29)
* feat: re-write authentication to rely on a bff that handles the actual authentication * test: fix playwright test to correctly serve login with included redirectUri * refactor: apply common pattern of redirect + return instead of nesting ifs for the case that no redirect was performed * feat: call HypermediaControl.exitApi if that component is active, otherwise go to main page * refactor: fix build * test: fix hypermedia-control test * feat: call logout on bff endpoint if attempted entrypoint from main or alias pages has an error and user clicks Exit API * refactor: remove not used isAuthenticated stream from auth-client * refactor: remove getSession per entry point change because it is called per navigation already * refactor: cleanup lint errors * refactor: fix test by re-introducing getContentTypeStream to mock and add it to the interface
1 parent 9615555 commit 3a8a5c8

32 files changed

Lines changed: 179 additions & 764 deletions

‎.github/workflows/build-and-publish-angular.yml‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -21,7 +21,7 @@ jobs:
2121
- name: Setup Node.js
2222
uses: actions/setup-node@v2
2323
with:
24-
node-version: '20'
24+
node-version: '24'
2525

2626
- name: Install GitVersion
2727
uses: gittools/actions/gitversion/setup@v3.1.0

‎.run/Playwright E2E.run.xml‎

Lines changed: 10 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,10 @@
1+
<component name="ProjectRunConfigurationManager">
2+
<configuration default="false" name="Playwright E2E" type="JavaScriptTestRunnerPlaywright">
3+
<node-interpreter value="project" />
4+
<playwright-package value="$PROJECT_DIR$/node_modules/@playwright/test" />
5+
<working-dir value="$PROJECT_DIR$" />
6+
<envs />
7+
<scope-kind value="ALL" />
8+
<method v="2" />
9+
</configuration>
10+
</component>

‎README.md‎

Lines changed: 6 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -112,20 +112,18 @@ The exit button on the top left then also returns the user to ``/SomePage`` inst
112112

113113
The following values for ``alias`` will have no effect, since they are already used internally and have precedence over the wildcard route used to implement the alias:
114114
- hui
115-
- auth-redirect
116-
- logout-redirect
117115

118116
## Authentication
119117

120-
The UI supports authentication with an OIDC provider by using the [``oidc-client-ts``](https://www.npmjs.com/package/oidc-client-ts) npm library.
118+
Authentication uses an OAuth 2.1 Backend for Frontend (BFF). The backend owns the authorization-code flow, client secret, token acquisition, and HTTP-only session cookie.
121119

122-
The parameters/formats from [this Microsoft article](https://learn.microsoft.com/en-us/entra/msal/dotnet/advanced/extract-authentication-parameters) are used / asserted.
120+
When an API request returns ``401``, the UI requests ``/bff/session`` on that API's origin. If it returns ``{ "isAuthenticated": false }``, the browser is redirected to ``/bff/login`` on the same origin. After the BFF completes authentication, its cookie is sent with subsequent API requests. The exit button calls ``/bff/logout`` to clear the BFF session.
123121

124-
Upon receiving a ``401`` response from the API with a ``www-authentication`` header starting with "Bearer", the values ``authorization_uri`` and ``client_id`` are extracted. These will be used to make an OIDC call to the authorization uri.<br/>
125-
The redirect uri is given as ``/auth_redirect`` with the current alias (in case of a configured entry point) or hui as the ``path`` parameter, and the current api path as the ``apiPath`` parameter.<br/>
126-
When redirected to ``auth-redirect``, the token is extracted and saved under the site specific settings for the API, and the user is internally redirected to the page they just requested using the ``path`` and ``apiPath`` parameters.
122+
The BFF must allow credentialed cross-origin requests from the UI origin. This CORS policy must apply to successful responses and error responses, including ``401`` responses. It must return ``Access-Control-Allow-Origin`` with the exact UI origin, rather than ``*``, and ``Access-Control-Allow-Credentials: true``. Its preflight response must allow the HTTP methods and request headers used by the UI. Without these headers, browsers hide the backend response and Angular receives a status ``0`` network error instead of the ``401`` required to start BFF login.
127123

128-
The exit button on the top right performs a logout action on top of leaving the API. The user is redirected to the ``/logout-redirect`` page and is able to see if the logout was successful. While the app is open it remembers this, such that when authenticating again, the OIDC provider is prompted to select an account explicitly, preventing an automatic re-login after logout, especially when the user was in a configured EntryPoint which enforces authentication from the start.
124+
For a cross-site BFF cookie, configure it as ``Secure`` and ``SameSite=None``. Browser privacy settings can still block third-party cookies; hosting the UI and BFF on the same site avoids that restriction.
125+
126+
Manually configured global and per-site headers, including an ``Authorization`` header, remain supported.
129127

130128
## Content Preview
131129

‎e2e/hypermedia-ui.spec.ts‎

Lines changed: 39 additions & 21 deletions
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,5 @@
11
import { expect, test } from '@playwright/test';
2+
import { URLPattern } from 'node:url';
23

34
const api = 'https://api.test';
45
const siren = 'application/vnd.siren+json';
@@ -90,12 +91,19 @@ async function installApi(page: import('@playwright/test').Page) {
9091
contentType: 'image/png',
9192
body: Buffer.from('iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAQAAAC1HAwCAAAAC0lEQVR42mNk+A8AAQUBAScY42YAAAAASUVORK5CYII=', 'base64'),
9293
});
93-
case '/protected': return route.fulfill({
94-
status: 401,
95-
headers: {
96-
'www-authenticate': 'Bearer authorization_uri="https://identity.test", client_id="hypermedia-ui"',
97-
'access-control-expose-headers': 'www-authenticate',
98-
},
94+
case '/protected': return route.fulfill({ status: 401 });
95+
case '/forbidden': return route.fulfill({ status: 403 });
96+
case '/bff/session': return route.fulfill({
97+
contentType: 'application/json',
98+
body: JSON.stringify({ isAuthenticated: false }),
99+
});
100+
case '/bff/login': return route.fulfill({
101+
contentType: 'text/html',
102+
body: '<h1>BFF login</h1>',
103+
});
104+
case '/bff/logout': return route.fulfill({
105+
contentType: 'text/html',
106+
body: '<h1>BFF logout</h1>',
99107
});
100108
case '/missing': return route.fulfill({
101109
status: 404,
@@ -279,7 +287,7 @@ test('searches nested properties in the tree', async ({ page }) => {
279287
await expect(page.locator('.match-counter')).toHaveText('1/1');
280288
});
281289

282-
test('navigates with breadcrumbs, exits the API, and recovers from an API error', async ({ page }) => {
290+
test('navigates with breadcrumbs and recovers from an API error', async ({ page }) => {
283291
await openEntryPoint(page);
284292
await page.getByRole('link', { name: 'customer' }).click();
285293
await page.getByRole('link', { name: 'entrypoint' }).click();
@@ -292,7 +300,7 @@ test('navigates with breadcrumbs, exits the API, and recovers from an API error'
292300
await page.getByRole('button', { name: 'Go to entry point' }).click();
293301
await expect(page.getByText('Demo API', { exact: true })).toBeVisible();
294302
await page.getByRole('button', { description: 'Exit API' }).click();
295-
await expect(page.getByPlaceholder('Enter API entrypoint URL')).toBeVisible();
303+
await expect(page).toHaveURL(new URLPattern({ hostname: 'api.test', pathname: '/bff/logout' }));
296304
});
297305

298306
test('uses configured entry points and disables developer controls', async ({ page }) => {
@@ -311,20 +319,30 @@ test('uses configured entry points and disables developer controls', async ({ pa
311319
await expect(page.getByRole('radio', { name: 'Raw' })).toBeHidden();
312320
});
313321

314-
test('redirects to OIDC after a 401 bearer challenge', async ({ page }) => {
315-
await page.route('https://identity.test/**', async route => {
316-
const path = new URL(route.request().url()).pathname;
317-
if (path === '/.well-known/openid-configuration') {
318-
return route.fulfill({ contentType: 'application/json', body: JSON.stringify({
319-
issuer: 'https://identity.test', authorization_endpoint: 'https://identity.test/authorize', token_endpoint: 'https://identity.test/token', jwks_uri: 'https://identity.test/keys',
320-
}) });
321-
}
322-
if (path === '/authorize') return route.fulfill({ contentType: 'text/html', body: '<h1>Identity provider</h1>' });
323-
throw new Error(`Unhandled identity request: ${route.request().url()}`);
324-
});
322+
test('redirects to the BFF login endpoint after an unauthenticated 401', async ({ page }) => {
325323
await page.goto('/');
326324
await page.getByPlaceholder('Enter API entrypoint URL').fill(`${api}/protected`);
327325
await page.getByRole('button', { name: 'Enter API' }).click();
328-
await expect(page).toHaveURL(/https:\/\/identity\.test\/authorize/);
329-
await expect(page.getByRole('heading', { name: 'Identity provider' })).toBeVisible();
326+
await expect(page).toHaveURL(new URLPattern({ hostname: 'api.test', pathname: '/bff/login' }));
327+
const loginUrl = new URL(page.url());
328+
const search = loginUrl.searchParams.get('redirectUri');
329+
expect(search).not.toBeNull();
330+
const redirectUrl = URL.parse(search!);
331+
expect(redirectUrl).not.toBeNull();
332+
expect(redirectUrl!.pathname).toBe("/hui");
333+
const apiPath = redirectUrl!.searchParams.get('apiPath');
334+
expect(apiPath).not.toBeNull();
335+
const apiPathUrl = URL.parse(apiPath!);
336+
expect(apiPathUrl).not.toBeNull();
337+
expect(apiPathUrl!.pathname).toBe("/protected");
338+
await expect(page.getByRole('heading', { name: 'BFF login' })).toBeVisible();
339+
});
340+
341+
test('logs out through the BFF when exiting an API error from the main page', async ({ page }) => {
342+
await page.goto('/');
343+
await page.getByPlaceholder('Enter API entrypoint URL').fill(`${api}/forbidden`);
344+
await page.getByRole('button', { name: 'Enter API' }).click();
345+
await expect(page.getByText('API error', { exact: true })).toBeVisible();
346+
await page.getByRole('button', { name: 'Exit API' }).click();
347+
await expect(page).toHaveURL(new URLPattern({ hostname: 'api.test', pathname: '/bff/logout' }));
330348
});

‎eslint.config.js‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -39,6 +39,7 @@ export default defineConfig([
3939
"caughtErrorsIgnorePattern": "^_"
4040
}
4141
],
42+
'@typescript-eslint/no-inferrable-types': "off",
4243
},
4344
},
4445
{

‎package-lock.json‎

Lines changed: 0 additions & 23 deletions
Some generated files are not rendered by default. Learn more about customizing how changed files appear on GitHub.

‎package.json‎

Lines changed: 0 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -34,12 +34,10 @@
3434
"highlight.js": "^11.10.0",
3535
"immutable": "^5.1.3",
3636
"json-schema": "^0.4.0",
37-
"jwt-decode": "^4.0.0",
3837
"ngx-clipboard": "^16.0.0",
3938
"ngx-dropzone": "^3.1.0",
4039
"ngx-json-viewer": "^3.2.1",
4140
"normalize.css": "^8.0.1",
42-
"oidc-client-ts": "^3.3.0",
4341
"rxjs": "~7.8.1",
4442
"simple-object-query": "^1.6.1",
4543
"zone.js": "^0.15.1"

‎src/app/app.module.ts‎

Lines changed: 0 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -28,14 +28,12 @@ import { MatListModule } from '@angular/material/list';
2828
import { MatTableModule } from '@angular/material/table';
2929
import { MatAutocompleteModule } from '@angular/material/autocomplete';
3030
import { CustomHeadersInterceptor } from './settings/custom-headers.interceptor';
31-
import { AuthRedirectComponent } from './auth-redirect/auth-redirect.component';
3231
import { ProblemDetailsErrorService } from './error-dialog/problem-details-error.service';
3332
import { GlobalNavigationEvents } from './global-navigation.events';
3433
import { AppConfigService } from 'src/app.config.service';
3534
import { Observable } from 'rxjs';
3635
import { importStore } from './store/store-module';
3736
import { AliasPageComponent } from './alias-page/alias-page.component';
38-
import {LogoutRedirectComponent} from "./logout-redirect/logout-redirect.component";
3937
import { ConfirmationDialogComponent } from './common/confirmation-dialog/confirmation-dialog.component';
4038
import {Unit} from "./utils/unit";
4139

@@ -44,14 +42,6 @@ const appRoutes: Routes = [
4442
path: 'hui',
4543
component: HypermediaControlComponent
4644
},
47-
{
48-
path: 'auth-redirect',
49-
component: AuthRedirectComponent
50-
},
51-
{
52-
path: 'logout-redirect',
53-
component: LogoutRedirectComponent
54-
},
5545
{
5646
path: '',
5747
pathMatch: 'full',
@@ -77,7 +67,6 @@ export const myCustomTooltipDefaults: MatTooltipDefaultOptions = {
7767
declarations: [
7868
AppComponent,
7969
MainPageComponent,
80-
AuthRedirectComponent,
8170
ConfirmationDialogComponent
8271
],
8372
imports: [

‎src/app/auth-redirect/auth-redirect.component.css‎

Whitespace-only changes.

‎src/app/auth-redirect/auth-redirect.component.html‎

Whitespace-only changes.

0 commit comments

Comments
 (0)