octokit / auth-oauth-user.js Goto Github PK
View Code? Open in Web Editor NEWOctokit authentication strategy for OAuth clients
License: MIT License
Octokit authentication strategy for OAuth clients
License: MIT License
The following API responds with a 404 {"error":"Not Found"}
error: https://github.com/login/oauth/access_token
.
I have tried the following approaches:
octokit 3.1.2
$ curl -X POST \
-H "Content-Type: application/x-www-form-urlencoded" \
-H "User-Agent: axios/0.21.1" \
-H "Accept: application/json" \
-d "client_id=XXXXXX" \
-d "client_secret=XXXXXXX" \
-d "grant_type=authorization_code" \
-d "code=XXXXXX" \
-d "redirect_uri=https://example.com" \
https://github.com/login/oauth/access_token
{"error":"Not Found"}
Hello everyone!
I am trying to run successive requests with one octokit instance and on the second request I'm getting this error:
RequestError [HttpError]: The code passed is incorrect or expired. (bad_verification_code, https://docs.github.com/apps/managing-oauth-apps/troubleshooting-oauth-app-access-token-request-errors/#bad-verification-code)
I'm using Next.js, passing the code from the frontend to an API route. Here's the code of the API route:
import type { NextApiRequest, NextApiResponse } from "next";
import { createOAuthUserAuth } from "@octokit/auth-oauth-user";
import { Octokit } from "@octokit/rest";
export default async function handler(
req: NextApiRequest,
res: NextApiResponse
) {
const { code } = req.body;
// Logs the expected code
console.log("code", code);
const octokit = new Octokit({
authStrategy: createOAuthUserAuth,
auth: {
clientId: process.env.NEXT_PUBLIC_CLIENT_ID,
clientSecret: process.env.CLIENT_SECRET,
code,
},
});
// First request
// Copied over from the documentation, at https://github.com/octokit/auth-oauth-user.js#usage-with-octokit
const {
data: { login },
} = await octokit.rest.users.getAuthenticated();
// Logs my GitHub username, as expected
console.log("Hello, %s!", login);
// Second request
// Throws an error
await octokit.rest.git.getRef({
owner: "sine-fdn",
repo: "tandem",
ref: "heads/main",
});
res.status(200).json({ data: `${req.body}` });
}
I am new to octokit, so I am sorry if I'm missing something that should be clear.
Thank you very much for your work and for your attention!
What happened?
When using the authentication strategy together with @octokit/core
and adding hooks, the hooks are not triggered for internal requests (e.g. to https://github.com/login/oauth/access_token
):
import { Octokit } from '@octokit/core';
import { createOAuthUserAuth } from '@octokit/auth-oauth-user';
import fetchMock from 'fetch-mock';
describe('With Octokit', () => {
test('hooks', async () => {
const fm = fetchMock
.sandbox()
.postOnce('https://github.com/login/oauth/access_token', {
body: {
access_token: 'ghu_dummyToken',
expires_in: 28800,
refresh_token: 'ghr_dummyRefreshToken',
refresh_token_expires_in: 15811200,
scope: '',
token_type: 'bearer',
},
headers: {
date: new Date().toISOString(),
},
})
.getOnce(
{
url: 'https://api.github.com/user',
headers: { authorization: 'token ghu_dummyToken' },
},
{}
);
const octokit = new Octokit({
authStrategy: createOAuthUserAuth,
auth: {
clientId: '1234567890abcdef1234',
clientSecret: '1234567890abcdef1234567890abcdef12345678',
code: 'code123',
},
request: {
fetch: fm,
},
});
const mockedErrorRequestHook = jest.fn();
const mockedBeforeRequestHook = jest.fn();
const mockedAfterRequestHook = jest.fn();
const mockedWrapRequestHook = jest.fn((request, options) =>
request(options)
);
octokit.hook.error('request', mockedErrorRequestHook);
octokit.hook.before('request', mockedBeforeRequestHook);
octokit.hook.after('request', mockedAfterRequestHook);
octokit.hook.wrap('request', mockedWrapRequestHook);
// Exchanges the code for the user access token authentication on first request
// and caches the authentication for successive requests
await octokit.request('GET /user');
// First call to https://github.com/login/oauth/access_token
// Second call to https://api.github.com/user
expect(fm.calls().length).toBe(2); // passes
expect(mockedErrorRequestHook).not.toHaveBeenCalled(); // passes
expect(mockedBeforeRequestHook).toHaveBeenCalledTimes(2); // fails: 1
expect(mockedAfterRequestHook).toHaveBeenCalledTimes(2); // fails: 1
expect(mockedWrapRequestHook).toHaveBeenCalledTimes(2); // fails: 1
});
});
x-ref: octokit/octokit.js#2294 (comment)
What did you expect to happen?
That the hooks are also called for the defined hooks, when internal requests are made.
Follow up to #1
What’s missing?
auth({ type: "scope" })
The feature to Create a scoped access token is not yet implemented.
I think it shouldn't work like auth({ type: "reset" })
, because creating a scoped token does not invalidate the current token. I think what we should do is to reuse the factory
pattern from @octokit/auth-app
which would make it possible to create a new octokit
instance from the current one, and the new instance would be authenticated using the scoped token, or we could create a new auth
instance like this
const scopedAuth = await auth({
type: "scope",
target: 123,
repos: [456],
factory: createOAuthUserAuth,
});
In order to make the above code possible, createOAuthUserAuth()
would need to accept additional options specific to scoping user-to-server access tokens, which might not be to bad of an idea anyway.
Alternatives you tried
scopeToken()
from @octokit/oauth-methods
works to create the scoped authentication.
There is an error with this repository's Renovate configuration that needs to be fixed. As a precaution, Renovate will stop PRs until it is resolved.
Location: package.json
Error type: The renovate configuration file contains some invalid settings
Message: Invalid configuration option: @pika/pack, Invalid configuration option: author, Invalid configuration option: jest, Invalid configuration option: keywords, Invalid configuration option: license, Invalid configuration option: name, Invalid configuration option: packageRules[0].@octokit/auth-oauth-device, Invalid configuration option: packageRules[0].@octokit/oauth-methods, Invalid configuration option: packageRules[0].@octokit/request, Invalid configuration option: packageRules[0].@octokit/types, Invalid configuration option: packageRules[0].btoa-lite, Invalid configuration option: packageRules[0].universal-user-agent, Invalid configuration option: packageRules[1].@octokit/core, Invalid configuration option: packageRules[1].@octokit/tsconfig, Invalid configuration option: packageRules[1].@pika/pack, Invalid configuration option: packageRules[1].@pika/plugin-build-node, Invalid configuration option: packageRules[1].@pika/plugin-build-web, Invalid configuration option: packageRules[1].@pika/plugin-ts-standard-pkg, Invalid configuration option: packageRules[1].@types/btoa-lite, Invalid configuration option: packageRules[1].@types/jest, Invalid configuration option: packageRules[1].@types/node, Invalid configuration option: packageRules[1].fetch-mock, Invalid configuration option: packageRules[1].jest, Invalid configuration option: packageRules[1].mockdate, Invalid configuration option: packageRules[1].prettier, Invalid configuration option: packageRules[1].semantic-release, Invalid configuration option: packageRules[1].semantic-release-plugin-update-version-in-files, Invalid configuration option: packageRules[1].ts-jest, Invalid configuration option: packageRules[1].typescript, Invalid configuration option: publishConfig, Invalid configuration option: release, Invalid configuration option: renovate, Invalid configuration option: scripts, Invalid configuration option: version
What’s missing?
When an access token is created (either from the OAuth code
or by exchanging the refreshToken
) during a request I want a way to retrieve the authentication payload to save it for later usage (e.g. in a database):
token
refreshToken
expiresAt
refreshTokenExpiresAt
Idea of implementation (octokit/octokit.js#2294 (comment)):
@octokit/auth-oauth-user
already has anonVerification
option, we could add a newonTokenCreated
option, which could pass a flag whether it was a refresh or not?
Why?
The library provides on the fly token refresh (See code), when providing the refreshToken
and expiresAt
like this:
import { createOAuthUserAuth } from '@octokit/auth-oauth-user';
import { graphql } from '@octokit/graphql';
const {
accessToken,
accessTokenExpiresAt,
refreshToken,
refreshTokenExpiresAt,
} = await getTokenFromDatabase();
const auth = createOAuthUserAuth({
clientId: secretStore.getGithubClientId(),
clientSecret: secretStore.getGithubClientSecret(),
clientType: 'github-app',
token: accessToken,
expiresAt: accessTokenExpiresAt.toISOString(),
refreshToken,
refreshTokenExpiresAt: refreshTokenExpiresAt.toISOString(),
});
const apiClient = graphql.defaults({
request: {
hook: auth.hook,
},
});
However it is impossible to detect whether the token was renewed during a request against the API this way and save the refreshed token back to the database.
Also see the discussion here for more information: octokit/octokit.js#2294
Alternatives you tried
--
This issue contains a list of Renovate updates and their statuses.
These updates are awaiting their schedule. Click on a checkbox to get an update now.
A declarative, efficient, and flexible JavaScript library for building user interfaces.
🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.
TypeScript is a superset of JavaScript that compiles to clean JavaScript output.
An Open Source Machine Learning Framework for Everyone
The Web framework for perfectionists with deadlines.
A PHP framework for web artisans
Bring data to life with SVG, Canvas and HTML. 📊📈🎉
JavaScript (JS) is a lightweight interpreted programming language with first-class functions.
Some thing interesting about web. New door for the world.
A server is a program made to process requests and deliver data to clients.
Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.
Some thing interesting about visualization, use data art
Some thing interesting about game, make everyone happy.
We are working to build community through open source technology. NB: members must have two-factor auth.
Open source projects and samples from Microsoft.
Google ❤️ Open Source for everyone.
Alibaba Open Source for everyone
Data-Driven Documents codes.
China tencent open source team.