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

GitHub OAuth App authentication for JavaScript

License

NotificationsYou must be signed in to change notification settings

octokit/auth-oauth-app.js

Repository files navigation

GitHub OAuth App authentication for JavaScript

@latestBuild Status

@octokit/auth-oauth-app is implementing one ofGitHub’s authentication strategies.

It implements authentication using an OAuth app’s client ID and secret as well as creating user access tokens GitHub's OAuthweb application flow anddevice flow.

Standalone Usage

Browsers

⚠️@octokit/auth-oauth-app is not meant for usage in the browser. The OAuth APIs to create tokens do not have CORS enabled, and a client secret must not be exposed to the client.

If you know what you are doing, load@octokit/auth-oauth-app directly fromesm.sh

<scripttype="module">import{createOAuthAppAuth}from"https://esm.sh/@octokit/auth-oauth-app";</script>
Node

Install withnpm install @octokit/auth-oauth-app

import{createOAuthAppAuth}from"@octokit/auth-oauth-app";

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

Authenticate as app

constauth=createOAuthAppAuth({clientType:"oauth-app",clientId:"1234567890abcdef1234",clientSecret:"1234567890abcdef1234567890abcdef12345678",});constappAuthentication=awaitauth({type:"oauth-app",});

resolves with

{"type":"oauth-app","clientId":"1234567890abcdef1234","clientSecret":"1234567890abcdef1234567890abcdef12345678","headers": {"authorization":"basic MTIzNDU2Nzg5MGFiY2RlZjEyMzQ6MTIzNDU2Nzg5MGFiY2RlZjEyMzQ1Njc4OTBhYmNkZWYxMjM0NTY3OA=="  }}

Authenticate user using OAuth Web Flow

Exchange code from GitHub's OAuth web flow, seehttps://docs.github.com/en/developers/apps/authorizing-oauth-apps#2-users-are-redirected-back-to-your-site-by-github

constauth=createOAuthAppAuth({clientType:"oauth-app",clientId:"1234567890abcdef1234",clientSecret:"1234567890abcdef1234567890abcdef12345678",});constuserAuthenticationFromWebFlow=awaitauth({type:"oauth-user",code:"random123",state:"mystate123",});

resolves with

{"clientType":"oauth-app","clientId":"1234567890abcdef1234","clientSecret":"1234567890abcdef1234567890abcdef12345678","type":"token","tokenType":"oauth","token":"useraccesstoken123","scopes": []}

Authenticate user using OAuth Device flow

Pass an asynchronousonVerification() method which will be called with the response from step 1 of the device flow. In that function you have to prompt the user to enter the user code at the provided verification URL.

auth() will not resolve until the user entered the code and granted access to the app.

Seehttps://docs.github.com/en/developers/apps/authorizing-oauth-apps#2-users-are-redirected-back-to-your-site-by-github

constauth=createOAuthAppAuth({clientType:"oauth-app",clientId:"1234567890abcdef1234",clientSecret:"1234567890abcdef1234567890abcdef12345678",});constuserAuthenticationFromDeviceFlow=awaitauth({asynconVerification(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 with

{"clientType":"oauth-app","clientId":"1234567890abcdef1234","clientSecret":"1234567890abcdef1234567890abcdef12345678","type":"token","tokenType":"oauth","token":"useraccesstoken123","scopes": []}

Usage with Octokit

Browsers

⚠️@octokit/auth-oauth-app is not meant for usage in the browser. The OAuth APIs to create tokens do not have CORS enabled, and a client secret must not be exposed to the client.

If you know what you are doing, load@octokit/auth-oauth-app and@octokit/core (or a compatible module) directly fromesm.sh

<scripttype="module">import{createOAuthAppAuth}from"https://esm.sh/@octokit/auth-oauth-app";import{Octokit}from"https://esm.sh/@octokit/core";</script>

Node

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

import{Octokit}from"@octokit/core";import{createOAuthAppAuth,createOAuthUserAuth,}from"@octokit/auth-oauth-app";
constappOctokit=newOctokit({authStrategy:createOAuthAppAuth,auth:{clientId:"1234567890abcdef1234",clientSecret:"1234567890abcdef1234567890abcdef12345678",},});// Send requests as appawaitappOctokit.request("POST /application/{client_id}/token",{client_id:"1234567890abcdef1234",access_token:"existingtoken123",});console.log("token is valid");// create a new octokit instance that is authenticated as the userconstuserOctokit=awaitappOctokit.auth({type:"oauth-user",code:"code123",factory:(options)=>{returnnewOctokit({authStrategy:createOAuthUserAuth,auth:options,});},});// Exchanges the code for the user access token authentication on first request// and caches the authentication for successive requestsconst{data:{ login},}=awaituserOctokit.request("GET /user");console.log("Hello, %s!",login);

createOAuthAppAuth(options) ornew Octokit({ auth })

ThecreateOAuthAppAuth method accepts a singleoptions object as argument. The same set of options can be passed asauth to theOctokit constructor when settingauthStrategy: createOAuthAppAuth

name type description
clientIdstringRequired. Find your OAuth app’sClient ID in your account’s developer settings.
clientSecretstringRequired. Find your OAuth app’sClient Secret in your account’s developer settings.
clientTypestring Must be set to either"oauth-app" or"github-app". Defaults to"oauth-app"
requestfunction You can pass in your own@octokit/request instance. For usage with enterprise, setbaseUrl 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",}),});

auth(options) oroctokit.auth(options)

The asyncauth() method returned bycreateOAuthAppAuth(options) accepts different options depending on your use case

Client ID/Client Secret Basic authentication

All REST API routes starting with/applications/{client_id} need to be authenticated using the OAuth/GitHub App's Client ID and a client secret.

name type description
typestringRequired. Must be set to"oauth-app"

OAuth web flow

Exchangecode for a user access token. SeeWeb application flow.

name type description
typestringRequired. Must be set to"oauth-user".
codestringRequired. The authorizationcode which was passed as query parameter to the callback URL from theOAuth web application flow.
redirectUrlstring The URL in your application where users are sent after authorization. Seeredirect urls.
statestring The unguessable random string you provided in Step 1 of theOAuth web application flow.
factoryfunction

When thefactory option is, theauth({type: "oauth-user", code, factory }) call with resolve with whatever thefactory function returns. Thefactory function will be called with all the strategy option thatauth was created with, plus the additional options passed toauth, besidestype andfactory.

For example, you can create a newauth instance for a user usingcreateOAuthUserAuth which implements auto-refreshing tokens, among other features. You can importcreateOAuthUserAuth directly from@octokit/auth-oauth-app which will ensure compatibility.

import{createOAuthAppAuth,createOAuthUserAuth,}from"@octokit/auth-oauth-app";constappAuth=createOAuthAppAuth({clientType:"github-app",clientId:"lv1.1234567890abcdef",clientSecret:"1234567890abcdef1234567890abcdef12345678",});constuserAuth=awaitappAuth({type:"oauth-user",  code,factory:createOAuthUserAuth,});// will create token upon first call, then cache authentication for successive calls,// until token needs to be refreshed (if enabled for the GitHub App)constauthentication=awaituserAuth();

OAuth device flow

Create a user access token without an http redirect. SeeDevice flow.

The device flow does not require a client secret, but it is required as strategy option for@octokit/auth-oauth-app, even for the device flow. If you want to implement the device flow without requiring a client secret, use@octokit/auth-oauth-device.

name type description
typestringRequired. Must be set to"oauth-user".
onVerificationfunction

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

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

constauth=auth({type:"oauth-user",asynconVerification(verification){console.log("Open %s",verification.verification_uri);console.log("Enter code: %s",verification.user_code);awaitprompt("press enter when you are ready to continue");},});
scopesarray of strings Only relevant if theclientType strategy option is set to"oauth-app".Array of OAuth scope names that the user access token should be granted. Defaults to no scopes ([]).
factoryfunction

When thefactory option is, theauth({type: "oauth-user", code, factory }) call with resolve with whatever thefactory function returns. Thefactory function will be called with all the strategy option thatauth was created with, plus the additional options passed toauth, besidestype andfactory.

For example, you can create a newauth instance for a user usingcreateOAuthUserAuth which implements auto-refreshing tokens, among other features. You can importcreateOAuthUserAuth directly from@octokit/auth-oauth-app which will ensure compatibility.

import{createOAuthAppAuth,createOAuthUserAuth,}from"@octokit/auth-oauth-app";constappAuth=createOAuthAppAuth({clientType:"github-app",clientId:"lv1.1234567890abcdef",clientSecret:"1234567890abcdef1234567890abcdef12345678",});constuserAuth=awaitappAuth({type:"oauth-user",  onVerification,factory:createOAuthUserAuth,});// will create token upon first call, then cache authentication for successive calls,// until token needs to be refreshed (if enabled for the GitHub App)constauthentication=awaituserAuth();

Authentication object

The asyncauth(options) method to one of four possible authentication objects

  1. OAuth App authentication forauth({ type: "oauth-app" })
  2. OAuth user access token authentication forauth({ type: "oauth-app" }) and App is an OAuth App (OAuth user access token)
  3. GitHub APP user authentication token with expiring disabled forauth({ type: "oauth-app" }) and App is a GitHub App (user-to-server token)
  4. GitHub APP user authentication token with expiring enabled forauth({ type: "oauth-app" }) and App is a GitHub App (user-to-server token)

OAuth App authentication

name type description
typestring"oauth-app"
clientTypestring"oauth-app" or"github-app"
clientIdstring The client ID as passed to the constructor.
clientSecretstring The client secret as passed to the constructor.
headersobject{ authorization }.

OAuth user access token authentication

name type description
typestring"token"
tokenTypestring"oauth"
clientTypestring"oauth-app"
clientIdstring TheclientId from the strategy options
clientSecretstring TheclientSecret from the strategy options
tokenstring The user access token
scopesarray of strings array of scope names enabled for the token

GitHub APP user authentication token with expiring disabled

name type description
typestring"token"
tokenTypestring"oauth"
clientTypestring"github-app"
clientIdstring The app'sClient ID
clientSecretstring One of the app's client secrets
tokenstring The user access token

GitHub APP user authentication token with expiring enabled

name type description
typestring"token"
tokenTypestring"oauth"
clientTypestring"github-app"
clientIdstring The app'sClient ID
clientSecretstring One of the app's client secrets
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

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 usingclientId andclientSecret as basic auth for the API endpoints that support it. It throws an error in other cases.

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

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

const{data:user}=awaitauth.hook(request,"POST /applications/{client_id}/token",{client_id:"1234567890abcdef1234",access_token:"token123",},);

Or it can be passed as option torequest().

constrequestWithAuth=request.defaults({request:{hook:auth.hook,},});const{data:user}=awaitrequestWithAuth("POST /applications/{client_id}/token",{client_id:"1234567890abcdef1234",access_token:"token123",},);

Types

import{// strategy optionsOAuthAppStrategyOptions,GitHubAppStrategyOptions,// auth optionsAppAuthOptions,WebFlowAuthOptions,OAuthAppDeviceFlowAuthOptions,GitHubAppDeviceFlowAuthOptions,// auth interfacesOAuthAppAuthInterface,GitHubAuthInterface,// authentication objectAppAuthentication,OAuthAppUserAuthentication,GitHubAppUserAuthentication,GitHubAppUserAuthenticationWithExpiration,}from"@octokit/auth-oauth-app";

Implementation details

Client ID and secret can be passed as Basic auth in theAuthorization header in order to get a higher rate limit compared to unauthenticated requests. This is meant for the use on servers only: never expose an OAuth client secret on a client such as a web application!

auth.hook will set the correct authentication header automatically based on the request URL. For allOAuth Application endpoints, theAuthorization header is set to basic auth. For all other endpoints and token is retrieved and used in theAuthorization header. The token is cached and used for succeeding requests.

To reset the cached access token, you can do this

const{ token}=awaitauth({type:"oauth-user"});awaitauth.hook(request,"POST /applications/{client_id}/token",{client_id:"1234567890abcdef1234",access_token:token,});

The internally cached token will be replaced and used for succeeding requests. See also"the REST API documentation".

See also:octokit/oauth-authorization-url.js.

License

MIT

About

GitHub OAuth App authentication for JavaScript

Topics

Resources

License

Code of conduct

Security policy

Stars

Watchers

Forks

Packages

No packages published

Contributors17


[8]ページ先頭

©2009-2025 Movatter.jp