oidc.go 4.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153
  1. package auth
  2. import (
  3. "context"
  4. "fmt"
  5. "net/http"
  6. "time"
  7. "github.com/coreos/go-oidc/v3/oidc"
  8. "github.com/gravitl/netmaker/logger"
  9. "github.com/gravitl/netmaker/logic"
  10. "github.com/gravitl/netmaker/models"
  11. "github.com/gravitl/netmaker/servercfg"
  12. "golang.org/x/oauth2"
  13. )
  14. const OIDC_TIMEOUT = 10 * time.Second
  15. var oidc_functions = map[string]interface{}{
  16. init_provider: initOIDC,
  17. get_user_info: getOIDCUserInfo,
  18. handle_callback: handleOIDCCallback,
  19. handle_login: handleOIDCLogin,
  20. verify_user: verifyOIDCUser,
  21. }
  22. var oidc_verifier *oidc.IDTokenVerifier
  23. // == handle OIDC authentication here ==
  24. func initOIDC(redirectURL string, clientID string, clientSecret string, issuer string) {
  25. ctx, cancel := context.WithTimeout(context.Background(), OIDC_TIMEOUT)
  26. defer cancel()
  27. provider, err := oidc.NewProvider(ctx, issuer)
  28. if err != nil {
  29. logger.Log(1, "error when initializing OIDC provider with issuer \""+issuer+"\"", err.Error())
  30. return
  31. }
  32. oidc_verifier = provider.Verifier(&oidc.Config{ClientID: clientID})
  33. auth_provider = &oauth2.Config{
  34. ClientID: clientID,
  35. ClientSecret: clientSecret,
  36. RedirectURL: redirectURL,
  37. Endpoint: provider.Endpoint(),
  38. Scopes: []string{oidc.ScopeOpenID, "profile", "email"},
  39. }
  40. }
  41. func handleOIDCLogin(w http.ResponseWriter, r *http.Request) {
  42. var oauth_state_string = logic.RandomString(user_signin_length)
  43. if auth_provider == nil {
  44. handleOauthNotConfigured(w)
  45. return
  46. }
  47. if err := logic.SetState(oauth_state_string); err != nil {
  48. handleOauthNotConfigured(w)
  49. return
  50. }
  51. var url = auth_provider.AuthCodeURL(oauth_state_string)
  52. http.Redirect(w, r, url, http.StatusTemporaryRedirect)
  53. }
  54. func handleOIDCCallback(w http.ResponseWriter, r *http.Request) {
  55. var rState, rCode = getStateAndCode(r)
  56. var content, err = getOIDCUserInfo(rState, rCode)
  57. if err != nil {
  58. logger.Log(1, "error when getting user info from callback:", err.Error())
  59. handleOauthNotConfigured(w)
  60. return
  61. }
  62. _, err = logic.GetUser(content.Email)
  63. if err != nil { // user must not exists, so try to make one
  64. if err = addUser(content.Email); err != nil {
  65. return
  66. }
  67. }
  68. user, err := logic.GetUser(content.Email)
  69. if err != nil {
  70. handleOauthUserNotFound(w)
  71. return
  72. }
  73. if !(user.IsSuperAdmin || user.IsAdmin) {
  74. handleOauthUserNotAllowed(w)
  75. return
  76. }
  77. var newPass, fetchErr = fetchPassValue("")
  78. if fetchErr != nil {
  79. return
  80. }
  81. // send a netmaker jwt token
  82. var authRequest = models.UserAuthParams{
  83. UserName: content.Email,
  84. Password: newPass,
  85. }
  86. var jwt, jwtErr = logic.VerifyAuthRequest(authRequest)
  87. if jwtErr != nil {
  88. logger.Log(1, "could not parse jwt for user", authRequest.UserName, jwtErr.Error())
  89. return
  90. }
  91. logger.Log(1, "completed OIDC OAuth signin in for", content.Email)
  92. http.Redirect(w, r, servercfg.GetFrontendURL()+"/login?login="+jwt+"&user="+content.Email, http.StatusPermanentRedirect)
  93. }
  94. func getOIDCUserInfo(state string, code string) (u *OAuthUser, e error) {
  95. oauth_state_string, isValid := logic.IsStateValid(state)
  96. logger.Log(3, "using oauth state string:,", oauth_state_string)
  97. logger.Log(3, " state string:,", state)
  98. if (!isValid || state != oauth_state_string) && !isStateCached(state) {
  99. return nil, fmt.Errorf("invalid oauth state")
  100. }
  101. defer func() {
  102. if p := recover(); p != nil {
  103. e = fmt.Errorf("getOIDCUserInfo panic: %v", p)
  104. }
  105. }()
  106. ctx, cancel := context.WithTimeout(context.Background(), OIDC_TIMEOUT)
  107. defer cancel()
  108. oauth2Token, err := auth_provider.Exchange(ctx, code)
  109. if err != nil {
  110. return nil, fmt.Errorf("failed to exchange oauth2 token using code \"%s\"", code)
  111. }
  112. rawIDToken, ok := oauth2Token.Extra("id_token").(string)
  113. if !ok {
  114. return nil, fmt.Errorf("failed to get raw id_token from oauth2 token")
  115. }
  116. idToken, err := oidc_verifier.Verify(ctx, rawIDToken)
  117. if err != nil {
  118. return nil, fmt.Errorf("failed to verify raw id_token: \"%s\"", err.Error())
  119. }
  120. u = &OAuthUser{}
  121. if err := idToken.Claims(u); err != nil {
  122. e = fmt.Errorf("error when claiming OIDCUser: \"%s\"", err.Error())
  123. }
  124. return
  125. }
  126. func verifyOIDCUser(token *oauth2.Token) bool {
  127. return token.Valid()
  128. }