/go-pkce

Go library for OAuth 2.0 PKCE.

Primary LanguageGoMIT LicenseMIT

PKCE for Go

Build Status Go Report Card Code Coverage Docs License

go-pkce package contains an implementation for OAuth 2.0 PKCE spec, IETF RFC 7636.

Installation

go get github.com/grokify/go-pkce

Or you can manually git clone the repository to $(go env GOPATH)/src/github.com/grokify/go-pkce.

Usage

import("github.com/grokify/go-pkce")

func main() {
  // Create a code_verifier with default 32 byte length.
  codeVerifier := pkce.NewCodeVerifier()

  // Create a code_verifier with a custom length (32-96 bytes)
  codeVerifier, err := pkce.NewCodeVerifierWithLength(96)

  // Create a code_challenge using `S256`
  codeChallenge := pkce.CodeChallengeS256(codeVerifier)
}

Usage with oauth2

import(
  "context"

  "github.com/grokify/go-pkce"
  "golang.org/x/oauth2"
)

func main() {
  // Create a code_verifier with default 32 byte length.
  codeVerifier := pkce.NewCodeVerifier()

  // Create a code_challenge using `S256`
  codeChallenge := pkce.CodeChallengeS256(codeVerifier)

  // Create authorization_code URL using `oauth2.Config`
  authURL := oauth2Config.AuthCodeURL(
    "myState",
    oauth2.SetAuthURLParam(pkce.ParamCodeChallenge, codeChallenge),
    oauth2.SetAuthURLParam(pkce.ParamCodeChallengeMethod, pkce.MethodS256))

  // ... retrieve authorization_code ...

  // Exchange the authorization_code for a token with PKCE.
  token, err := oauth2Config.Exchange(
    context.Background(),
    "myCode",
    oauth2.SetAuthURLParam(pkce.ParamCodeVerifier, codeVerifier),
  )
}

Similar projects