keycloak-auth-plugin.ts 2.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566
  1. import {
  2. createProxyHandler,
  3. OnVendureBootstrap,
  4. OnVendureClose,
  5. PluginCommonModule,
  6. VendurePlugin,
  7. } from '@vendure/core';
  8. import express from 'express';
  9. import { Server } from 'http';
  10. import path from 'path';
  11. import { KeycloakAuthenticationStrategy } from './keycloak-authentication-strategy';
  12. /**
  13. * A demo plugin which configures an AuthenticationStrategy for a KeyCloak ID server.
  14. *
  15. * Assumes that KeyCloak is running on port 9000, with a realm configured named "myrealm"
  16. * and a client named "vendure".
  17. *
  18. * Add the plugin to the VendureConfig and set the Admin UI `loginUrl` option to
  19. * "http://localhost:3000/keycloak-login".
  20. *
  21. * Video demo of this: https://youtu.be/Tj4kwjNd2nM
  22. */
  23. @VendurePlugin({
  24. imports: [PluginCommonModule],
  25. configuration: (config) => {
  26. config.authOptions.adminAuthenticationStrategy = [
  27. ...config.authOptions.adminAuthenticationStrategy,
  28. new KeycloakAuthenticationStrategy(),
  29. ];
  30. config.apiOptions.middleware.push({
  31. handler: createProxyHandler({
  32. port: 3042,
  33. route: 'keycloak-login',
  34. label: 'Keycloak Login',
  35. basePath: '',
  36. }),
  37. route: 'keycloak-login',
  38. });
  39. return config;
  40. },
  41. })
  42. export class KeycloakAuthPlugin implements OnVendureBootstrap, OnVendureClose {
  43. private staticServer: Server;
  44. onVendureBootstrap() {
  45. // Set up a static express server to serve the demo login page
  46. // from public/index.html.
  47. const app = express();
  48. app.use(express.static(path.join(__dirname, 'public')));
  49. this.staticServer = app.listen(3042);
  50. }
  51. onVendureClose(): void | Promise<void> {
  52. return new Promise((resolve, reject) => {
  53. this.staticServer.close((err) => {
  54. if (err) {
  55. reject(err);
  56. } else {
  57. resolve();
  58. }
  59. });
  60. });
  61. }
  62. }