oidc.go 3.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131
  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. "context"
  6. "errors"
  7. "fmt"
  8. "miniflux.app/v2/internal/model"
  9. "github.com/coreos/go-oidc/v3/oidc"
  10. "golang.org/x/oauth2"
  11. )
  12. // ErrEmptyUsername is returned when the OIDC user profile has no username.
  13. var ErrEmptyUsername = errors.New("oidc: username is empty")
  14. type userClaims struct {
  15. Email string `json:"email"`
  16. Profile string `json:"profile"`
  17. Name string `json:"name"`
  18. PreferredUsername string `json:"preferred_username"`
  19. }
  20. type oidcProvider struct {
  21. clientID string
  22. clientSecret string
  23. redirectURL string
  24. provider *oidc.Provider
  25. }
  26. // NewOidcProvider returns a Provider that authenticates users via OpenID Connect.
  27. // It discovers the OIDC endpoints from the given discovery URL.
  28. func NewOidcProvider(ctx context.Context, clientID, clientSecret, redirectURL, discoveryEndpoint string) (Provider, error) {
  29. provider, err := oidc.NewProvider(ctx, discoveryEndpoint)
  30. if err != nil {
  31. return nil, fmt.Errorf(`oidc: failed to initialize provider %q: %w`, discoveryEndpoint, err)
  32. }
  33. return &oidcProvider{
  34. clientID: clientID,
  35. clientSecret: clientSecret,
  36. redirectURL: redirectURL,
  37. provider: provider,
  38. }, nil
  39. }
  40. func (o *oidcProvider) UserExtraKey() string {
  41. return "openid_connect_id"
  42. }
  43. func (o *oidcProvider) Config() *oauth2.Config {
  44. return &oauth2.Config{
  45. RedirectURL: o.redirectURL,
  46. ClientID: o.clientID,
  47. ClientSecret: o.clientSecret,
  48. Scopes: []string{oidc.ScopeOpenID, "profile", "email"},
  49. Endpoint: o.provider.Endpoint(),
  50. }
  51. }
  52. func (o *oidcProvider) Profile(ctx context.Context, code, codeVerifier string) (*UserProfile, error) {
  53. conf := o.Config()
  54. token, err := conf.Exchange(ctx, code, oauth2.SetAuthURLParam("code_verifier", codeVerifier))
  55. if err != nil {
  56. return nil, fmt.Errorf(`oidc: failed to exchange token: %w`, err)
  57. }
  58. rawIDToken, ok := token.Extra("id_token").(string)
  59. if !ok {
  60. return nil, errors.New(`oidc: no id_token in token response`)
  61. }
  62. verifier := o.provider.Verifier(&oidc.Config{ClientID: o.clientID})
  63. idToken, err := verifier.Verify(ctx, rawIDToken)
  64. if err != nil {
  65. return nil, fmt.Errorf(`oidc: failed to verify id token: %w`, err)
  66. }
  67. userInfo, err := o.provider.UserInfo(ctx, oauth2.StaticTokenSource(token))
  68. if err != nil {
  69. return nil, fmt.Errorf(`oidc: failed to get user info: %w`, err)
  70. }
  71. if idToken.Subject != userInfo.Subject {
  72. return nil, fmt.Errorf(`oidc: id token subject %q does not match userinfo subject %q`, idToken.Subject, userInfo.Subject)
  73. }
  74. profile := &UserProfile{
  75. Key: o.UserExtraKey(),
  76. ID: userInfo.Subject,
  77. }
  78. var userClaims userClaims
  79. if err := userInfo.Claims(&userClaims); err != nil {
  80. return nil, fmt.Errorf(`oidc: failed to parse user claims: %w`, err)
  81. }
  82. // Use the first non-empty value from the claims to set the username.
  83. // The order of preference is: preferred_username, email, name, profile.
  84. for _, value := range []string{userClaims.PreferredUsername, userClaims.Email, userClaims.Name, userClaims.Profile} {
  85. if value != "" {
  86. profile.Username = value
  87. break
  88. }
  89. }
  90. if profile.Username == "" {
  91. return nil, ErrEmptyUsername
  92. }
  93. return profile, nil
  94. }
  95. func (o *oidcProvider) PopulateUserCreationWithProfileID(user *model.UserCreationRequest, profile *UserProfile) {
  96. user.OpenIDConnectID = profile.ID
  97. }
  98. func (o *oidcProvider) PopulateUserWithProfileID(user *model.User, profile *UserProfile) {
  99. user.OpenIDConnectID = profile.ID
  100. }
  101. func (o *oidcProvider) UserProfileID(user *model.User) string {
  102. return user.OpenIDConnectID
  103. }
  104. func (o *oidcProvider) UnsetUserProfileID(user *model.User) {
  105. user.OpenIDConnectID = ""
  106. }