Movatterモバイル変換


[0]ホーム

URL:


Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings

Request methods to create and refresh user access tokens for OAuth and GitHub Apps

License

NotificationsYou must be signed in to change notification settings

octokit/oauth-methods.js

Repository files navigation

Set of stateless request methods to create, check, reset, refresh, and delete user access tokens for OAuth and GitHub Apps

@latestBuild Status

The OAuth endpoints related to user access tokens are not all part of GitHub's REST API and they behave slightly different. The methods exported by `@octokit/normalize the differences so you don't have to.

Usage

Browsers

@octokit/oauth-methods is not meant for browser usage.

Some of the methods will work, but others do not have CORS headers enabled and will fail (exchangeWebFlowCode(),createDeviceCode(),exchangeDeviceCode(),refreshToken()). Also the Client Secret should not be exposed to clients as it can be used for aPerson-in-the-middle attack.

Node

Install withnpm install @octokit/core @octokit/oauth-methods

import{exchangeWebFlowCode,createDeviceCode,exchangeDeviceCode,checkToken,refreshToken,scopeToken,resetToken,deleteToken,deleteAuthorization,}from"@octokit/oauth-methods";

Important

As we useconditional exports, you will need to adapt yourtsconfig.json by setting"moduleResolution": "node16", "module": "node16".

See the TypeScript docs onpackage.json "exports".
See thishelpful guide on transitioning to ESM from@sindresorhus

OAuth Web Flow

After a user granted access to an OAuth App or GitHub App onStep 1 of GitHub's OAuth Web Flow, they get redirected to a URL controlled by your app with a?code=... query parameter.

You can exchange that code for a user access token as described inStep 2 of GitHub's OAuth Web Flow.

SettingclientType is required because there are slight differences between"oauth-app" and"github-app". Most importantly, GitHub Apps do not support scopes.

const{ data, authentication}=awaitexchangeWebFlowCode({clientType:"oauth-app",clientId:"1234567890abcdef1234",clientSecret:"1234567890abcdef12347890abcdef12345678",code:"code123",scopes:["repo"],});

data is the raw response data.authentication is aUser Authentication object.

OAuth Device Flow

Instep 1 of GitHub's OAuth Device Flow, you need to create a device and user code

const{data:{ device_code, user_code, verification_uri},}=awaitcreateDeviceCode({clientType:"oauth-app",clientId:"1234567890abcdef1234",scopes:["repo"],});

Instep 2 of GitHub's OAuth Device Flow, the user has to enteruser_code onverification_uri (https://github.com/login/device unless you use GitHub Enterprise Server).

Once the user entered the code and granted access, you can exchange thedevice_code for a user access token instep 3 of GitHub's OAuth Device Flow

const{ data, authentication}=awaitexchangeDeviceCode({clientType:"oauth-app",clientId:"1234567890abcdef1234",code:device_code,});

data is the raw response data.authentication is aUser Authentication object.

Methods

getWebFlowAuthorizationUrl()

This is a wrapper around@octokit/oauth-authorization-url that accepts arequest option instead ofbaseUrl for consistency with the other OAuth methods.getWebFlowAuthorizationUrl() is a synchronous method and does not send any request.

const{ url}=getWebFlowAuthorizationUrl({clientType:"oauth-app",clientId:"1234567890abcdef1234",scopes:["repo"],});

Options

name type description
clientIdstringRequired. The client ID you received from GitHub when you registered.
clientTypestringRequired. Must be set to either"oauth-app" or"github-app".
redirectUrlstring The URL in your application where users will be sent after authorization. SeeRedirect URLs in GitHub’s Developer Guide.
loginstring Suggests a specific account to use for signing in and authorizing the app.
scopesarray of strings

Only relevant ifclientType is set to"oauth-app".

An array of scope names (or: space-delimited list of scopes). If not provided, scope defaults to an empty list for users that have not authorized any scopes for the application. For users who have authorized scopes for the application, the user won't be shown the OAuth authorization page with the list of scopes. Instead, this step of the flow will automatically complete with the set of scopes the user has authorized for the application. For example, if a user has already performed the web flow twice and has authorized one token with user scope and another token with repo scope, a third web flow that does not provide a scope will receive a token with user and repo scope.

Defaults to[].

statestring An unguessable random string. It is used to protect against cross-site request forgery attacks. Defaults toMath.random().toString(36).substr(2).
allowSignupboolean Whether or not unauthenticated users will be offered an option to sign up for GitHub during the OAuth flow. Usefalse in the case that a policy prohibits signups. Defaults totrue.
requestfunction You can pass in your own@octokit/request instance. For usage with enterprise, setbaseUrl to the REST API root endpoint. Example:
import{request}from"@octokit/request";const{ url}=getWebFlowAuthorizationUrl({clientType:"oauth-app",clientId:"1234567890abcdef1234",scopes:["repo"],request:request.defaults({baseUrl:"https://ghe.my-company.com/api/v3",}),});

ThegetWebFlowAuthorizationUrl method is synchronous and returns an object with the following properties.

name type description
allowSignupboolean Returnsoptions.allowSignup if it was set. Defaults totrue.
clientTypestring Returnsoptions.clientType
clientIdstring Returnsoptions.clientId.
loginstring Returnsoptions.login if it was set. Defaults tonull.
redirectUrlstring Returnsoptions.redirectUrl if it was set. Defaults tonull.
scopesarray of strings

Only set ifoptions.clientType is set to"oauth-app".

Returns an array of strings. Returnsoptions.scopes if it was set and turns the string into an array if a string was passed, otherwise[].

statestring Returnsoptions.state if it was set. Defaults toMath.random().toString(36).substr(2).
urlstring The authorization URL

exchangeWebFlowCode()

const{ data, authentication}=awaitexchangeWebFlowCode({clientType:"oauth-app",clientId:"1234567890abcdef1234",clientSecret:"1234567890abcdef12347890abcdef12345678",code:"code123",});

Options

name type description
clientTypestringRequired. Must be set to either"oauth-app" or"github-app"
clientIdstringRequired. Your app's client ID
clientSecretstringRequired. One of your app's client secrets
codestringRequired. The code from GitHub's OAuth flow redirect's?code=... query parameter
redirectUrlstring TheredirectUrl option you passed togetWebFlowAuthorizationUrl()
requestfunction You can pass in your own@octokit/request instance. For usage with enterprise, setbaseUrl to the REST API root endpoint. Example:
import{request}from"@octokit/request";const{ data, authentication}=awaitexchangeWebFlowCode({clientType:"oauth-app",clientId:"1234567890abcdef1234",clientSecret:"1234567890abcdef12347890abcdef12345678",code:"code123",request:request.defaults({baseUrl:"https://ghe.my-company.com/api/v3",}),});

Resolves with an@octokit/request response object forPOST /login/oauth/access_token (JSON) with an additionalauthentication key which is theauthentication object.

createDeviceCode()

const{ data, authentication}=awaitcreateDeviceCode({clientType:"oauth-app",clientId:"1234567890abcdef1234",scopes:["repo"],});

Options

name type description
clientTypestringRequired. Must be set to either"oauth-app" or"github-app"
clientIdstringRequired. Your app's client ID
scopesarray of strings

Only permitted ifclientType is set to"oauth-app". GitHub Apps do not support scopes.

Array ofscope names you want to request for the user access token.

requestfunction You can pass in your own@octokit/request instance. For usage with enterprise, setbaseUrl to the REST API root endpoint. Example:
import{request}from"@octokit/request";const{ data}=awaitcreateDeviceCode({clientType:"oauth-app",clientId:"1234567890abcdef1234",scopes:["repo"],request:request.defaults({baseUrl:"https://ghe.my-company.com/api/v3",}),});

Resolves with an@octokit/request response object forPOST https://github.com/login/device/code (JSON).

exchangeDeviceCode()

const{ data, authentication}=awaitexchangeDeviceCode({clientType:"oauth-app",clientId:"1234567890abcdef1234",code:"code123",});
name type description
clientTypestringRequired. Must be set to either"oauth-app" or"github-app"
clientIdstringRequired. Your app's client ID
codestringRequired. Thedevice_code from thecreateDeviceCode() response
requestfunction You can pass in your own@octokit/request instance. For usage with enterprise, setbaseUrl to the REST API root endpoint. Example:
import{request}from"@octokit/request";const{ data, authentication}=awaitexchangeDeviceCode({clientType:"oauth-app",clientId:"1234567890abcdef1234",code:"code123",request:request.defaults({baseUrl:"https://ghe.my-company.com/api/v3",}),});

checkToken()

const{ data, authentication}=awaitcheckToken({clientType:"oauth-app",clientId:"1234567890abcdef1234",clientSecret:"1234567890abcdef12347890abcdef12345678",token:"usertoken123",});

Options

name type description
clientTypestringRequired. Must be set to either"oauth-app" or"github-app"
clientIdstringRequired. Your app's client ID
clientSecretstringRequired. One of your app's client secrets
tokenstringRequired. The user access token to check
requestfunction You can pass in your own@octokit/request instance. For usage with enterprise, setbaseUrl to the REST API root endpoint. Example:
import{request}from"@octokit/request";const{ data, authentication}=awaitcheckToken({clientType:"oauth-app",clientId:"1234567890abcdef1234",clientSecret:"1234567890abcdef12347890abcdef12345678",token:"usertoken123",request:request.defaults({baseUrl:"https://ghe.my-company.com/api/v3",}),});

Resolves with an@octokit/request response object forPOST /applications/{client_id}/token with an additionalauthentication key which is theauthentication object. Note that theauthentication object will not include the keys for expiring authentication.

refreshToken()

Expiring user access tokens are currently in preview. You canenable them for any of your GitHub apps. OAuth Apps do not support expiring user access tokens

When a user access token expires it can berefreshed using a refresh token. Refreshing a token invalidates the current user access token.

const{ data, authentication}=awaitrefreshToken({clientType:"github-app",clientId:"lv1.1234567890abcdef",clientSecret:"1234567890abcdef12347890abcdef12345678",refreshToken:"r1.refreshtoken123",});

Options

name type description
clientTypestring Must be set to"github-app"
clientIdstringRequired. Your app's client ID
clientSecretstringRequired. One of your app's client secrets
refreshTokenstringRequired. The refresh token that was received alongside the user access token.
requestfunction You can pass in your own@octokit/request instance. For usage with enterprise, setbaseUrl to the REST API root endpoint. Example:
import{request}from"@octokit/request";const{ data, authentication}=awaitrefreshToken({clientType:"github-app",clientId:"lv1.1234567890abcdef",clientSecret:"1234567890abcdef12347890abcdef12345678",refreshToken:"r1.refreshtoken123",request:request.defaults({baseUrl:"https://ghe.my-company.com/api/v3",}),});

Resolves with an@octokit/request response object forPOST /login/oauth/access_token with an additionalauthentication key which is theGitHub App expiring user authentication.

scopeToken()

const{ data, authentication}=awaitscopeToken({clientType:"github-app",clientId:"lv1.1234567890abcdef",clientSecret:"1234567890abcdef12347890abcdef12345678",token:"usertoken123",target:"octokit",repositories:["oauth-methods.js"],permissions:{issues:"write",},});

Options

name type description
clientTypestringRequired. Must be set to"github-app".
clientIdstringRequired. Your app's client ID
clientSecretstringRequired. One of your app's client secrets
targetstringRequired unlesstargetId is set. The name of the user or organization to scope the user-to-server access token to.
targetIdintegerRequired unlesstarget is set. The ID of the user or organization to scope the user-to-server access token to.
repositoriesarray of strings The list of repository names to scope the user-to-server access token to.repositories may not be specified ifrepository_ids is specified.
repository_idsarray of integers The list of repository IDs to scope the user-to-server access token to.repositories may not be specified ifrepositories is specified.
permissionsobject The permissions granted to the user-to-server access token. SeeGitHub App Permissions.
requestfunction You can pass in your own@octokit/request instance. For usage with enterprise, setbaseUrl to the REST API root endpoint. Example:
import{request}from"@octokit/request";const{ data, authentication}=awaitscopeToken({clientType:"github-app",clientId:"lv1.1234567890abcdef",token:"usertoken123",target:"octokit",repositories:["oauth-methods.js"],permissions:{issues:"write",},request:request.defaults({baseUrl:"https://ghe.my-company.com/api/v3",}),});

Resolves with an@octokit/request response object forPOST /applications/{client_id}/token/scoped with an additionalauthentication key which is the newauthentication object.

resetToken()

const{ data, authentication}=awaitresetToken({clientType:"oauth-app",clientId:"1234567890abcdef1234",clientSecret:"1234567890abcdef12347890abcdef12345678",token:"usertoken123",});

Options

name type description
clientTypestring Must be set to"oauth-app" or"github-app".
clientIdstringRequired. Your app's client ID
clientSecretstringRequired. One of your app's client secrets
tokenstringRequired. The user access token to reset
requestfunction You can pass in your own@octokit/request instance. For usage with enterprise, setbaseUrl to the REST API root endpoint. Example:
import{request}from"@octokit/request";const{ data, authentication}=awaitresetToken({clientId:"1234567890abcdef1234",clientSecret:"secret",token:"usertoken123",request:request.defaults({baseUrl:"https://ghe.my-company.com/api/v3",}),});

Resolves with an@octokit/request response object forPOST /applications/{client_id}/token with an additionalauthentication key which is the newauthentication object.

deleteToken()

const{ status}=awaitdeleteToken({clientType:"oauth-app",clientId:"1234567890abcdef1234",clientSecret:"1234567890abcdef12347890abcdef12345678",token:"usertoken123",});

Options

name type description
clientTypestring Must be set to"oauth-app" or"github-app"
clientIdstringRequired. Your app's client ID
clientSecretstringRequired. One of your app's client secrets
tokenstringRequired. The user access token to delete
requestfunction You can pass in your own@octokit/request instance. For usage with enterprise, setbaseUrl to the REST API root endpoint. Example:
import{request}from"@octokit/request";const{ data, authentication}=awaitdeleteToken({clientId:"1234567890abcdef1234",clientSecret:"secret",token:"usertoken123",request:request.defaults({baseUrl:"https://ghe.my-company.com/api/v3",}),});

Resolves with an@octokit/request response object forDELETE /applications/{client_id}/token (which is an empty204 response).

deleteAuthorization()

const{ status}=awaitdeleteAuthorization({clientType:"oauth-app",clientId:"1234567890abcdef1234",clientSecret:"1234567890abcdef12347890abcdef12345678",token:"usertoken123",});

Options

name type description
clientTypestring Must be set to"oauth-app" or"github-app"
clientIdstringRequired. Your app's client ID
clientSecretstringRequired. One of your app's client secrets
tokenstringRequired. A valid user access token for the authorization
requestfunction You can pass in your own@octokit/request instance. For usage with enterprise, setbaseUrl to the REST API root endpoint. Example:
import{request}from"@octokit/request";const{ data, authentication}=awaitdeleteAuthorization({clientId:"1234567890abcdef1234",clientSecret:"secret",token:"usertoken123",request:request.defaults({baseUrl:"https://ghe.my-company.com/api/v3",}),});

Resolves with an@octokit/request response object forDELETE /applications/{client_id}/grant (which is an empty204 response).

Authentication object

Theauthentication object returned by the methods have one of three formats.

  1. OAuth APP authentication token
  2. GitHub APP non-expiring 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

Note that theclientSecret may not be set when usingexchangeDeviceCode() asclientSecret is not required for the OAuth device flow.

OAuth APP authentication

name type description
clientTypestring"oauth-app"
clientIdstring The app'sClient ID
tokenstring The user access token
scopesarray of strings array of scope names enabled for the token

GitHub App with non-expiring user authentication

name type description
clientTypestring"github-app"
clientIdstring The app'sClient ID
tokenstring The user access token

GitHub App with expiring user authentication

name type description
clientTypestring"github-app"
clientIdstring The app'sClient ID
tokenstring The user access token
refreshTokenstring The refresh token
expiresAtstring Date timestamp inISO 8601 standard. Example:2022-01-01T08:00:0.000Z
refreshTokenExpiresAtstring Date timestamp inISO 8601 standard. Example:2021-07-01T00:00:0.000Z

Types

import{OAuthAppAuthentication,GitHubAppAuthentication,GitHubAppAuthenticationWithExpiration,GetWebFlowAuthorizationUrlOAuthAppOptions,GetWebFlowAuthorizationUrlGitHubAppOptions,GetWebFlowAuthorizationUrlOAuthAppResult,GetWebFlowAuthorizationUrlGitHubAppResult,CheckTokenOAuthAppOptions,CheckTokenGitHubAppOptions,CheckTokenOAuthAppResponse,CheckTokenGitHubAppResponse,ExchangeWebFlowCodeOAuthAppOptions,ExchangeWebFlowCodeGitHubAppOptions,ExchangeWebFlowCodeOAuthAppResponse,ExchangeWebFlowCodeGitHubAppResponse,CreateDeviceCodeOAuthAppOptions,CreateDeviceCodeGitHubAppOptions,CreateDeviceCodeDeviceTokenResponse,ExchangeDeviceCodeOAuthAppOptionsWithoutClientSecret,ExchangeDeviceCodeOAuthAppOptions,ExchangeDeviceCodeGitHubAppOptionsWithoutClientSecret,ExchangeDeviceCodeGitHubAppOptions,ExchangeDeviceCodeOAuthAppResponse,ExchangeDeviceCodeOAuthAppResponseWithoutClientSecret,ExchangeDeviceCodeGitHubAppResponse,ExchangeDeviceCodeGitHubAppResponseWithoutClientSecret,RefreshTokenOptions,RefreshTokenResponse,ScopeTokenOptions,ScopeTokenResponse,ResetTokenOAuthAppOptions,ResetTokenGitHubAppOptions,ResetTokenOAuthAppResponse,ResetTokenGitHubAppResponse,DeleteTokenOAuthAppOptions,DeleteTokenGitHubAppOptions,DeleteTokenResponse,DeleteAuthorizationOAuthAppOptions,DeleteAuthorizationGitHubAppOptions,DeleteAuthorizationResponse,}from"@octokit/oauth-methods";

Contributing

SeeCONTRIBUTING.md

License

MIT

About

Request methods to create and refresh user access tokens for OAuth and GitHub Apps

Topics

Resources

License

Code of conduct

Stars

Watchers

Forks

Packages

No packages published

Contributors15


[8]ページ先頭

©2009-2025 Movatter.jp