next-auth-heksso 1.1.13 → 2.0.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -1,6 +1,8 @@
1
1
  # Next-Auth config for use with HEKsso (Keycloak)
2
2
 
3
- The rollowing environment variables are required:
3
+ > Version 2 of this package is no longer in CommonJS format, instead it is in ESM format.
4
+
5
+ The following environment variables are required:
4
6
 
5
7
  NEXTAUTH_SECRET
6
8
  NEXTAUTH_URL
@@ -1,8 +1,7 @@
1
1
  import { NextApiRequest, NextApiResponse } from "next";
2
2
  /**
3
3
  * Provides a next api route for performing a federated logout of the user (logs ouf of keycloak)
4
- * @param req NextApiRequest
5
- * @param res NextApiRequest
4
+ * @param logoutPath Post redirect URI
6
5
  * @returns
7
6
  */
8
- export declare function federatedLogout(logoutPath: string): (req: NextApiRequest, res: NextApiResponse) => Promise<NextApiResponse<any> | undefined>;
7
+ export declare function federatedLogout(logoutPath: string): (req: NextApiRequest, res: NextApiResponse) => Promise<void>;
@@ -1,71 +1,34 @@
1
- "use strict";
2
- var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
3
- if (k2 === undefined) k2 = k;
4
- var desc = Object.getOwnPropertyDescriptor(m, k);
5
- if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
6
- desc = { enumerable: true, get: function() { return m[k]; } };
7
- }
8
- Object.defineProperty(o, k2, desc);
9
- }) : (function(o, m, k, k2) {
10
- if (k2 === undefined) k2 = k;
11
- o[k2] = m[k];
12
- }));
13
- var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
14
- Object.defineProperty(o, "default", { enumerable: true, value: v });
15
- }) : function(o, v) {
16
- o["default"] = v;
17
- });
18
- var __importStar = (this && this.__importStar) || function (mod) {
19
- if (mod && mod.__esModule) return mod;
20
- var result = {};
21
- if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k);
22
- __setModuleDefault(result, mod);
23
- return result;
24
- };
25
- var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
26
- function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
27
- return new (P || (P = Promise))(function (resolve, reject) {
28
- function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
29
- function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
30
- function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
31
- step((generator = generator.apply(thisArg, _arguments || [])).next());
32
- });
33
- };
34
- Object.defineProperty(exports, "__esModule", { value: true });
35
- exports.federatedLogout = federatedLogout;
36
- const jwt = __importStar(require("next-auth/jwt"));
1
+ import * as jwt from "next-auth/jwt";
37
2
  /**
38
3
  * Provides a next api route for performing a federated logout of the user (logs ouf of keycloak)
39
- * @param req NextApiRequest
40
- * @param res NextApiRequest
4
+ * @param logoutPath Post redirect URI
41
5
  * @returns
42
6
  */
43
- function federatedLogout(logoutPath) {
44
- return function (req, res) {
45
- return __awaiter(this, void 0, void 0, function* () {
46
- try {
47
- const token = yield jwt.getToken({ req, secret: process.env.NEXTAUTH_SECRET });
48
- if (!token) {
49
- console.warn("No JWT token found when calling /federated-logout endpoint");
50
- return res.redirect(process.env.NEXTAUTH_URL || "");
51
- }
52
- const endsessionURL = `${process.env.KEYCLOAK_ISSUER}/protocol/openid-connect/logout`;
53
- if (token.idToken) {
54
- console.warn("Without an id_token the user won't be redirected back from the IdP after logout.");
55
- const endsessionParams = new URLSearchParams({
56
- id_token_hint: token.idToken,
57
- post_logout_redirect_uri: process.env.NEXTAUTH_URL + logoutPath || ""
58
- });
59
- return res.redirect(`${endsessionURL}?${endsessionParams}`);
60
- }
61
- else {
62
- return res.redirect(`${endsessionURL}`);
63
- }
64
- }
65
- catch (error) {
66
- console.error(error);
7
+ export function federatedLogout(logoutPath) {
8
+ return async function (req, res) {
9
+ try {
10
+ const token = await jwt.getToken({ req, secret: process.env.NEXTAUTH_SECRET });
11
+ if (!token) {
12
+ console.warn("No JWT token found when calling /federated-logout endpoint");
67
13
  res.redirect(process.env.NEXTAUTH_URL || "");
14
+ return;
15
+ }
16
+ const endsessionURL = `${process.env.KEYCLOAK_ISSUER}/protocol/openid-connect/logout`;
17
+ if (token.idToken) {
18
+ const endsessionParams = new URLSearchParams({
19
+ id_token_hint: token.idToken,
20
+ post_logout_redirect_uri: process.env.NEXTAUTH_URL + logoutPath || ""
21
+ });
22
+ res.redirect(`${endsessionURL}?${endsessionParams}`);
23
+ }
24
+ else {
25
+ console.warn("Without an id_token the user won't be redirected back from the IdP after logout.");
26
+ res.redirect(`${endsessionURL}`);
68
27
  }
69
- });
28
+ }
29
+ catch (error) {
30
+ console.error(error);
31
+ res.redirect(process.env.NEXTAUTH_URL || "");
32
+ }
70
33
  };
71
34
  }
package/api/index.d.ts CHANGED
@@ -1,2 +1,2 @@
1
- export * from "./federatedLogout";
2
- export * from "./nextAuthConfig";
1
+ export * from "./federatedLogout.js";
2
+ export * from "./nextAuthConfig.js";
package/api/index.js CHANGED
@@ -1,18 +1,2 @@
1
- "use strict";
2
- var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
3
- if (k2 === undefined) k2 = k;
4
- var desc = Object.getOwnPropertyDescriptor(m, k);
5
- if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
6
- desc = { enumerable: true, get: function() { return m[k]; } };
7
- }
8
- Object.defineProperty(o, k2, desc);
9
- }) : (function(o, m, k, k2) {
10
- if (k2 === undefined) k2 = k;
11
- o[k2] = m[k];
12
- }));
13
- var __exportStar = (this && this.__exportStar) || function(m, exports) {
14
- for (var p in m) if (p !== "default" && !Object.prototype.hasOwnProperty.call(exports, p)) __createBinding(exports, m, p);
15
- };
16
- Object.defineProperty(exports, "__esModule", { value: true });
17
- __exportStar(require("./federatedLogout"), exports);
18
- __exportStar(require("./nextAuthConfig"), exports);
1
+ export * from "./federatedLogout.js";
2
+ export * from "./nextAuthConfig.js";
@@ -1,69 +1,58 @@
1
- "use strict";
2
- var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
3
- function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
4
- return new (P || (P = Promise))(function (resolve, reject) {
5
- function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
6
- function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
7
- function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
8
- step((generator = generator.apply(thisArg, _arguments || [])).next());
9
- });
10
- };
11
- var __importDefault = (this && this.__importDefault) || function (mod) {
12
- return (mod && mod.__esModule) ? mod : { "default": mod };
13
- };
14
- Object.defineProperty(exports, "__esModule", { value: true });
15
- exports.configureAuthOptions = configureAuthOptions;
16
- const keycloak_1 = __importDefault(require("next-auth/providers/keycloak"));
17
- const refreshAccessToken_1 = require("./refreshAccessToken");
1
+ import KeycloakProviderImport from "next-auth/providers/keycloak";
2
+ import { refreshAccessToken } from "./refreshAccessToken.js";
3
+ const KeycloakProvider = typeof KeycloakProviderImport === "object" ? KeycloakProviderImport.default : KeycloakProviderImport;
18
4
  /**
19
5
  * Provides authOptions for next-auth that configures it for use with the typical HEKsso setup
20
6
  */
21
- function configureAuthOptions(options) {
7
+ export function configureAuthOptions(options) {
22
8
  let callbacks = undefined;
23
9
  if (options && "callbacks" in options) {
24
10
  callbacks = options.callbacks;
25
11
  }
26
- return Object.assign(Object.assign({}, options), { secret: process.env.NEXTAUTH_SECRET, providers: [
27
- (0, keycloak_1.default)({
12
+ return {
13
+ secret: process.env.NEXTAUTH_SECRET,
14
+ providers: [
15
+ KeycloakProvider({
28
16
  clientId: process.env.KEYCLOAK_CLIENT_ID || "",
29
17
  clientSecret: process.env.KEYCLOAK_CLIENT_SECRET || "",
30
18
  issuer: process.env.KEYCLOAK_ISSUER, // something like "http://localhost:8080/realms/master"
31
19
  authorization: { params: { scope: "openid email profile roles" } }
32
20
  })
33
- ], callbacks: Object.assign({ jwt(data) {
34
- return __awaiter(this, void 0, void 0, function* () {
35
- var _a, _b;
36
- const hekGroups = (_a = data.profile) === null || _a === void 0 ? void 0 : _a.hekGroups;
37
- // Persist the OAuth access_token to the token right after signin
38
- if (data.account && data.user) {
39
- data.token.idToken = (_b = data.account) === null || _b === void 0 ? void 0 : _b.id_token;
40
- data.token.accessToken = data.account.access_token;
41
- data.token.hekGroups = hekGroups;
42
- data.token.username = data.profile.preferred_username;
43
- if (data.account.expires_at)
44
- data.token.accessTokenExpires = data.account.expires_at * 1000;
45
- data.token.refreshToken = data.account.refresh_token;
46
- return data.token;
47
- }
48
- // Return previous token if the access token has not expired yet
49
- if (Date.now() < data.token.accessTokenExpires) {
50
- return data.token;
51
- }
52
- // Access token has expired, try to update it
53
- return (0, refreshAccessToken_1.refreshAccessToken)(data.token);
54
- });
21
+ ],
22
+ callbacks: {
23
+ async jwt(data) {
24
+ const hekGroups = data.profile?.hekGroups;
25
+ // Persist the OAuth access_token to the token right after signin
26
+ if (data.account && data.user) {
27
+ data.token.idToken = data.account?.id_token;
28
+ data.token.accessToken = data.account.access_token;
29
+ data.token.hekGroups = hekGroups;
30
+ data.token.username = data.profile.preferred_username;
31
+ if (data.account.expires_at)
32
+ data.token.accessTokenExpires = data.account.expires_at * 1000;
33
+ data.token.refreshToken = data.account.refresh_token;
34
+ return data.token;
35
+ }
36
+ // Return previous token if the access token has not expired yet
37
+ if (Date.now() < data.token.accessTokenExpires) {
38
+ return data.token;
39
+ }
40
+ // Access token has expired, try to update it
41
+ return refreshAccessToken(data.token);
55
42
  },
56
- session(_a) {
57
- return __awaiter(this, arguments, void 0, function* ({ session, token }) {
58
- // Send properties to the client, like an access_token from a provider.
59
- const _session = session;
60
- _session.accessToken = token.accessToken;
61
- _session.accessTokenExpires = token.accessTokenExpires;
62
- _session.hekGroups = token.hekGroups || [];
63
- _session.username = token.username;
64
- if (token.error)
65
- _session.error = token.error;
66
- return _session;
67
- });
68
- } }, callbacks) });
43
+ async session({ session, token }) {
44
+ // Send properties to the client, like an access_token from a provider.
45
+ const _session = session;
46
+ _session.accessToken = token.accessToken;
47
+ _session.accessTokenExpires = token.accessTokenExpires;
48
+ _session.hekGroups = token.hekGroups || [];
49
+ _session.username = token.username;
50
+ if (token.error)
51
+ _session.error = token.error;
52
+ return _session;
53
+ },
54
+ ...callbacks
55
+ },
56
+ ...options
57
+ };
69
58
  }
@@ -1,15 +1,3 @@
1
- "use strict";
2
- var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
3
- function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
4
- return new (P || (P = Promise))(function (resolve, reject) {
5
- function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
6
- function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
7
- function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
8
- step((generator = generator.apply(thisArg, _arguments || [])).next());
9
- });
10
- };
11
- Object.defineProperty(exports, "__esModule", { value: true });
12
- exports.refreshAccessToken = refreshAccessToken;
13
1
  /**
14
2
  * Takes a token, and returns a new token with updated
15
3
  * `accessToken` and `accessTokenExpires`. If an error occurs,
@@ -17,33 +5,36 @@ exports.refreshAccessToken = refreshAccessToken;
17
5
  *
18
6
  * This is a utility function and not an API route
19
7
  */
20
- function refreshAccessToken(token) {
21
- return __awaiter(this, void 0, void 0, function* () {
22
- var _a;
23
- try {
24
- const url = process.env.KEYCLOAK_ISSUER + "/protocol/openid-connect/token?";
25
- const response = yield fetch(url, {
26
- headers: {
27
- "Content-Type": "application/x-www-form-urlencoded"
28
- },
29
- method: "POST",
30
- body: new URLSearchParams({
31
- client_id: process.env.KEYCLOAK_CLIENT_ID || "",
32
- client_secret: process.env.KEYCLOAK_CLIENT_SECRET || "",
33
- grant_type: "refresh_token",
34
- refresh_token: token.refreshToken
35
- })
36
- });
37
- const refreshedTokens = yield response.json();
38
- if (!response.ok) {
39
- throw refreshedTokens;
40
- }
41
- return Object.assign(Object.assign({}, token), { accessToken: refreshedTokens.access_token, accessTokenExpires: Date.now() + refreshedTokens.expires_in * 1000, refreshToken: (_a = refreshedTokens.refresh_token) !== null && _a !== void 0 ? _a : token.refreshToken // Fall back to old refresh token
42
- });
8
+ export async function refreshAccessToken(token) {
9
+ try {
10
+ const url = process.env.KEYCLOAK_ISSUER + "/protocol/openid-connect/token?";
11
+ const response = await fetch(url, {
12
+ headers: {
13
+ "Content-Type": "application/x-www-form-urlencoded"
14
+ },
15
+ method: "POST",
16
+ body: new URLSearchParams({
17
+ client_id: process.env.KEYCLOAK_CLIENT_ID || "",
18
+ client_secret: process.env.KEYCLOAK_CLIENT_SECRET || "",
19
+ grant_type: "refresh_token",
20
+ refresh_token: token.refreshToken
21
+ })
22
+ });
23
+ const refreshedTokens = await response.json();
24
+ if (!response.ok) {
25
+ throw refreshedTokens;
43
26
  }
44
- catch (error) {
45
- console.log(error);
46
- return Object.assign(Object.assign({}, token), { error: "RefreshAccessTokenError" });
47
- }
48
- });
27
+ return {
28
+ ...token,
29
+ accessToken: refreshedTokens.access_token,
30
+ accessTokenExpires: Date.now() + refreshedTokens.expires_in * 1000,
31
+ refreshToken: refreshedTokens.refresh_token ?? token.refreshToken // Fall back to old refresh token
32
+ };
33
+ }
34
+ catch (error) {
35
+ return {
36
+ ...token,
37
+ error: "RefreshAccessTokenError"
38
+ };
39
+ }
49
40
  }
package/package.json CHANGED
@@ -5,10 +5,11 @@
5
5
  "email": "contact@voakie.com"
6
6
  },
7
7
  "license": "MIT",
8
- "version": "1.1.13",
8
+ "version": "2.0.1",
9
+ "type": "module",
9
10
  "scripts": {
10
11
  "prepublish": "run-script-os",
11
- "prepublish:default": "rm api/ -rf && rm react/ -rf && tsc",
12
+ "prepublish:default": "rm -rf api/ && rm -rf react/ && tsc",
12
13
  "prepublish:windows": "del /s /q api && del /s /q react",
13
14
  "build": "tsc",
14
15
  "clean": "run-script-os",
@@ -18,18 +19,21 @@
18
19
  "main": "api/index.js",
19
20
  "types": "api/index.d.ts",
20
21
  "dependencies": {
21
- "@types/node": "^22.8.1",
22
- "@types/react": "^18.3.12",
23
- "@types/react-dom": "^18.3.1",
22
+
23
+ },
24
+ "devDependencies": {
25
+ "run-script-os": "^1.1.6",
26
+ "@types/node": "^24",
27
+ "@types/react": "^19",
28
+ "@types/react-dom": "^19",
24
29
  "eslint": "^9.13.0",
25
- "eslint-config-next": "^15.0.1",
26
- "next": "^15.0.1",
27
- "next-auth": "^4.24.10",
28
- "react": "^18.3.1",
29
- "react-dom": "^18.3.1",
30
+ "eslint-config-next": "^16",
30
31
  "typescript": "^5.6.3"
31
32
  },
32
- "devDependencies": {
33
- "run-script-os": "^1.1.6"
33
+ "peerDependencies": {
34
+ "next": "^15 || ^16",
35
+ "next-auth": "^4",
36
+ "react": "^18 || ^19",
37
+ "react-dom": "^18 || ^19"
34
38
  }
35
39
  }
@@ -1,71 +1,32 @@
1
- "use strict";
2
- var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
3
- if (k2 === undefined) k2 = k;
4
- var desc = Object.getOwnPropertyDescriptor(m, k);
5
- if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
6
- desc = { enumerable: true, get: function() { return m[k]; } };
7
- }
8
- Object.defineProperty(o, k2, desc);
9
- }) : (function(o, m, k, k2) {
10
- if (k2 === undefined) k2 = k;
11
- o[k2] = m[k];
12
- }));
13
- var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
14
- Object.defineProperty(o, "default", { enumerable: true, value: v });
15
- }) : function(o, v) {
16
- o["default"] = v;
17
- });
18
- var __importStar = (this && this.__importStar) || function (mod) {
19
- if (mod && mod.__esModule) return mod;
20
- var result = {};
21
- if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k);
22
- __setModuleDefault(result, mod);
23
- return result;
24
- };
25
- var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
26
- function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
27
- return new (P || (P = Promise))(function (resolve, reject) {
28
- function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
29
- function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
30
- function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
31
- step((generator = generator.apply(thisArg, _arguments || [])).next());
32
- });
33
- };
34
- Object.defineProperty(exports, "__esModule", { value: true });
35
- exports.KeycloakSessionContext = void 0;
36
- exports.useKeycloakSession = useKeycloakSession;
37
- exports.KeycloakSessionProvider = KeycloakSessionProvider;
38
- const react_1 = __importStar(require("react"));
39
- exports.KeycloakSessionContext = (0, react_1.createContext)({
1
+ import React, { Component, createContext, useContext } from "react";
2
+ export const KeycloakSessionContext = createContext({
40
3
  accessTokenError: false,
41
- getAccessToken: () => __awaiter(void 0, void 0, void 0, function* () {
4
+ getAccessToken: async () => {
42
5
  return "";
43
- })
6
+ }
44
7
  });
45
- function useKeycloakSession() {
46
- return (0, react_1.useContext)(exports.KeycloakSessionContext);
8
+ export function useKeycloakSession() {
9
+ return useContext(KeycloakSessionContext);
47
10
  }
48
- function refreshAccessToken() {
49
- return __awaiter(this, void 0, void 0, function* () {
50
- try {
51
- const response = yield fetch("/api/auth/session", {
52
- method: "GET",
53
- headers: {
54
- "Content-Type": "application/json"
55
- }
56
- });
57
- const data = yield response.json();
58
- if (data.error) {
59
- console.error(data.error);
60
- return undefined;
11
+ async function refreshAccessToken() {
12
+ try {
13
+ const response = await fetch("/api/auth/session", {
14
+ method: "GET",
15
+ headers: {
16
+ "Content-Type": "application/json"
61
17
  }
62
- return { accessToken: data.accessToken, accessTokenExpires: data.accessTokenExpires };
63
- }
64
- catch (e) {
65
- console.error(e);
18
+ });
19
+ const data = await response.json();
20
+ if (data.error) {
21
+ console.error(data.error);
66
22
  return undefined;
67
23
  }
68
- });
24
+ return { accessToken: data.accessToken, accessTokenExpires: data.accessTokenExpires };
25
+ }
26
+ catch (e) {
27
+ console.error(e);
28
+ return undefined;
29
+ }
69
30
  }
70
31
  /**
71
32
  * Provider for the useKeycloakSession react hook. Has to directly hook into next-auth and next/router
@@ -75,11 +36,12 @@ function refreshAccessToken() {
75
36
  * @param children
76
37
  * @constructor
77
38
  */
78
- function KeycloakSessionProvider({ session, signOut, children }) {
79
- return (react_1.default.createElement(_KeycloakSessionProvider, { session: session, signOut: signOut }, children));
39
+ export function KeycloakSessionProvider({ session, signOut, children }) {
40
+ return (React.createElement(_KeycloakSessionProvider, { session: session, signOut: signOut }, children));
80
41
  }
81
42
  // Proxy class component to prevent unnecessary re-renders
82
- class _KeycloakSessionProvider extends react_1.Component {
43
+ class _KeycloakSessionProvider extends Component {
44
+ contextValue;
83
45
  constructor(props) {
84
46
  super(props);
85
47
  this.state = {
@@ -101,39 +63,37 @@ class _KeycloakSessionProvider extends react_1.Component {
101
63
  }
102
64
  return this.contextValue;
103
65
  }
104
- getAccessToken() {
105
- return __awaiter(this, void 0, void 0, function* () {
106
- if (!this.state.accessToken ||
107
- (this.state.accessTokenExpires && Date.now() >= this.state.accessTokenExpires)) {
108
- try {
109
- const refreshed = yield refreshAccessToken();
110
- if (refreshed) {
111
- this.setState({
112
- accessTokenError: false,
113
- accessToken: refreshed.accessToken,
114
- accessTokenExpires: refreshed.accessTokenExpires
115
- });
116
- return refreshed.accessToken;
117
- }
118
- else {
119
- // Refresh failed due to network error
120
- return undefined;
121
- }
122
- }
123
- catch (e) {
124
- // Refresh failed because keycloak denied the request
125
- console.error(e);
66
+ async getAccessToken() {
67
+ if (!this.state.accessToken ||
68
+ (this.state.accessTokenExpires && Date.now() >= this.state.accessTokenExpires)) {
69
+ try {
70
+ const refreshed = await refreshAccessToken();
71
+ if (refreshed) {
126
72
  this.setState({
127
- accessTokenError: true,
128
- accessToken: undefined,
129
- accessTokenExpires: undefined
73
+ accessTokenError: false,
74
+ accessToken: refreshed.accessToken,
75
+ accessTokenExpires: refreshed.accessTokenExpires
130
76
  });
77
+ return refreshed.accessToken;
78
+ }
79
+ else {
80
+ // Refresh failed due to network error
131
81
  return undefined;
132
82
  }
133
83
  }
134
- else
135
- return this.state.accessToken;
136
- });
84
+ catch (e) {
85
+ // Refresh failed because keycloak denied the request
86
+ console.error(e);
87
+ this.setState({
88
+ accessTokenError: true,
89
+ accessToken: undefined,
90
+ accessTokenExpires: undefined
91
+ });
92
+ return undefined;
93
+ }
94
+ }
95
+ else
96
+ return this.state.accessToken;
137
97
  }
138
98
  componentDidUpdate() {
139
99
  if (sessionDataGuard(this.props.session.data)) {
@@ -157,7 +117,7 @@ class _KeycloakSessionProvider extends react_1.Component {
157
117
  }
158
118
  }
159
119
  render() {
160
- return (react_1.default.createElement(exports.KeycloakSessionContext.Provider, { value: this.getContextValue() }, this.props.children));
120
+ return (React.createElement(KeycloakSessionContext.Provider, { value: this.getContextValue() }, this.props.children));
161
121
  }
162
122
  }
163
123
  function sessionDataGuard(sessionData) {
package/react/index.d.ts CHANGED
@@ -1 +1 @@
1
- export * from "./KeycloakSessionContext";
1
+ export * from "./KeycloakSessionContext.js";
package/react/index.js CHANGED
@@ -1,17 +1 @@
1
- "use strict";
2
- var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
3
- if (k2 === undefined) k2 = k;
4
- var desc = Object.getOwnPropertyDescriptor(m, k);
5
- if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
6
- desc = { enumerable: true, get: function() { return m[k]; } };
7
- }
8
- Object.defineProperty(o, k2, desc);
9
- }) : (function(o, m, k, k2) {
10
- if (k2 === undefined) k2 = k;
11
- o[k2] = m[k];
12
- }));
13
- var __exportStar = (this && this.__exportStar) || function(m, exports) {
14
- for (var p in m) if (p !== "default" && !Object.prototype.hasOwnProperty.call(exports, p)) __createBinding(exports, m, p);
15
- };
16
- Object.defineProperty(exports, "__esModule", { value: true });
17
- __exportStar(require("./KeycloakSessionContext"), exports);
1
+ export * from "./KeycloakSessionContext.js";
package/.eslintrc.json DELETED
@@ -1,3 +0,0 @@
1
- {
2
- "extends": "next/core-web-vitals"
3
- }
@@ -1,40 +0,0 @@
1
- // /api/auth/federated-logout
2
- import { NextApiRequest, NextApiResponse } from "next"
3
- import * as jwt from "next-auth/jwt"
4
-
5
- /**
6
- * Provides a next api route for performing a federated logout of the user (logs ouf of keycloak)
7
- * @param req NextApiRequest
8
- * @param res NextApiRequest
9
- * @returns
10
- */
11
- export function federatedLogout(logoutPath: string) {
12
- return async function (req: NextApiRequest, res: NextApiResponse) {
13
- try {
14
- const token = await jwt.getToken({ req, secret: process.env.NEXTAUTH_SECRET })
15
- if (!token) {
16
- console.warn("No JWT token found when calling /federated-logout endpoint")
17
- return res.redirect(process.env.NEXTAUTH_URL || "")
18
- }
19
-
20
- const endsessionURL = `${process.env.KEYCLOAK_ISSUER}/protocol/openid-connect/logout`
21
-
22
- if (token.idToken) {
23
- console.warn(
24
- "Without an id_token the user won't be redirected back from the IdP after logout."
25
- )
26
-
27
- const endsessionParams = new URLSearchParams({
28
- id_token_hint: token.idToken as string,
29
- post_logout_redirect_uri: process.env.NEXTAUTH_URL + logoutPath || ""
30
- })
31
- return res.redirect(`${endsessionURL}?${endsessionParams}`)
32
- } else {
33
- return res.redirect(`${endsessionURL}`)
34
- }
35
- } catch (error) {
36
- console.error(error)
37
- res.redirect(process.env.NEXTAUTH_URL || "")
38
- }
39
- }
40
- }
package/src/api/index.ts DELETED
@@ -1,2 +0,0 @@
1
- export * from "./federatedLogout"
2
- export * from "./nextAuthConfig"
@@ -1,67 +0,0 @@
1
- import { NextAuthOptions } from "next-auth"
2
- import KeycloakProvider from "next-auth/providers/keycloak"
3
- import { refreshAccessToken } from "./refreshAccessToken"
4
-
5
- /**
6
- * Provides authOptions for next-auth that configures it for use with the typical HEKsso setup
7
- */
8
- export function configureAuthOptions(options?: Partial<NextAuthOptions>): NextAuthOptions {
9
- let callbacks: NextAuthOptions["callbacks"] | undefined = undefined
10
-
11
- if (options && "callbacks" in options) {
12
- callbacks = options.callbacks
13
- }
14
-
15
- return {
16
- ...options,
17
- secret: process.env.NEXTAUTH_SECRET,
18
- providers: [
19
- KeycloakProvider({
20
- clientId: process.env.KEYCLOAK_CLIENT_ID || "",
21
- clientSecret: process.env.KEYCLOAK_CLIENT_SECRET || "",
22
- issuer: process.env.KEYCLOAK_ISSUER, // something like "http://localhost:8080/realms/master"
23
- authorization: { params: { scope: "openid email profile roles" } }
24
- })
25
- ],
26
- callbacks: {
27
- async jwt(data) {
28
- const hekGroups = (data.profile as any)?.hekGroups
29
-
30
- // Persist the OAuth access_token to the token right after signin
31
- if (data.account && data.user) {
32
- data.token.idToken = data.account?.id_token
33
- data.token.accessToken = data.account.access_token
34
- data.token.hekGroups = hekGroups
35
- data.token.username = (
36
- data.profile as { [key: string]: string }
37
- ).preferred_username
38
-
39
- if (data.account.expires_at)
40
- data.token.accessTokenExpires = data.account.expires_at * 1000
41
-
42
- data.token.refreshToken = data.account.refresh_token
43
- return data.token
44
- }
45
-
46
- // Return previous token if the access token has not expired yet
47
- if (Date.now() < (data.token.accessTokenExpires as number)) {
48
- return data.token
49
- }
50
-
51
- // Access token has expired, try to update it
52
- return refreshAccessToken(data.token)
53
- },
54
- async session({ session, token }) {
55
- // Send properties to the client, like an access_token from a provider.
56
- const _session = session as any
57
- _session.accessToken = token.accessToken
58
- _session.accessTokenExpires = token.accessTokenExpires
59
- _session.hekGroups = token.hekGroups || []
60
- _session.username = token.username
61
- if (token.error) _session.error = token.error
62
- return _session
63
- },
64
- ...callbacks
65
- }
66
- }
67
- }
@@ -1,47 +0,0 @@
1
- import { JWT } from "next-auth/jwt"
2
-
3
- /**
4
- * Takes a token, and returns a new token with updated
5
- * `accessToken` and `accessTokenExpires`. If an error occurs,
6
- * returns the old token and an error property
7
- *
8
- * This is a utility function and not an API route
9
- */
10
- export async function refreshAccessToken(token: JWT) {
11
- try {
12
- const url = process.env.KEYCLOAK_ISSUER + "/protocol/openid-connect/token?"
13
-
14
- const response = await fetch(url, {
15
- headers: {
16
- "Content-Type": "application/x-www-form-urlencoded"
17
- },
18
- method: "POST",
19
- body: new URLSearchParams({
20
- client_id: process.env.KEYCLOAK_CLIENT_ID || "",
21
- client_secret: process.env.KEYCLOAK_CLIENT_SECRET || "",
22
- grant_type: "refresh_token",
23
- refresh_token: token.refreshToken as string
24
- })
25
- })
26
-
27
- const refreshedTokens = await response.json()
28
-
29
- if (!response.ok) {
30
- throw refreshedTokens
31
- }
32
-
33
- return {
34
- ...token,
35
- accessToken: refreshedTokens.access_token,
36
- accessTokenExpires: Date.now() + refreshedTokens.expires_in * 1000,
37
- refreshToken: refreshedTokens.refresh_token ?? token.refreshToken // Fall back to old refresh token
38
- }
39
- } catch (error) {
40
- console.log(error)
41
-
42
- return {
43
- ...token,
44
- error: "RefreshAccessTokenError"
45
- }
46
- }
47
- }
@@ -1,192 +0,0 @@
1
- import type { signOut as nextAuthSignOut, useSession } from "next-auth/react"
2
- import React, { Component, createContext, PropsWithChildren, useContext } from "react"
3
-
4
- type NextAuthSession = ReturnType<typeof useSession>
5
-
6
- export interface KeycloakSession {
7
- accessTokenError: boolean
8
- getAccessToken: () => Promise<string>
9
- }
10
-
11
- export const KeycloakSessionContext = createContext<KeycloakSession>({
12
- accessTokenError: false,
13
- getAccessToken: async () => {
14
- return ""
15
- }
16
- })
17
-
18
- export function useKeycloakSession(): KeycloakSession {
19
- return useContext(KeycloakSessionContext)
20
- }
21
-
22
- async function refreshAccessToken() {
23
- try {
24
- const response = await fetch("/api/auth/session", {
25
- method: "GET",
26
- headers: {
27
- "Content-Type": "application/json"
28
- }
29
- })
30
-
31
- const data = await response.json()
32
-
33
- if (data.error) {
34
- console.error(data.error)
35
- return undefined
36
- }
37
-
38
- return { accessToken: data.accessToken, accessTokenExpires: data.accessTokenExpires }
39
- } catch (e: unknown) {
40
- console.error(e)
41
- return undefined
42
- }
43
- }
44
-
45
- interface KeycloakSessionProviderProps {
46
- session: ReturnType<typeof useSession>
47
- signOut: typeof nextAuthSignOut
48
- }
49
-
50
- interface KeycloakSessionProviderState {
51
- accessToken?: string
52
- accessTokenError: boolean
53
- accessTokenExpires?: number
54
- }
55
-
56
- /**
57
- * Provider for the useKeycloakSession react hook. Has to directly hook into next-auth and next/router
58
- * @param router Next.js router (retrieve with `useRouter()`)
59
- * @param session Next Auth Session (retrieve with `useSession()`)
60
- * @param signOut Next Auth Sign Out function (exported by "next-auth/react")
61
- * @param children
62
- * @constructor
63
- */
64
- export function KeycloakSessionProvider({
65
- session,
66
- signOut,
67
- children
68
- }: PropsWithChildren<{
69
- session: NextAuthSession
70
- signOut: typeof nextAuthSignOut
71
- }>) {
72
- return (
73
- <_KeycloakSessionProvider session={session} signOut={signOut}>
74
- {children}
75
- </_KeycloakSessionProvider>
76
- )
77
- }
78
-
79
- // Proxy class component to prevent unnecessary re-renders
80
- class _KeycloakSessionProvider extends Component<
81
- PropsWithChildren<KeycloakSessionProviderProps>,
82
- KeycloakSessionProviderState
83
- > {
84
- private contextValue
85
-
86
- constructor(props: KeycloakSessionProviderProps) {
87
- super(props)
88
-
89
- this.state = {
90
- accessTokenError: false
91
- }
92
-
93
- this.getAccessToken = this.getAccessToken.bind(this)
94
- this.getContextValue = this.getContextValue.bind(this)
95
-
96
- this.contextValue = {
97
- getAccessToken: this.getAccessToken,
98
- accessTokenError: false
99
- }
100
- }
101
-
102
- private getContextValue() {
103
- if (this.state.accessTokenError !== this.contextValue.accessTokenError) {
104
- this.contextValue = {
105
- getAccessToken: this.getAccessToken,
106
- accessTokenError: this.state.accessTokenError
107
- }
108
- }
109
-
110
- return this.contextValue
111
- }
112
-
113
- async getAccessToken() {
114
- if (
115
- !this.state.accessToken ||
116
- (this.state.accessTokenExpires && Date.now() >= this.state.accessTokenExpires)
117
- ) {
118
- try {
119
- const refreshed = await refreshAccessToken()
120
-
121
- if (refreshed) {
122
- this.setState({
123
- accessTokenError: false,
124
- accessToken: refreshed.accessToken,
125
- accessTokenExpires: refreshed.accessTokenExpires
126
- })
127
- return refreshed.accessToken
128
- } else {
129
- // Refresh failed due to network error
130
- return undefined
131
- }
132
- } catch (e) {
133
- // Refresh failed because keycloak denied the request
134
- console.error(e)
135
- this.setState({
136
- accessTokenError: true,
137
- accessToken: undefined,
138
- accessTokenExpires: undefined
139
- })
140
- return undefined
141
- }
142
- } else return this.state.accessToken
143
- }
144
-
145
- componentDidUpdate() {
146
- if (sessionDataGuard(this.props.session.data)) {
147
- const { error, accessToken, accessTokenExpires } = this.props.session.data
148
-
149
- if (error === "RefreshAccessTokenError") {
150
- // Force sign in to get a new refresh token
151
- this.props.signOut({ redirect: true, callbackUrl: "/" }).then()
152
- } else if (accessToken && accessToken != this.state.accessToken) {
153
- this.setState({
154
- accessToken,
155
- accessTokenExpires
156
- })
157
- } else if (!accessToken) {
158
- this.setState({
159
- accessToken: undefined,
160
- accessTokenExpires: undefined
161
- })
162
- }
163
- }
164
- }
165
-
166
- render() {
167
- return (
168
- <KeycloakSessionContext.Provider value={this.getContextValue()}>
169
- {this.props.children}
170
- </KeycloakSessionContext.Provider>
171
- )
172
- }
173
- }
174
-
175
- function sessionDataGuard(
176
- sessionData: unknown
177
- ): sessionData is { error?: string; accessToken?: string; accessTokenExpires?: number } {
178
- if (sessionData && typeof sessionData === "object") {
179
- if (!("error" in sessionData) || typeof sessionData.error === "string") {
180
- if (!("accessToken" in sessionData) || typeof sessionData.accessToken === "string") {
181
- if (
182
- !("accessTokenExpires" in sessionData) ||
183
- typeof sessionData.accessTokenExpires === "number"
184
- ) {
185
- return true
186
- }
187
- }
188
- }
189
- }
190
-
191
- return false
192
- }
@@ -1 +0,0 @@
1
- export * from "./KeycloakSessionContext"
package/tsconfig.json DELETED
@@ -1,104 +0,0 @@
1
- {
2
- "compilerOptions": {
3
- /* Visit https://aka.ms/tsconfig to read more about this file */
4
-
5
- /* Projects */
6
- // "incremental": true, /* Save .tsbuildinfo files to allow for incremental compilation of projects. */
7
- // "composite": true, /* Enable constraints that allow a TypeScript project to be used with project references. */
8
- // "tsBuildInfoFile": "./.tsbuildinfo", /* Specify the path to .tsbuildinfo incremental compilation file. */
9
- // "disableSourceOfProjectReferenceRedirect": true, /* Disable preferring source files instead of declaration files when referencing composite projects. */
10
- // "disableSolutionSearching": true, /* Opt a project out of multi-project reference checking when editing. */
11
- // "disableReferencedProjectLoad": true, /* Reduce the number of projects loaded automatically by TypeScript. */
12
-
13
- /* Language and Environment */
14
- "target": "es2016", /* Set the JavaScript language version for emitted JavaScript and include compatible library declarations. */
15
- // "lib": [], /* Specify a set of bundled library declaration files that describe the target runtime environment. */
16
- "jsx": "react", /* Specify what JSX code is generated. */
17
- // "experimentalDecorators": true, /* Enable experimental support for TC39 stage 2 draft decorators. */
18
- // "emitDecoratorMetadata": true, /* Emit design-type metadata for decorated declarations in source files. */
19
- // "jsxFactory": "", /* Specify the JSX factory function used when targeting React JSX emit, e.g. 'React.createElement' or 'h'. */
20
- // "jsxFragmentFactory": "", /* Specify the JSX Fragment reference used for fragments when targeting React JSX emit e.g. 'React.Fragment' or 'Fragment'. */
21
- // "jsxImportSource": "", /* Specify module specifier used to import the JSX factory functions when using 'jsx: react-jsx*'. */
22
- // "reactNamespace": "", /* Specify the object invoked for 'createElement'. This only applies when targeting 'react' JSX emit. */
23
- // "noLib": true, /* Disable including any library files, including the default lib.d.ts. */
24
- // "useDefineForClassFields": true, /* Emit ECMAScript-standard-compliant class fields. */
25
- // "moduleDetection": "auto", /* Control what method is used to detect module-format JS files. */
26
-
27
- /* Modules */
28
- "module": "commonjs", /* Specify what module code is generated. */
29
- "rootDir": "./src", /* Specify the root folder within your source files. */
30
- // "moduleResolution": "node", /* Specify how TypeScript looks up a file from a given module specifier. */
31
- // "baseUrl": "./", /* Specify the base directory to resolve non-relative module names. */
32
- // "paths": {}, /* Specify a set of entries that re-map imports to additional lookup locations. */
33
- // "rootDirs": [], /* Allow multiple folders to be treated as one when resolving modules. */
34
- // "typeRoots": [], /* Specify multiple folders that act like './node_modules/@types'. */
35
- // "types": [], /* Specify type package names to be included without being referenced in a source file. */
36
- // "allowUmdGlobalAccess": true, /* Allow accessing UMD globals from modules. */
37
- // "moduleSuffixes": [], /* List of file name suffixes to search when resolving a module. */
38
- // "resolveJsonModule": true, /* Enable importing .json files. */
39
- // "noResolve": true, /* Disallow 'import's, 'require's or '<reference>'s from expanding the number of files TypeScript should add to a project. */
40
-
41
- /* JavaScript Support */
42
- // "allowJs": true, /* Allow JavaScript files to be a part of your program. Use the 'checkJS' option to get errors from these files. */
43
- // "checkJs": true, /* Enable error reporting in type-checked JavaScript files. */
44
- // "maxNodeModuleJsDepth": 1, /* Specify the maximum folder depth used for checking JavaScript files from 'node_modules'. Only applicable with 'allowJs'. */
45
-
46
- /* Emit */
47
- "declaration": true, /* Generate .d.ts files from TypeScript and JavaScript files in your project. */
48
- // "declarationMap": true, /* Create sourcemaps for d.ts files. */
49
- // "emitDeclarationOnly": true, /* Only output d.ts files and not JavaScript files. */
50
- // "sourceMap": true, /* Create source map files for emitted JavaScript files. */
51
- // "outFile": "./lib/index.js", /* Specify a file that bundles all outputs into one JavaScript file. If 'declaration' is true, also designates a file that bundles all .d.ts output. */
52
- "outDir": ".", /* Specify an output folder for all emitted files. */
53
- // "removeComments": true, /* Disable emitting comments. */
54
- // "noEmit": true, /* Disable emitting files from a compilation. */
55
- // "importHelpers": true, /* Allow importing helper functions from tslib once per project, instead of including them per-file. */
56
- // "importsNotUsedAsValues": "remove", /* Specify emit/checking behavior for imports that are only used for types. */
57
- // "downlevelIteration": true, /* Emit more compliant, but verbose and less performant JavaScript for iteration. */
58
- // "sourceRoot": "", /* Specify the root path for debuggers to find the reference source code. */
59
- // "mapRoot": "", /* Specify the location where debugger should locate map files instead of generated locations. */
60
- // "inlineSourceMap": true, /* Include sourcemap files inside the emitted JavaScript. */
61
- // "inlineSources": true, /* Include source code in the sourcemaps inside the emitted JavaScript. */
62
- // "emitBOM": true, /* Emit a UTF-8 Byte Order Mark (BOM) in the beginning of output files. */
63
- // "newLine": "crlf", /* Set the newline character for emitting files. */
64
- // "stripInternal": true, /* Disable emitting declarations that have '@internal' in their JSDoc comments. */
65
- // "noEmitHelpers": true, /* Disable generating custom helper functions like '__extends' in compiled output. */
66
- // "noEmitOnError": true, /* Disable emitting files if any type checking errors are reported. */
67
- // "preserveConstEnums": true, /* Disable erasing 'const enum' declarations in generated code. */
68
- // "declarationDir": "./", /* Specify the output directory for generated declaration files. */
69
- // "preserveValueImports": true, /* Preserve unused imported values in the JavaScript output that would otherwise be removed. */
70
-
71
- /* Interop Constraints */
72
- // "isolatedModules": true, /* Ensure that each file can be safely transpiled without relying on other imports. */
73
- // "allowSyntheticDefaultImports": true, /* Allow 'import x from y' when a module doesn't have a default export. */
74
- "esModuleInterop": true, /* Emit additional JavaScript to ease support for importing CommonJS modules. This enables 'allowSyntheticDefaultImports' for type compatibility. */
75
- // "preserveSymlinks": true, /* Disable resolving symlinks to their realpath. This correlates to the same flag in node. */
76
- "forceConsistentCasingInFileNames": true, /* Ensure that casing is correct in imports. */
77
-
78
- /* Type Checking */
79
- "strict": true, /* Enable all strict type-checking options. */
80
- // "noImplicitAny": true, /* Enable error reporting for expressions and declarations with an implied 'any' type. */
81
- // "strictNullChecks": true, /* When type checking, take into account 'null' and 'undefined'. */
82
- // "strictFunctionTypes": true, /* When assigning functions, check to ensure parameters and the return values are subtype-compatible. */
83
- // "strictBindCallApply": true, /* Check that the arguments for 'bind', 'call', and 'apply' methods match the original function. */
84
- // "strictPropertyInitialization": true, /* Check for class properties that are declared but not set in the constructor. */
85
- // "noImplicitThis": true, /* Enable error reporting when 'this' is given the type 'any'. */
86
- // "useUnknownInCatchVariables": true, /* Default catch clause variables as 'unknown' instead of 'any'. */
87
- // "alwaysStrict": true, /* Ensure 'use strict' is always emitted. */
88
- // "noUnusedLocals": true, /* Enable error reporting when local variables aren't read. */
89
- // "noUnusedParameters": true, /* Raise an error when a function parameter isn't read. */
90
- // "exactOptionalPropertyTypes": true, /* Interpret optional property types as written, rather than adding 'undefined'. */
91
- // "noImplicitReturns": true, /* Enable error reporting for codepaths that do not explicitly return in a function. */
92
- // "noFallthroughCasesInSwitch": true, /* Enable error reporting for fallthrough cases in switch statements. */
93
- // "noUncheckedIndexedAccess": true, /* Add 'undefined' to a type when accessed using an index. */
94
- // "noImplicitOverride": true, /* Ensure overriding members in derived classes are marked with an override modifier. */
95
- // "noPropertyAccessFromIndexSignature": true, /* Enforces using indexed accessors for keys declared using an indexed type. */
96
- // "allowUnusedLabels": true, /* Disable error reporting for unused labels. */
97
- // "allowUnreachableCode": true, /* Disable error reporting for unreachable code. */
98
-
99
- /* Completeness */
100
- // "skipDefaultLibCheck": true, /* Skip type checking .d.ts files that are included with TypeScript. */
101
- "skipLibCheck": true /* Skip type checking all .d.ts files. */
102
- },
103
- "exclude": ["api", "react", "node_modules"]
104
- }