|
| 1 | +// Copyright 2014 The Go Authors. All rights reserved. |
| 2 | +// Use of this source code is governed by a BSD-style |
| 3 | +// license that can be found in the LICENSE file. |
| 4 | +package oauth2 |
| 5 | + |
| 6 | +import ( |
| 7 | + "crypto/rand" |
| 8 | + "crypto/sha256" |
| 9 | + "encoding/base64" |
| 10 | + "io" |
| 11 | + "net/url" |
| 12 | +) |
| 13 | + |
| 14 | +const ( |
| 15 | + codeChallengeKey = "code_challenge" |
| 16 | + codeChallengeMethodKey = "code_challenge_method" |
| 17 | + codeVerifierKey = "code_verifier" |
| 18 | +) |
| 19 | + |
| 20 | +// GenerateVerifier generates a code verifier with 32 octets of randomness. |
| 21 | +// This follows recommendations in RFC 7636. |
| 22 | +// |
| 23 | +// A fresh verifier should be generated for each authorization. |
| 24 | +func GenerateVerifier() string { |
| 25 | + // "RECOMMENDED that the output of a suitable random number generator be |
| 26 | + // used to create a 32-octet sequence. The octet sequence is then |
| 27 | + // base64url-encoded to produce a 43-octet URL-safe string to use as the |
| 28 | + // code verifier." |
| 29 | + // https://datatracker.ietf.org/doc/html/rfc7636#section-4.1 |
| 30 | + data := make([]byte, 32) |
| 31 | + if _, err := io.ReadFull(rand.Reader, data); err != nil { |
| 32 | + panic(err) |
| 33 | + } |
| 34 | + return base64.URLEncoding.EncodeToString(data) |
| 35 | +} |
| 36 | + |
| 37 | +// S256ChallengeOption should be passed to Config.AuthCodeURL. It derives an |
| 38 | +// S256 code challenge from verifier following RFC 7636 (PKCE). |
| 39 | +func S256ChallengeOption(verifier string) AuthCodeOption { |
| 40 | + sha := sha256.Sum256([]byte(verifier)) |
| 41 | + challenge := base64.URLEncoding.EncodeToString(sha[:]) |
| 42 | + return challengeOption{challenge_method: "S256", challenge: challenge} |
| 43 | +} |
| 44 | + |
| 45 | +type challengeOption struct{ challenge_method, challenge string } |
| 46 | + |
| 47 | +func (p challengeOption) setValue(m url.Values) { |
| 48 | + m.Set(codeChallengeMethodKey, p.challenge_method) |
| 49 | + m.Set(codeChallengeKey, p.challenge) |
| 50 | +} |
| 51 | + |
| 52 | +// VerifierOption should be passed to Config.Exchange. It describes a RFC 7636 |
| 53 | +// (PKCE) code verifier. |
| 54 | +func VerifierOption(verifier string) AuthCodeOption { |
| 55 | + return setParam{k: codeVerifierKey, v: verifier} |
| 56 | +} |
0 commit comments