authorization.go 1.5 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556
  1. // SPDX-FileCopyrightText: Copyright The Miniflux Authors. All rights reserved.
  2. // SPDX-License-Identifier: Apache-2.0
  3. package oauth2 // import "miniflux.app/v2/internal/oauth2"
  4. import (
  5. "crypto/sha256"
  6. "encoding/base64"
  7. "golang.org/x/oauth2"
  8. "miniflux.app/v2/internal/crypto"
  9. )
  10. // Authorization holds the OAuth2 authorization URL, state parameter, and PKCE code verifier.
  11. type Authorization struct {
  12. url string
  13. state string
  14. codeVerifier string
  15. }
  16. // RedirectURL returns the OAuth2 authorization URL to redirect the user to.
  17. func (a *Authorization) RedirectURL() string {
  18. return a.url
  19. }
  20. // State returns the random state parameter used for CSRF protection.
  21. func (a *Authorization) State() string {
  22. return a.state
  23. }
  24. // CodeVerifier returns the PKCE code verifier associated with this authorization.
  25. func (a *Authorization) CodeVerifier() string {
  26. return a.codeVerifier
  27. }
  28. // GenerateAuthorization creates a new Authorization with a random state and PKCE code challenge
  29. // derived from the given OAuth2 configuration.
  30. func GenerateAuthorization(config *oauth2.Config) *Authorization {
  31. codeVerifier := crypto.GenerateRandomStringHex(32)
  32. sum := sha256.Sum256([]byte(codeVerifier))
  33. state := crypto.GenerateRandomStringHex(24)
  34. authURL := config.AuthCodeURL(
  35. state,
  36. oauth2.SetAuthURLParam("code_challenge_method", "S256"),
  37. oauth2.SetAuthURLParam("code_challenge", base64.RawURLEncoding.EncodeToString(sum[:])),
  38. )
  39. return &Authorization{
  40. url: authURL,
  41. state: state,
  42. codeVerifier: codeVerifier,
  43. }
  44. }