Git Product home page Git Product logo

auth-token.js's Introduction

auth-token.js

GitHub API token authentication for browsers and Node.js

@latest Build Status

@octokit/auth-token is the simplest of GitHub’s authentication strategies.

It is useful if you want to support multiple authentication strategies, as it’s API is compatible with its sibling packages for basic, GitHub App and OAuth app authentication.

Usage

Browsers

Load @octokit/auth-token directly from cdn.skypack.dev

<script type="module">
  import { createTokenAuth } from "https://cdn.skypack.dev/@octokit/auth-token";
</script>
Node

Install with npm install @octokit/auth-token

const { createTokenAuth } = require("@octokit/auth-token");
// or: import { createTokenAuth } from "@octokit/auth-token";
const auth = createTokenAuth("1234567890abcdef1234567890abcdef12345678");
const authentication = await auth();
// {
//   type: 'token',
//   token: '1234567890abcdef1234567890abcdef12345678',
//   tokenType: 'oauth'
// }

createTokenAuth(token) options

The createTokenAuth method accepts a single argument of type string, which is the token. The passed token can be one of the following:

Examples

// Personal access token or OAuth access token
createTokenAuth("1234567890abcdef1234567890abcdef12345678");

// Installation access token or GitHub Action token
createTokenAuth("v1.d3d433526f780fbcc3129004e2731b3904ad0b86");

auth()

The auth() method has no options. It returns a promise which resolves with the the authentication object.

Authentication object

name type description
type string "token"
token string The provided token.
tokenType string Can be either "oauth" for personal access tokens and OAuth tokens, or "installation" for installation access tokens (includes GITHUB_TOKEN provided to GitHub Actions)

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

auth.hook() hooks directly into the request life cycle. It authenticates the request using the provided token.

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: authorizations } = await auth.hook(
  request,
  "GET /authorizations"
);

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

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

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

Find more information

auth() does not send any requests, it only transforms the provided token string into an authentication object.

Here is a list of things you can do to retrieve further information

Find out what scopes are enabled for oauth tokens

Note that this does not work for installations. There is no way to retrieve permissions based on an installation access tokens.

const TOKEN = "1234567890abcdef1234567890abcdef12345678";

const auth = createTokenAuth(TOKEN);
const authentication = await auth();

const response = await request("HEAD /", {
  headers: authentication.headers,
});
const scopes = response.headers["x-oauth-scopes"].split(/,\s+/);

if (scopes.length) {
  console.log(
    `"${TOKEN}" has ${scopes.length} scopes enabled: ${scopes.join(", ")}`
  );
} else {
  console.log(`"${TOKEN}" has no scopes enabled`);
}

Find out if token is a personal access token or if it belongs to an OAuth app

const TOKEN = "1234567890abcdef1234567890abcdef12345678";

const auth = createTokenAuth(TOKEN);
const authentication = await auth();

const response = await request("HEAD /", {
  headers: authentication.headers,
});
const clientId = response.headers["x-oauth-client-id"];

if (clientId) {
  console.log(
    `"${token}" is an OAuth token, its app’s client_id is ${clientId}.`
  );
} else {
  console.log(`"${token}" is a personal access token`);
}

Find out what permissions are enabled for a repository

Note that the permissions key is not set when authenticated using an installation access token.

const TOKEN = "1234567890abcdef1234567890abcdef12345678";

const auth = createTokenAuth(TOKEN);
const authentication = await auth();

const response = await request("GET /repos/{owner}/{repo}", {
  owner: 'octocat',
  repo: 'hello-world'
  headers: authentication.headers
});

console.log(response.data.permissions)
// {
//   admin: true,
//   push: true,
//   pull: true
// }

Use token for git operations

Both OAuth and installation access tokens can be used for git operations. However, when using with an installation, the token must be prefixed with x-access-token.

This example is using the execa package to run a git push command.

const TOKEN = "1234567890abcdef1234567890abcdef12345678";

const auth = createTokenAuth(TOKEN);
const { token, tokenType } = await auth();
const tokenWithPrefix =
  tokenType === "installation" ? `x-access-token:${token}` : token;

const repositoryUrl = `https://${tokenWithPrefix}@github.com/octocat/hello-world.git`;

const { stdout } = await execa("git", ["push", repositoryUrl]);
console.log(stdout);

License

MIT

auth-token.js's People

Contributors

dependabot[bot] avatar gr2m avatar renovate[bot] avatar greenkeeper[bot] avatar wolfy1339 avatar jovel avatar jhutchings1 avatar oscard0m avatar prettier-toc-me[bot] avatar

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.