next-auth-heksso 1.0.0
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/.env.example +5 -0
- package/.eslintrc.json +3 -0
- package/README.md +11 -0
- package/lib/index.d.ts +2 -0
- package/lib/index.js +18 -0
- package/lib/next/KeycloakSessionContext.d.ts +9 -0
- package/lib/next/KeycloakSessionContext.js +123 -0
- package/lib/next/KeycloakSessionContext.jsx +125 -0
- package/lib/next/index.d.ts +1 -0
- package/lib/next/index.js +17 -0
- package/lib/next-api/federatedLogout.d.ts +8 -0
- package/lib/next-api/federatedLogout.js +69 -0
- package/lib/next-api/index.d.ts +2 -0
- package/lib/next-api/index.js +18 -0
- package/lib/next-api/nextAuthConfig.d.ts +7 -0
- package/lib/next-api/nextAuthConfig.js +74 -0
- package/lib/next-api/refreshAccessToken.d.ts +23 -0
- package/lib/next-api/refreshAccessToken.js +50 -0
- package/package.json +26 -0
- package/src/index.ts +2 -0
- package/src/next/KeycloakSessionContext.tsx +103 -0
- package/src/next/index.ts +1 -0
- package/src/next-api/federatedLogout.ts +38 -0
- package/src/next-api/index.ts +2 -0
- package/src/next-api/nextAuthConfig.ts +60 -0
- package/src/next-api/refreshAccessToken.ts +47 -0
- package/tsconfig.json +104 -0
package/.env.example
ADDED
|
@@ -0,0 +1,5 @@
|
|
|
1
|
+
NEXTAUTH_URL=http://localhost:3000 # URL for this site
|
|
2
|
+
NEXTAUTH_SECRET=<Secret for Token generation. Enter a random string>
|
|
3
|
+
KEYCLOAK_CLIENT_ID=hekmoney
|
|
4
|
+
KEYCLOAK_CLIENT_SECRET=<Go to Keycloak -> Clients -> Credentials>
|
|
5
|
+
KEYCLOAK_ISSUER=http://localhost:8080/realms/master
|
package/.eslintrc.json
ADDED
package/README.md
ADDED
package/lib/index.d.ts
ADDED
package/lib/index.js
ADDED
|
@@ -0,0 +1,18 @@
|
|
|
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("./next"), exports);
|
|
18
|
+
__exportStar(require("./next-api"), exports);
|
|
@@ -0,0 +1,9 @@
|
|
|
1
|
+
import React, { ReactNode } from "react";
|
|
2
|
+
export interface KeycloakSession {
|
|
3
|
+
getAccessToken: () => Promise<string>;
|
|
4
|
+
}
|
|
5
|
+
export declare const KeycloakSessionContext: React.Context<KeycloakSession>;
|
|
6
|
+
export declare function KeycloakSessionProvider(props: {
|
|
7
|
+
children: ReactNode | ReactNode[];
|
|
8
|
+
signInPage?: string;
|
|
9
|
+
}): JSX.Element;
|
|
@@ -0,0 +1,123 @@
|
|
|
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.KeycloakSessionProvider = exports.KeycloakSessionContext = void 0;
|
|
36
|
+
const react_1 = require("next-auth/react");
|
|
37
|
+
const router_1 = require("next/router");
|
|
38
|
+
const react_2 = __importStar(require("react"));
|
|
39
|
+
exports.KeycloakSessionContext = (0, react_2.createContext)({
|
|
40
|
+
getAccessToken: () => __awaiter(void 0, void 0, void 0, function* () {
|
|
41
|
+
return "";
|
|
42
|
+
})
|
|
43
|
+
});
|
|
44
|
+
function refreshAccessToken() {
|
|
45
|
+
return __awaiter(this, void 0, void 0, function* () {
|
|
46
|
+
try {
|
|
47
|
+
const response = yield fetch("/api/auth/session", {
|
|
48
|
+
method: "GET",
|
|
49
|
+
headers: {
|
|
50
|
+
"Content-Type": "application/json"
|
|
51
|
+
}
|
|
52
|
+
});
|
|
53
|
+
const data = yield response.json();
|
|
54
|
+
if (data.error) {
|
|
55
|
+
throw data.error;
|
|
56
|
+
}
|
|
57
|
+
return { accessToken: data.accessToken, accessTokenExpires: data.accessTokenExpires };
|
|
58
|
+
}
|
|
59
|
+
catch (e) {
|
|
60
|
+
console.error(e);
|
|
61
|
+
return undefined;
|
|
62
|
+
}
|
|
63
|
+
});
|
|
64
|
+
}
|
|
65
|
+
function KeycloakSessionProvider(props) {
|
|
66
|
+
const session = (0, react_1.useSession)();
|
|
67
|
+
const router = (0, router_1.useRouter)();
|
|
68
|
+
const [accessToken, setAccessToken] = (0, react_2.useState)(undefined);
|
|
69
|
+
const [accessTokenError, setAccessTokenError] = (0, react_2.useState)(false);
|
|
70
|
+
const [accessTokenExpires, setAccessTokenExpires] = (0, react_2.useState)(undefined);
|
|
71
|
+
const getAccessToken = (0, react_2.useCallback)(() => __awaiter(this, void 0, void 0, function* () {
|
|
72
|
+
if (!accessToken)
|
|
73
|
+
return undefined;
|
|
74
|
+
if (accessTokenExpires && Date.now() >= accessTokenExpires) {
|
|
75
|
+
try {
|
|
76
|
+
const refreshed = yield refreshAccessToken();
|
|
77
|
+
if (refreshed) {
|
|
78
|
+
setAccessTokenError(false);
|
|
79
|
+
setAccessToken(refreshed.accessToken);
|
|
80
|
+
setAccessTokenExpires(refreshed.accessTokenExpires);
|
|
81
|
+
return refreshed.accessToken;
|
|
82
|
+
}
|
|
83
|
+
else {
|
|
84
|
+
// Refresh failed due to network error
|
|
85
|
+
return undefined;
|
|
86
|
+
}
|
|
87
|
+
}
|
|
88
|
+
catch (e) {
|
|
89
|
+
// Refresh failed because keycloak denied the request
|
|
90
|
+
console.error(e);
|
|
91
|
+
setAccessTokenError(true);
|
|
92
|
+
setAccessToken(undefined);
|
|
93
|
+
setAccessTokenExpires(undefined);
|
|
94
|
+
return undefined;
|
|
95
|
+
}
|
|
96
|
+
}
|
|
97
|
+
else
|
|
98
|
+
return accessToken;
|
|
99
|
+
}), [accessToken, accessTokenExpires]);
|
|
100
|
+
// Because this component is present on every page that requires a session,
|
|
101
|
+
// we check for a valid refresh token here
|
|
102
|
+
(0, react_2.useEffect)(() => {
|
|
103
|
+
var _a, _b, _c, _d;
|
|
104
|
+
if (!router.asPath.startsWith(props.signInPage || "/auth/signin") &&
|
|
105
|
+
(session.status === "unauthenticated" || accessTokenError)) {
|
|
106
|
+
router.push(props.signInPage || "/auth/signin");
|
|
107
|
+
return;
|
|
108
|
+
}
|
|
109
|
+
if (((_a = session.data) === null || _a === void 0 ? void 0 : _a.error) === "RefreshAccessTokenError") {
|
|
110
|
+
(0, react_1.signOut)(); // Force sign in to get a new refresh token
|
|
111
|
+
}
|
|
112
|
+
else if ((_b = session.data) === null || _b === void 0 ? void 0 : _b.accessToken) {
|
|
113
|
+
setAccessToken((_c = session.data) === null || _c === void 0 ? void 0 : _c.accessToken),
|
|
114
|
+
setAccessTokenExpires((_d = session.data) === null || _d === void 0 ? void 0 : _d.accessTokenExpires);
|
|
115
|
+
}
|
|
116
|
+
else {
|
|
117
|
+
setAccessToken(undefined);
|
|
118
|
+
setAccessTokenExpires(undefined);
|
|
119
|
+
}
|
|
120
|
+
}, [session, router.pathname, accessToken, router, props.signInPage, accessTokenError]);
|
|
121
|
+
return (react_2.default.createElement(exports.KeycloakSessionContext.Provider, { value: { getAccessToken } }, props.children));
|
|
122
|
+
}
|
|
123
|
+
exports.KeycloakSessionProvider = KeycloakSessionProvider;
|
|
@@ -0,0 +1,125 @@
|
|
|
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.KeycloakSessionProvider = exports.KeycloakSessionContext = void 0;
|
|
36
|
+
const react_1 = require("next-auth/react");
|
|
37
|
+
const router_1 = require("next/router");
|
|
38
|
+
const react_2 = __importStar(require("react"));
|
|
39
|
+
exports.KeycloakSessionContext = (0, react_2.createContext)({
|
|
40
|
+
getAccessToken: () => __awaiter(void 0, void 0, void 0, function* () {
|
|
41
|
+
return "";
|
|
42
|
+
})
|
|
43
|
+
});
|
|
44
|
+
function refreshAccessToken() {
|
|
45
|
+
return __awaiter(this, void 0, void 0, function* () {
|
|
46
|
+
try {
|
|
47
|
+
const response = yield fetch("/api/auth/session", {
|
|
48
|
+
method: "GET",
|
|
49
|
+
headers: {
|
|
50
|
+
"Content-Type": "application/json"
|
|
51
|
+
}
|
|
52
|
+
});
|
|
53
|
+
const data = yield response.json();
|
|
54
|
+
if (data.error) {
|
|
55
|
+
throw data.error;
|
|
56
|
+
}
|
|
57
|
+
return { accessToken: data.accessToken, accessTokenExpires: data.accessTokenExpires };
|
|
58
|
+
}
|
|
59
|
+
catch (e) {
|
|
60
|
+
console.error(e);
|
|
61
|
+
return undefined;
|
|
62
|
+
}
|
|
63
|
+
});
|
|
64
|
+
}
|
|
65
|
+
function KeycloakSessionProvider(props) {
|
|
66
|
+
const session = (0, react_1.useSession)();
|
|
67
|
+
const router = (0, router_1.useRouter)();
|
|
68
|
+
const [accessToken, setAccessToken] = (0, react_2.useState)(undefined);
|
|
69
|
+
const [accessTokenError, setAccessTokenError] = (0, react_2.useState)(false);
|
|
70
|
+
const [accessTokenExpires, setAccessTokenExpires] = (0, react_2.useState)(undefined);
|
|
71
|
+
const getAccessToken = (0, react_2.useCallback)(() => __awaiter(this, void 0, void 0, function* () {
|
|
72
|
+
if (!accessToken)
|
|
73
|
+
return undefined;
|
|
74
|
+
if (accessTokenExpires && Date.now() >= accessTokenExpires) {
|
|
75
|
+
try {
|
|
76
|
+
const refreshed = yield refreshAccessToken();
|
|
77
|
+
if (refreshed) {
|
|
78
|
+
setAccessTokenError(false);
|
|
79
|
+
setAccessToken(refreshed.accessToken);
|
|
80
|
+
setAccessTokenExpires(refreshed.accessTokenExpires);
|
|
81
|
+
return refreshed.accessToken;
|
|
82
|
+
}
|
|
83
|
+
else {
|
|
84
|
+
// Refresh failed due to network error
|
|
85
|
+
return undefined;
|
|
86
|
+
}
|
|
87
|
+
}
|
|
88
|
+
catch (e) {
|
|
89
|
+
// Refresh failed because keycloak denied the request
|
|
90
|
+
console.error(e);
|
|
91
|
+
setAccessTokenError(true);
|
|
92
|
+
setAccessToken(undefined);
|
|
93
|
+
setAccessTokenExpires(undefined);
|
|
94
|
+
return undefined;
|
|
95
|
+
}
|
|
96
|
+
}
|
|
97
|
+
else
|
|
98
|
+
return accessToken;
|
|
99
|
+
}), [accessToken, accessTokenExpires]);
|
|
100
|
+
// Because this component is present on every page that requires a session,
|
|
101
|
+
// we check for a valid refresh token here
|
|
102
|
+
(0, react_2.useEffect)(() => {
|
|
103
|
+
var _a, _b, _c, _d;
|
|
104
|
+
if (!router.asPath.startsWith(props.signInPage || "/auth/signin") &&
|
|
105
|
+
(session.status === "unauthenticated" || accessTokenError)) {
|
|
106
|
+
router.push(props.signInPage || "/auth/signin");
|
|
107
|
+
return;
|
|
108
|
+
}
|
|
109
|
+
if (((_a = session.data) === null || _a === void 0 ? void 0 : _a.error) === "RefreshAccessTokenError") {
|
|
110
|
+
(0, react_1.signOut)(); // Force sign in to get a new refresh token
|
|
111
|
+
}
|
|
112
|
+
else if ((_b = session.data) === null || _b === void 0 ? void 0 : _b.accessToken) {
|
|
113
|
+
setAccessToken((_c = session.data) === null || _c === void 0 ? void 0 : _c.accessToken),
|
|
114
|
+
setAccessTokenExpires((_d = session.data) === null || _d === void 0 ? void 0 : _d.accessTokenExpires);
|
|
115
|
+
}
|
|
116
|
+
else {
|
|
117
|
+
setAccessToken(undefined);
|
|
118
|
+
setAccessTokenExpires(undefined);
|
|
119
|
+
}
|
|
120
|
+
}, [session, router.pathname, accessToken, router, props.signInPage, accessTokenError]);
|
|
121
|
+
return (<exports.KeycloakSessionContext.Provider value={{ getAccessToken }}>
|
|
122
|
+
{props.children}
|
|
123
|
+
</exports.KeycloakSessionContext.Provider>);
|
|
124
|
+
}
|
|
125
|
+
exports.KeycloakSessionProvider = KeycloakSessionProvider;
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
export * from "./KeycloakSessionContext";
|
|
@@ -0,0 +1,17 @@
|
|
|
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);
|
|
@@ -0,0 +1,8 @@
|
|
|
1
|
+
import { NextApiRequest, NextApiResponse } from "next";
|
|
2
|
+
/**
|
|
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
|
|
6
|
+
* @returns
|
|
7
|
+
*/
|
|
8
|
+
export default function federatedLogout(req: NextApiRequest, res: NextApiResponse): Promise<NextApiResponse<any> | undefined>;
|
|
@@ -0,0 +1,69 @@
|
|
|
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
|
+
const jwt = __importStar(require("next-auth/jwt"));
|
|
36
|
+
/**
|
|
37
|
+
* Provides a next api route for performing a federated logout of the user (logs ouf of keycloak)
|
|
38
|
+
* @param req NextApiRequest
|
|
39
|
+
* @param res NextApiRequest
|
|
40
|
+
* @returns
|
|
41
|
+
*/
|
|
42
|
+
function federatedLogout(req, res) {
|
|
43
|
+
return __awaiter(this, void 0, void 0, function* () {
|
|
44
|
+
try {
|
|
45
|
+
const token = yield jwt.getToken({ req, secret: process.env.NEXTAUTH_SECRET });
|
|
46
|
+
if (!token) {
|
|
47
|
+
console.warn("No JWT token found when calling /federated-logout endpoint");
|
|
48
|
+
return res.redirect(process.env.NEXTAUTH_URL || "");
|
|
49
|
+
}
|
|
50
|
+
const endsessionURL = `${process.env.KEYCLOAK_ISSUER}/protocol/openid-connect/logout`;
|
|
51
|
+
if (token.idToken) {
|
|
52
|
+
console.warn("Without an id_token the user won't be redirected back from the IdP after logout.");
|
|
53
|
+
const endsessionParams = new URLSearchParams({
|
|
54
|
+
id_token_hint: token.idToken,
|
|
55
|
+
post_logout_redirect_uri: process.env.NEXTAUTH_URL + "/logout" || ""
|
|
56
|
+
});
|
|
57
|
+
return res.redirect(`${endsessionURL}?${endsessionParams}`);
|
|
58
|
+
}
|
|
59
|
+
else {
|
|
60
|
+
return res.redirect(`${endsessionURL}`);
|
|
61
|
+
}
|
|
62
|
+
}
|
|
63
|
+
catch (error) {
|
|
64
|
+
console.error(error);
|
|
65
|
+
res.redirect(process.env.NEXTAUTH_URL || "");
|
|
66
|
+
}
|
|
67
|
+
});
|
|
68
|
+
}
|
|
69
|
+
exports.default = federatedLogout;
|
|
@@ -0,0 +1,18 @@
|
|
|
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);
|
|
@@ -0,0 +1,74 @@
|
|
|
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.authOptions = void 0;
|
|
16
|
+
const next_auth_1 = __importDefault(require("next-auth"));
|
|
17
|
+
const keycloak_1 = __importDefault(require("next-auth/providers/keycloak"));
|
|
18
|
+
const refreshAccessToken_1 = require("./refreshAccessToken");
|
|
19
|
+
/**
|
|
20
|
+
* Provides authOptions for next-auth that configures it for use with the typical HEKsso setup
|
|
21
|
+
*/
|
|
22
|
+
exports.authOptions = {
|
|
23
|
+
secret: process.env.NEXTAUTH_SECRET,
|
|
24
|
+
providers: [
|
|
25
|
+
(0, keycloak_1.default)({
|
|
26
|
+
clientId: process.env.KEYCLOAK_CLIENT_ID || "",
|
|
27
|
+
clientSecret: process.env.KEYCLOAK_CLIENT_SECRET || "",
|
|
28
|
+
issuer: process.env.KEYCLOAK_ISSUER,
|
|
29
|
+
authorization: { params: { scope: "openid email profile roles" } }
|
|
30
|
+
})
|
|
31
|
+
],
|
|
32
|
+
pages: {
|
|
33
|
+
signIn: "/",
|
|
34
|
+
},
|
|
35
|
+
callbacks: {
|
|
36
|
+
jwt(data) {
|
|
37
|
+
var _a, _b;
|
|
38
|
+
return __awaiter(this, void 0, void 0, function* () {
|
|
39
|
+
const hekGroups = (_a = data.profile) === null || _a === void 0 ? void 0 : _a.hekGroups;
|
|
40
|
+
// Persist the OAuth access_token to the token right after signin
|
|
41
|
+
if (data.account && data.user) {
|
|
42
|
+
data.token.idToken = (_b = data.account) === null || _b === void 0 ? void 0 : _b.id_token;
|
|
43
|
+
data.token.accessToken = data.account.access_token;
|
|
44
|
+
data.token.hekGroups = hekGroups;
|
|
45
|
+
data.token.username = data.profile.preferred_username;
|
|
46
|
+
if (data.account.expires_at)
|
|
47
|
+
data.token.accessTokenExpires = data.account.expires_at * 1000;
|
|
48
|
+
data.token.refreshToken = data.account.refresh_token;
|
|
49
|
+
return data.token;
|
|
50
|
+
}
|
|
51
|
+
// Return previous token if the access token has not expired yet
|
|
52
|
+
if (Date.now() < data.token.accessTokenExpires) {
|
|
53
|
+
return data.token;
|
|
54
|
+
}
|
|
55
|
+
// Access token has expired, try to update it
|
|
56
|
+
return (0, refreshAccessToken_1.refreshAccessToken)(data.token);
|
|
57
|
+
});
|
|
58
|
+
},
|
|
59
|
+
session({ session, token }) {
|
|
60
|
+
return __awaiter(this, void 0, void 0, function* () {
|
|
61
|
+
// Send properties to the client, like an access_token from a provider.
|
|
62
|
+
const _session = session;
|
|
63
|
+
_session.accessToken = token.accessToken;
|
|
64
|
+
_session.accessTokenExpires = token.accessTokenExpires;
|
|
65
|
+
_session.hekGroups = token.hekGroups || [];
|
|
66
|
+
_session.username = token.username;
|
|
67
|
+
if (token.error)
|
|
68
|
+
_session.error = token.error;
|
|
69
|
+
return _session;
|
|
70
|
+
});
|
|
71
|
+
}
|
|
72
|
+
}
|
|
73
|
+
};
|
|
74
|
+
exports.default = (0, next_auth_1.default)(exports.authOptions);
|
|
@@ -0,0 +1,23 @@
|
|
|
1
|
+
import { JWT } from "next-auth/jwt";
|
|
2
|
+
/**
|
|
3
|
+
* Takes a token, and returns a new token with updated
|
|
4
|
+
* `accessToken` and `accessTokenExpires`. If an error occurs,
|
|
5
|
+
* returns the old token and an error property
|
|
6
|
+
*
|
|
7
|
+
* This is a utility function and not an API route
|
|
8
|
+
*/
|
|
9
|
+
export declare function refreshAccessToken(token: JWT): Promise<{
|
|
10
|
+
accessToken: any;
|
|
11
|
+
accessTokenExpires: number;
|
|
12
|
+
refreshToken: any;
|
|
13
|
+
name?: string | null | undefined;
|
|
14
|
+
email?: string | null | undefined;
|
|
15
|
+
picture?: string | null | undefined;
|
|
16
|
+
sub?: string | undefined;
|
|
17
|
+
} | {
|
|
18
|
+
error: string;
|
|
19
|
+
name?: string | null | undefined;
|
|
20
|
+
email?: string | null | undefined;
|
|
21
|
+
picture?: string | null | undefined;
|
|
22
|
+
sub?: string | undefined;
|
|
23
|
+
}>;
|
|
@@ -0,0 +1,50 @@
|
|
|
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 = void 0;
|
|
13
|
+
/**
|
|
14
|
+
* Takes a token, and returns a new token with updated
|
|
15
|
+
* `accessToken` and `accessTokenExpires`. If an error occurs,
|
|
16
|
+
* returns the old token and an error property
|
|
17
|
+
*
|
|
18
|
+
* This is a utility function and not an API route
|
|
19
|
+
*/
|
|
20
|
+
function refreshAccessToken(token) {
|
|
21
|
+
var _a;
|
|
22
|
+
return __awaiter(this, void 0, void 0, function* () {
|
|
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
|
+
});
|
|
43
|
+
}
|
|
44
|
+
catch (error) {
|
|
45
|
+
console.log(error);
|
|
46
|
+
return Object.assign(Object.assign({}, token), { error: "RefreshAccessTokenError" });
|
|
47
|
+
}
|
|
48
|
+
});
|
|
49
|
+
}
|
|
50
|
+
exports.refreshAccessToken = refreshAccessToken;
|
package/package.json
ADDED
|
@@ -0,0 +1,26 @@
|
|
|
1
|
+
{
|
|
2
|
+
"name": "next-auth-heksso",
|
|
3
|
+
"author": {
|
|
4
|
+
"name": "Voakie",
|
|
5
|
+
"email": "contact@voakie.com"
|
|
6
|
+
},
|
|
7
|
+
"license": "MIT",
|
|
8
|
+
"version": "1.0.0",
|
|
9
|
+
"scripts": {
|
|
10
|
+
"build": "tsc"
|
|
11
|
+
},
|
|
12
|
+
"main": "lib/index.js",
|
|
13
|
+
"types": "lib/index.d.ts",
|
|
14
|
+
"dependencies": {
|
|
15
|
+
"@types/node": "^18.11.18",
|
|
16
|
+
"@types/react": "^18.0.27",
|
|
17
|
+
"@types/react-dom": "^18.0.10",
|
|
18
|
+
"eslint": "^8.32.0",
|
|
19
|
+
"eslint-config-next": "^13.1.6",
|
|
20
|
+
"next": "^13.1.6",
|
|
21
|
+
"next-auth": "^4.19.0",
|
|
22
|
+
"react": "^18.2.0",
|
|
23
|
+
"react-dom": "^18.2.0",
|
|
24
|
+
"typescript": "^4.9.4"
|
|
25
|
+
}
|
|
26
|
+
}
|
package/src/index.ts
ADDED
|
@@ -0,0 +1,103 @@
|
|
|
1
|
+
import { signOut, useSession } from "next-auth/react"
|
|
2
|
+
import { useRouter } from "next/router"
|
|
3
|
+
import React, { createContext, ReactNode, useCallback, useEffect, useState } from "react"
|
|
4
|
+
|
|
5
|
+
export interface KeycloakSession {
|
|
6
|
+
getAccessToken: () => Promise<string>
|
|
7
|
+
}
|
|
8
|
+
|
|
9
|
+
export const KeycloakSessionContext = createContext<KeycloakSession>({
|
|
10
|
+
getAccessToken: async () => {
|
|
11
|
+
return ""
|
|
12
|
+
}
|
|
13
|
+
})
|
|
14
|
+
|
|
15
|
+
async function refreshAccessToken() {
|
|
16
|
+
try {
|
|
17
|
+
const response = await fetch("/api/auth/session", {
|
|
18
|
+
method: "GET",
|
|
19
|
+
headers: {
|
|
20
|
+
"Content-Type": "application/json"
|
|
21
|
+
}
|
|
22
|
+
})
|
|
23
|
+
|
|
24
|
+
const data = await response.json()
|
|
25
|
+
|
|
26
|
+
if (data.error) {
|
|
27
|
+
throw data.error
|
|
28
|
+
}
|
|
29
|
+
|
|
30
|
+
return { accessToken: data.accessToken, accessTokenExpires: data.accessTokenExpires }
|
|
31
|
+
} catch (e: unknown) {
|
|
32
|
+
console.error(e)
|
|
33
|
+
return undefined
|
|
34
|
+
}
|
|
35
|
+
}
|
|
36
|
+
|
|
37
|
+
export function KeycloakSessionProvider(props: {
|
|
38
|
+
children: ReactNode | ReactNode[]
|
|
39
|
+
signInPage?: string
|
|
40
|
+
}) {
|
|
41
|
+
const session = useSession()
|
|
42
|
+
const router = useRouter()
|
|
43
|
+
|
|
44
|
+
const [accessToken, setAccessToken] = useState<string | undefined>(undefined)
|
|
45
|
+
const [accessTokenError, setAccessTokenError] = useState(false)
|
|
46
|
+
const [accessTokenExpires, setAccessTokenExpires] = useState<number | undefined>(undefined)
|
|
47
|
+
|
|
48
|
+
const getAccessToken = useCallback(async () => {
|
|
49
|
+
if (!accessToken) return undefined
|
|
50
|
+
if (accessTokenExpires && Date.now() >= accessTokenExpires) {
|
|
51
|
+
try {
|
|
52
|
+
const refreshed = await refreshAccessToken()
|
|
53
|
+
|
|
54
|
+
if (refreshed) {
|
|
55
|
+
setAccessTokenError(false)
|
|
56
|
+
setAccessToken(refreshed.accessToken)
|
|
57
|
+
setAccessTokenExpires(refreshed.accessTokenExpires)
|
|
58
|
+
return refreshed.accessToken
|
|
59
|
+
} else {
|
|
60
|
+
// Refresh failed due to network error
|
|
61
|
+
return undefined
|
|
62
|
+
}
|
|
63
|
+
} catch (e) {
|
|
64
|
+
// Refresh failed because keycloak denied the request
|
|
65
|
+
console.error(e)
|
|
66
|
+
setAccessTokenError(true)
|
|
67
|
+
setAccessToken(undefined)
|
|
68
|
+
setAccessTokenExpires(undefined)
|
|
69
|
+
return undefined
|
|
70
|
+
}
|
|
71
|
+
} else return accessToken
|
|
72
|
+
}, [accessToken, accessTokenExpires])
|
|
73
|
+
|
|
74
|
+
// Because this component is present on every page that requires a session,
|
|
75
|
+
// we check for a valid refresh token here
|
|
76
|
+
useEffect(() => {
|
|
77
|
+
if (
|
|
78
|
+
!router.asPath.startsWith(props.signInPage || "/auth/signin") &&
|
|
79
|
+
(session.status === "unauthenticated" || accessTokenError)
|
|
80
|
+
) {
|
|
81
|
+
router.push(props.signInPage || "/auth/signin")
|
|
82
|
+
return
|
|
83
|
+
}
|
|
84
|
+
|
|
85
|
+
if ((session.data as any)?.error === "RefreshAccessTokenError") {
|
|
86
|
+
signOut() // Force sign in to get a new refresh token
|
|
87
|
+
} else if ((session.data as any)?.accessToken) {
|
|
88
|
+
setAccessToken((session.data as any)?.accessToken as string),
|
|
89
|
+
setAccessTokenExpires((session.data as any)?.accessTokenExpires as number)
|
|
90
|
+
} else {
|
|
91
|
+
setAccessToken(undefined)
|
|
92
|
+
setAccessTokenExpires(undefined)
|
|
93
|
+
}
|
|
94
|
+
}, [session, router.pathname, accessToken, router, props.signInPage, accessTokenError])
|
|
95
|
+
|
|
96
|
+
return (
|
|
97
|
+
<KeycloakSessionContext.Provider
|
|
98
|
+
value={{ getAccessToken }}
|
|
99
|
+
>
|
|
100
|
+
{props.children}
|
|
101
|
+
</KeycloakSessionContext.Provider>
|
|
102
|
+
)
|
|
103
|
+
}
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
export * from "./KeycloakSessionContext"
|
|
@@ -0,0 +1,38 @@
|
|
|
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 default async function federatedLogout(req: NextApiRequest, res: NextApiResponse) {
|
|
12
|
+
try {
|
|
13
|
+
const token = await jwt.getToken({ req, secret: process.env.NEXTAUTH_SECRET })
|
|
14
|
+
if (!token) {
|
|
15
|
+
console.warn("No JWT token found when calling /federated-logout endpoint")
|
|
16
|
+
return res.redirect(process.env.NEXTAUTH_URL || "")
|
|
17
|
+
}
|
|
18
|
+
|
|
19
|
+
const endsessionURL = `${process.env.KEYCLOAK_ISSUER}/protocol/openid-connect/logout`
|
|
20
|
+
|
|
21
|
+
if (token.idToken) {
|
|
22
|
+
console.warn(
|
|
23
|
+
"Without an id_token the user won't be redirected back from the IdP after logout."
|
|
24
|
+
)
|
|
25
|
+
|
|
26
|
+
const endsessionParams = new URLSearchParams({
|
|
27
|
+
id_token_hint: token.idToken as string,
|
|
28
|
+
post_logout_redirect_uri: process.env.NEXTAUTH_URL + "/logout" || ""
|
|
29
|
+
})
|
|
30
|
+
return res.redirect(`${endsessionURL}?${endsessionParams}`)
|
|
31
|
+
} else {
|
|
32
|
+
return res.redirect(`${endsessionURL}`)
|
|
33
|
+
}
|
|
34
|
+
} catch (error) {
|
|
35
|
+
console.error(error)
|
|
36
|
+
res.redirect(process.env.NEXTAUTH_URL || "")
|
|
37
|
+
}
|
|
38
|
+
}
|
|
@@ -0,0 +1,60 @@
|
|
|
1
|
+
import NextAuth, { 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 const authOptions: NextAuthOptions = {
|
|
9
|
+
secret: process.env.NEXTAUTH_SECRET,
|
|
10
|
+
providers: [
|
|
11
|
+
KeycloakProvider({
|
|
12
|
+
clientId: process.env.KEYCLOAK_CLIENT_ID || "",
|
|
13
|
+
clientSecret: process.env.KEYCLOAK_CLIENT_SECRET || "",
|
|
14
|
+
issuer: process.env.KEYCLOAK_ISSUER, // something like "http://localhost:8080/realms/master"
|
|
15
|
+
authorization: { params: { scope: "openid email profile roles" } }
|
|
16
|
+
})
|
|
17
|
+
],
|
|
18
|
+
pages: {
|
|
19
|
+
signIn: "/",
|
|
20
|
+
},
|
|
21
|
+
callbacks: {
|
|
22
|
+
async jwt(data) {
|
|
23
|
+
const hekGroups = (data.profile as any)?.hekGroups
|
|
24
|
+
|
|
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 as { [key: string]: string }).preferred_username
|
|
31
|
+
|
|
32
|
+
if (data.account.expires_at)
|
|
33
|
+
data.token.accessTokenExpires = data.account.expires_at * 1000
|
|
34
|
+
|
|
35
|
+
data.token.refreshToken = data.account.refresh_token
|
|
36
|
+
return data.token
|
|
37
|
+
}
|
|
38
|
+
|
|
39
|
+
// Return previous token if the access token has not expired yet
|
|
40
|
+
if (Date.now() < (data.token.accessTokenExpires as number)) {
|
|
41
|
+
return data.token
|
|
42
|
+
}
|
|
43
|
+
|
|
44
|
+
// Access token has expired, try to update it
|
|
45
|
+
return refreshAccessToken(data.token)
|
|
46
|
+
},
|
|
47
|
+
async session({ session, token }) {
|
|
48
|
+
// Send properties to the client, like an access_token from a provider.
|
|
49
|
+
const _session = session as any
|
|
50
|
+
_session.accessToken = token.accessToken
|
|
51
|
+
_session.accessTokenExpires = token.accessTokenExpires
|
|
52
|
+
_session.hekGroups = token.hekGroups || []
|
|
53
|
+
_session.username = token.username
|
|
54
|
+
if (token.error) _session.error = token.error
|
|
55
|
+
return _session
|
|
56
|
+
}
|
|
57
|
+
}
|
|
58
|
+
}
|
|
59
|
+
|
|
60
|
+
export default NextAuth(authOptions)
|
|
@@ -0,0 +1,47 @@
|
|
|
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
|
+
}
|
package/tsconfig.json
ADDED
|
@@ -0,0 +1,104 @@
|
|
|
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": "./lib", /* 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": ["lib", "node_modules"]
|
|
104
|
+
}
|