pkce.go 2.3 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768
  1. // Copyright 2023 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. import (
  6. "crypto/rand"
  7. "crypto/sha256"
  8. "encoding/base64"
  9. "net/url"
  10. )
  11. const (
  12. codeChallengeKey = "code_challenge"
  13. codeChallengeMethodKey = "code_challenge_method"
  14. codeVerifierKey = "code_verifier"
  15. )
  16. // GenerateVerifier generates a PKCE code verifier with 32 octets of randomness.
  17. // This follows recommendations in RFC 7636.
  18. //
  19. // A fresh verifier should be generated for each authorization.
  20. // S256ChallengeOption(verifier) should then be passed to Config.AuthCodeURL
  21. // (or Config.DeviceAccess) and VerifierOption(verifier) to Config.Exchange
  22. // (or Config.DeviceAccessToken).
  23. func GenerateVerifier() string {
  24. // "RECOMMENDED that the output of a suitable random number generator be
  25. // used to create a 32-octet sequence. The octet sequence is then
  26. // base64url-encoded to produce a 43-octet URL-safe string to use as the
  27. // code verifier."
  28. // https://datatracker.ietf.org/doc/html/rfc7636#section-4.1
  29. data := make([]byte, 32)
  30. if _, err := rand.Read(data); err != nil {
  31. panic(err)
  32. }
  33. return base64.RawURLEncoding.EncodeToString(data)
  34. }
  35. // VerifierOption returns a PKCE code verifier AuthCodeOption. It should be
  36. // passed to Config.Exchange or Config.DeviceAccessToken only.
  37. func VerifierOption(verifier string) AuthCodeOption {
  38. return setParam{k: codeVerifierKey, v: verifier}
  39. }
  40. // S256ChallengeFromVerifier returns a PKCE code challenge derived from verifier with method S256.
  41. //
  42. // Prefer to use S256ChallengeOption where possible.
  43. func S256ChallengeFromVerifier(verifier string) string {
  44. sha := sha256.Sum256([]byte(verifier))
  45. return base64.RawURLEncoding.EncodeToString(sha[:])
  46. }
  47. // S256ChallengeOption derives a PKCE code challenge derived from verifier with
  48. // method S256. It should be passed to Config.AuthCodeURL or Config.DeviceAccess
  49. // only.
  50. func S256ChallengeOption(verifier string) AuthCodeOption {
  51. return challengeOption{
  52. challenge_method: "S256",
  53. challenge: S256ChallengeFromVerifier(verifier),
  54. }
  55. }
  56. type challengeOption struct{ challenge_method, challenge string }
  57. func (p challengeOption) setValue(m url.Values) {
  58. m.Set(codeChallengeMethodKey, p.challenge_method)
  59. m.Set(codeChallengeKey, p.challenge)
  60. }