@youngshand/payload-auth-plugin
Version:
A temporary fork for testing of Authentication plugin for Payload CMS, use @payload-auth-plugin
48 lines (47 loc) • 2.28 kB
JavaScript
// src/core/protocols/oauth/oidc_callback.ts
import { parseCookies } from "payload";
import * as oauth from "oauth4webapi";
import { getCallbackURL } from "../../utils/cb.js";
import { MissingOrInvalidSession } from "../../errors/consoleErrors.js";
async function OIDCCallback(pluginType, request, providerConfig, session_callback) {
const parsedCookies = parseCookies(request.headers);
const code_verifier = parsedCookies.get("__session-code-verifier");
const nonce = parsedCookies.get("__session-oauth-nonce");
const clientOrigin = parsedCookies.get("__session-client-origin");
if (!code_verifier || !clientOrigin) {
throw new MissingOrInvalidSession;
}
const { client_id, client_secret, issuer, algorithm, profile } = providerConfig;
const client = {
client_id
};
const clientAuth = oauth.ClientSecretPost(client_secret ?? "");
const current_url = new URL(request.url);
const callback_url = getCallbackURL(request.payload.config.serverURL, pluginType, providerConfig.id);
const issuer_url = new URL(issuer);
const as = await oauth.discoveryRequest(issuer_url, { algorithm }).then((response2) => oauth.processDiscoveryResponse(issuer_url, response2));
const params = oauth.validateAuthResponse(as, client, current_url, providerConfig?.params?.state || undefined);
const grantResponse = await oauth.authorizationCodeGrantRequest(as, client, clientAuth, params, callback_url.toString(), code_verifier);
let body = await grantResponse.json();
let response = new Response(JSON.stringify(body), grantResponse);
if (Array.isArray(body.scope)) {
body.scope = body.scope.join(" ");
response = new Response(JSON.stringify(body), grantResponse);
}
const token_result = await oauth.processAuthorizationCodeResponse(as, client, response, {
expectedNonce: nonce,
requireIdToken: true
});
const claims = oauth.getValidatedIdTokenClaims(token_result);
const userInfoResponse = await oauth.userInfoRequest(as, client, token_result.access_token);
const result = await oauth.processUserInfoResponse(as, client, claims.sub, userInfoResponse);
return session_callback(profile({
sub: result.sub,
name: result.name,
email: result.email,
picture: result.picture
}), clientOrigin);
}
export {
OIDCCallback
};