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

Octokit authentication strategy for OAuth clients

License

NotificationsYou must be signed in to change notification settings

octokit/auth-oauth-user.js

Repository files navigation

Octokit authentication strategy for OAuth user authentication

@latestBuild Status

Important:@octokit/auth-oauth-user requires your app'sclient_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 theclient_secret, but does not work in browsers due to CORS constraints.

Table of contents

Features

Standalone usage

Browsers

Load@octokit/auth-oauth-user directly fromesm.sh

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

Node

Install withnpm install @octokit/auth-oauth-user

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

Exchange code from OAuth web flow

constauth=createOAuthUserAuth({clientId:"1234567890abcdef1234",clientSecret:"1234567890abcdef1234567890abcdef12345678",code:"code123",// optionalstate:"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 callsconst{ token}=awaitauth();

AboutGitHub's OAuth web flow

OAuth Device flow

constauth=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}=awaitauth();

AboutGitHub's OAuth device flow

Use an existing authentication

constauth=createOAuthUserAuth({clientId:"1234567890abcdef1234",clientSecret:"1234567890abcdef1234567890abcdef12345678",clientType:"oauth-app",token:"token123",});// will return the passed authenticationconst{ token}=awaitauth();

SeeAuthentication object.

Usage with Octokit

Browsers

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

Node

Install withnpm 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";
constoctokit=newOctokit({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 requestsconst{data:{ login},}=awaitoctokit.request("GET /user");console.log("Hello, %s!",login);

createOAuthUserAuth(options) ornew Octokit({ auth })

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

When using GitHub's OAuth web flow

name type description
clientIdstringRequired. Client ID of your GitHub/OAuth App. Find it on your app's settings page.
clientSecretstringRequired. Client Secret for your GitHub/OAuth App. Create one on your app's settings page.
clientTypestring Either"oauth-app" or"github-app". Defaults to"oauth-app".
codestring

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

statestring

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

redirectUrlstring

Theredirect_uri parameter you provided inStep 1 of GitHub's OAuth web application flow.

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",}),});

When using GitHub's OAuth device flow

name type description
clientIdstringRequired. Client ID of your GitHub/OAuth App. Find it on your app's settings page.
clientSecretstringRequired. Client Secret for your GitHub/OAuth App. TheclientSecret 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.
clientTypestring Either"oauth-app" or"github-app". Defaults to"oauth-app".
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=createOAuthUserAuth({clientId:"1234567890abcdef1234",clientSecret:"1234567890abcdef1234567890abcdef12345678",onVerification(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");},});
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",onVerification(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");},request:request.defaults({baseUrl:"https://ghe.my-company.com/api/v3",}),});

When passing an existing authentication object

name type description
clientTypestringRequired. Either"oauth-app" or"github".
clientIdstringRequired. Client ID of your GitHub/OAuth App. Find it on your app's settings page.
clientSecretstringRequired. Client Secret for your GitHub/OAuth App. Create one on your app's settings page.
tokenstringRequired. The user access token
scopesarray of stringsRequired ifclientType is set to"oauth-app". Array of OAuth scope names the token was granted
refreshTokenstring Only relevant ifclientType is set to"github-app" and token expiration is enabled.
expiresAtstring Only relevant ifclientType is set to"github-app" and token expiration is enabled. Date timestamp inISO 8601 standard. Example:2022-01-01T08:00:0.000Z
refreshTokenExpiresAtstring Only relevant ifclientType is set to"github-app" and token expiration is enabled. Date timestamp inISO 8601 standard. Example:2021-07-01T00:00:0.000Z
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",}),});

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

auth(options) oroctokit.auth(options)

The asyncauth() method is returned bycreateOAuthUserAuth(options) or set on theoctokit instance when theOctokit constructor was called withauthStrategy: createOAuthUserAuth.

Onceauth() 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. Callingauth({ type: "reset" }) will replace the internally cached authentication.

Resolves with anauthentication object.

name type description
typestring

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

Possible values fortype 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
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
onTokenCreatedfunction callback invoked when a token is "reset" or "refreshed"
invalidboolean

Eitherundefined ortrue. Will be set totrue if the token was invalided explicitly or found to be invalid

GitHub APP user authentication token with expiring disabled

name type description
typestring"token"
tokenTypestring"oauth"
clientTypestring"github-app"
clientIdstring TheclientId from the strategy options
clientSecretstring TheclientSecret from the strategy options
tokenstring The user access token
onTokenCreatedfunction callback invoked when a token is "reset" or "refreshed"
invalidboolean

Eitherundefined ortrue. Will be set totrue if the token was invalided explicitly or found to be invalid

GitHub APP user authentication token with expiring enabled

name type description
typestring"token"
tokenTypestring"oauth"
clientTypestring"github-app"
clientIdstring TheclientId from the strategy options
clientSecretstring TheclientSecret from the strategy options
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
invalidboolean

Eitherundefined ortrue. Will be set totrue 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.

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,"GET /user");

Or it can be passed as option torequest().

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

Types

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

Contributing

SeeCONTRIBUTING.md

License

MIT

About

Octokit authentication strategy for OAuth clients

Topics

Resources

License

Code of conduct

Security policy

Stars

Watchers

Forks

Packages

No packages published

Contributors12


[8]ページ先頭

©2009-2025 Movatter.jp