Giter Club home page Giter Club logo

auth-oauth-user.js's Introduction

auth-oauth-user.js

Octokit authentication strategy for OAuth user authentication

@latest Build Status

Important: @octokit/auth-oauth-user requires your app's client_secret, which must not be exposed. If you are looking for an OAuth user authentication strategy that can be used on a client (browser, IoT, CLI), check out @octokit/auth-oauth-user-client. Note that @octokit/auth-oauth-user-client requires a backend. The only exception is @octokit/auth-oauth-device which does not require the client_secret, but does not work in browsers due to CORS constraints.

Table of contents

Features

Standalone usage

Browsers

Load @octokit/auth-oauth-user directly from esm.sh

<script type="module">
  import { createOAuthUserAuth } from "https://esm.sh/@octokit/auth-oauth-user";
</script>

Node

Install with npm install @octokit/auth-oauth-user

import { createOAuthUserAuth } from "@octokit/auth-oauth-user";

Exchange code from OAuth web flow

const auth = createOAuthUserAuth({
  clientId: "1234567890abcdef1234",
  clientSecret: "1234567890abcdef1234567890abcdef12345678",
  code: "code123",
  // optional
  state: "state123",
  redirectUrl: "https://acme-inc.com/login",
});

// Exchanges the code for the user access token authentication on first call
// and caches the authentication for successive calls
const { token } = await auth();

About GitHub's OAuth web flow

OAuth Device flow

const auth = createOAuthUserAuth({
  clientId: "1234567890abcdef1234",
  clientSecret: "1234567890abcdef1234567890abcdef12345678",
  onVerification(verification) {
    // verification example
    // {
    //   device_code: "3584d83530557fdd1f46af8289938c8ef79f9dc5",
    //   user_code: "WDJB-MJHT",
    //   verification_uri: "https://github.com/login/device",
    //   expires_in: 900,
    //   interval: 5,
    // };

    console.log("Open %s", verification.verification_uri);
    console.log("Enter code: %s", verification.user_code);
  },
});

// resolves once the user entered the `user_code` on `verification_uri`
const { token } = await auth();

About GitHub's OAuth device flow

Use an existing authentication

const auth = createOAuthUserAuth({
  clientId: "1234567890abcdef1234",
  clientSecret: "1234567890abcdef1234567890abcdef12345678",
  clientType: "oauth-app",
  token: "token123",
});

// will return the passed authentication
const { token } = await auth();

See Authentication object.

Usage with Octokit

Browsers

@octokit/auth-oauth-user cannot be used in the browser. It requires clientSecret to be set which must not be exposed to clients, and some of the OAuth APIs it uses do not support CORS.

Node

Install with npm install @octokit/core @octokit/auth-oauth-user. Optionally replace @octokit/core with a compatible module

import { Octokit } from "@octokit/core";
import { createOAuthUserAuth } from "@octokit/auth-oauth-user";
const octokit = new Octokit({
  authStrategy: createOAuthUserAuth,
  auth: {
    clientId: "1234567890abcdef1234",
    clientSecret: "1234567890abcdef1234567890abcdef12345678",
    code: "code123",
  },
});

// Exchanges the code for the user access token authentication on first request
// and caches the authentication for successive requests
const {
  data: { login },
} = await octokit.request("GET /user");
console.log("Hello, %s!", login);

createOAuthUserAuth(options) or new Octokit({ auth })

The createOAuthUserAuth method accepts a single options object as argument. The same set of options can be passed as auth to the Octokit constructor when setting authStrategy: createOAuthUserAuth

When using GitHub's OAuth web flow

name type description
clientId string Required. Client ID of your GitHub/OAuth App. Find it on your app's settings page.
clientSecret string Required. Client Secret for your GitHub/OAuth App. Create one on your app's settings page.
clientType string Either "oauth-app" or "github-app". Defaults to "oauth-app".
code string

Required. The authorization code which was passed as query parameter to the callback URL from GitHub's OAuth web application flow.

state string

The unguessable random string you provided in Step 1 of GitHub's OAuth web application flow.

redirectUrl string

The redirect_uri parameter you provided in Step 1 of GitHub's OAuth web application flow.

request function You can pass in your own @octokit/request instance. For usage with enterprise, set baseUrl to the API root endpoint. Example:
import { request } from "@octokit/request";
createOAuthAppAuth({
  clientId: "1234567890abcdef1234",
  clientSecret: "1234567890abcdef1234567890abcdef12345678",
  request: request.defaults({
    baseUrl: "https://ghe.my-company.com/api/v3",
  }),
});

When using GitHub's OAuth device flow

name type description
clientId string Required. Client ID of your GitHub/OAuth App. Find it on your app's settings page.
clientSecret string Required. Client Secret for your GitHub/OAuth App. The clientSecret is not needed for the OAuth device flow itself, but it is required for resetting, refreshing, and invalidating a token. Find the Client Secret on your app's settings page.
clientType string Either "oauth-app" or "github-app". Defaults to "oauth-app".
onVerification function

Required. A function that is called once the device and user codes were retrieved

The onVerification() callback can be used to pause until the user completes step 2, which might result in a better user experience.

const auth = createOAuthUserAuth({
  clientId: "1234567890abcdef1234",
  clientSecret: "1234567890abcdef1234567890abcdef12345678",
  onVerification(verification) {
    console.log("Open %s", verification.verification_uri);
    console.log("Enter code: %s", verification.user_code);

    await prompt("press enter when you are ready to continue");
  },
});
request function You can pass in your own @octokit/request instance. For usage with enterprise, set baseUrl to the API root endpoint. Example:
import { request } from "@octokit/request";
createOAuthAppAuth({
  clientId: "1234567890abcdef1234",
  clientSecret: "1234567890abcdef1234567890abcdef12345678",
  onVerification(verification) {
    console.log("Open %s", verification.verification_uri);
    console.log("Enter code: %s", verification.user_code);

    await prompt("press enter when you are ready to continue");
  },
  request: request.defaults({
    baseUrl: "https://ghe.my-company.com/api/v3",
  }),
});

When passing an existing authentication object

name type description
clientType string Required. Either "oauth-app" or "github".
clientId string Required. Client ID of your GitHub/OAuth App. Find it on your app's settings page.
clientSecret string Required. Client Secret for your GitHub/OAuth App. Create one on your app's settings page.
token string Required. The user access token
scopes array of strings Required if clientType is set to "oauth-app". Array of OAuth scope names the token was granted
refreshToken string Only relevant if clientType is set to "github-app" and token expiration is enabled.
expiresAt string Only relevant if clientType is set to "github-app" and token expiration is enabled. Date timestamp in ISO 8601 standard. Example: 2022-01-01T08:00:0.000Z
refreshTokenExpiresAt string Only relevant if clientType is set to "github-app" and token expiration is enabled. Date timestamp in ISO 8601 standard. Example: 2021-07-01T00:00:0.000Z
request function You can pass in your own @octokit/request instance. For usage with enterprise, set baseUrl to the API root endpoint. Example:
import { request } from "@octokit/request";
createOAuthAppAuth({
  clientId: "1234567890abcdef1234",
  clientSecret: "1234567890abcdef1234567890abcdef12345678",
  request: request.defaults({
    baseUrl: "https://ghe.my-company.com/api/v3",
  }),
});

Important

As we use conditional exports, you will need to adapt your tsconfig.json by setting "moduleResolution": "node16", "module": "node16".

See the TypeScript docs on package.json "exports".
See this helpful guide on transitioning to ESM from @sindresorhus

auth(options) or octokit.auth(options)

The async auth() method is returned by createOAuthUserAuth(options) or set on the octokit instance when the Octokit constructor was called with authStrategy: createOAuthUserAuth.

Once auth() receives a valid authentication object it caches it in memory and uses it for subsequent calls. It also caches if the token is invalid and no longer tries to send any requests. If the authentication is using a refresh token, a new token will be requested as needed. Calling auth({ type: "reset" }) will replace the internally cached authentication.

Resolves with an authentication object.

name type description
type string

Without setting type auth will return the current authentication object, or exchange the code from the strategy options on first call. If the current authentication token is expired, the tokens will be refreshed.

Possible values for type are

  • "get": returns the token from internal state and creates it if none was created yet
  • "check": sends request to verify the validity of the current token
  • "reset": invalidates current token and replaces it with a new one
  • "refresh": GitHub Apps only, and only if expiring user tokens are enabled.
  • "delete": invalidates current token
  • "deleteAuthorization": revokes OAuth access for application. All tokens for the current user created by the same app are invalidated. The user will be prompted to grant access again during the next OAuth web flow.

Authentication object

There are three possible results

  1. OAuth APP authentication token
  2. GitHub APP user authentication token with expiring disabled
  3. GitHub APP user authentication token with expiring enabled

The differences are

  1. scopes is only present for OAuth Apps
  2. refreshToken, expiresAt, refreshTokenExpiresAt are only present for GitHub Apps, and only if token expiration is enabled

OAuth APP authentication token

name type description
type string "token"
tokenType string "oauth"
clientType string "oauth-app"
clientId string The clientId from the strategy options
clientSecret string The clientSecret from the strategy options
token string The user access token
scopes array of strings array of scope names enabled for the token
onTokenCreated function callback invoked when a token is "reset" or "refreshed"
invalid boolean

Either undefined or true. Will be set to true if the token was invalided explicitly or found to be invalid

GitHub APP user authentication token with expiring disabled

name type description
type string "token"
tokenType string "oauth"
clientType string "github-app"
clientId string The clientId from the strategy options
clientSecret string The clientSecret from the strategy options
token string The user access token
onTokenCreated function callback invoked when a token is "reset" or "refreshed"
invalid boolean

Either undefined or true. Will be set to true if the token was invalided explicitly or found to be invalid

GitHub APP user authentication token with expiring enabled

name type description
type string "token"
tokenType string "oauth"
clientType string "github-app"
clientId string The clientId from the strategy options
clientSecret string The clientSecret from the strategy options
token string The user access token
refreshToken string The refresh token
expiresAt string Date timestamp in ISO 8601 standard. Example: 2022-01-01T08:00:0.000Z
refreshTokenExpiresAt string Date timestamp in ISO 8601 standard. Example: 2021-07-01T00:00:0.000Z
invalid boolean

Either undefined or true. Will be set to true if the token was invalided explicitly or found to be invalid

auth.hook(request, route, parameters) or auth.hook(request, options)

auth.hook() hooks directly into the request life cycle. It amends the request to authenticate correctly based on the request URL.

The request option is an instance of @octokit/request. The route/options parameters are the same as for the request() method.

auth.hook() can be called directly to send an authenticated request

const { data: user } = await auth.hook(request, "GET /user");

Or it can be passed as option to request().

const requestWithAuth = request.defaults({
  request: {
    hook: auth.hook,
  },
});

const { data: user } = await requestWithAuth("GET /user");

Types

import {
  GitHubAppAuthentication,
  GitHubAppAuthenticationWithExpiration,
  GitHubAppAuthOptions,
  GitHubAppStrategyOptions,
  GitHubAppStrategyOptionsDeviceFlow,
  GitHubAppStrategyOptionsExistingAuthentication,
  GitHubAppStrategyOptionsExistingAuthenticationWithExpiration,
  GitHubAppStrategyOptionsWebFlow,
  OAuthAppAuthentication,
  OAuthAppAuthOptions,
  OAuthAppStrategyOptions,
  OAuthAppStrategyOptionsDeviceFlow,
  OAuthAppStrategyOptionsExistingAuthentication,
  OAuthAppStrategyOptionsWebFlow,
} from "@octokit/auth-oauth-user";

Contributing

See CONTRIBUTING.md

License

MIT

auth-oauth-user.js's People

Contributors

aarondewes avatar gr2m avatar jsoref avatar kfcampbell avatar nickfloyd avatar octokitbot avatar ofhouse avatar oscard0m avatar renovate[bot] avatar wolfy1339 avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar

auth-oauth-user.js's Issues

Successive requests return RequestError [HttpError] [...] bad_verification_code

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!

Callback that gets triggered on token creation / refresh

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 an onVerification option, we could add a new onTokenCreated 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

--

Action Required: Fix Renovate Configuration

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

[BUG]: Getting a "Not Found" error while exchanging code for a token

What happened?

The following API responds with a 404 {"error":"Not Found"} error: https://github.com/login/oauth/access_token.

I have tried the following approaches:

  1. cURL call
  2. new Octokit(
  3. createOAuthUserAuth(

Versions

octokit 3.1.2

Relevant log output

$ 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"}

Code of Conduct

  • I agree to follow this project's Code of Conduct

Dependency Dashboard

This issue contains a list of Renovate updates and their statuses.

Awaiting Schedule

These updates are awaiting their schedule. Click on a checkbox to get an update now.

  • build(deps): lock file maintenance

  • Check this box to trigger a request for Renovate to run again on this repository

Octokit hooks are not triggered for token requests

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.

Create scoped authentication

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.

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.