azure-ad.go 4.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134
  1. package auth
  2. import (
  3. "context"
  4. "encoding/json"
  5. "fmt"
  6. "io"
  7. "net/http"
  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. "golang.org/x/oauth2/microsoft"
  14. )
  15. var azure_ad_functions = map[string]interface{}{
  16. init_provider: initAzureAD,
  17. get_user_info: getAzureUserInfo,
  18. handle_callback: handleAzureCallback,
  19. handle_login: handleAzureLogin,
  20. verify_user: verifyAzureUser,
  21. }
  22. type azureOauthUser struct {
  23. UserPrincipalName string `json:"userPrincipalName" bson:"userPrincipalName"`
  24. AccessToken string `json:"accesstoken" bson:"accesstoken"`
  25. }
  26. // == handle azure ad authentication here ==
  27. func initAzureAD(redirectURL string, clientID string, clientSecret string) {
  28. auth_provider = &oauth2.Config{
  29. RedirectURL: redirectURL,
  30. ClientID: clientID,
  31. ClientSecret: clientSecret,
  32. Scopes: []string{"User.Read"},
  33. Endpoint: microsoft.AzureADEndpoint(servercfg.GetAzureTenant()),
  34. }
  35. }
  36. func handleAzureLogin(w http.ResponseWriter, r *http.Request) {
  37. var oauth_state_string = logic.RandomString(16)
  38. if auth_provider == nil && servercfg.GetFrontendURL() != "" {
  39. http.Redirect(w, r, servercfg.GetFrontendURL()+"/login?oauth=callback-error", http.StatusTemporaryRedirect)
  40. return
  41. } else if auth_provider == nil {
  42. fmt.Fprintf(w, "%s", []byte("no frontend URL was provided and an OAuth login was attempted\nplease reconfigure server to use OAuth or use basic credentials"))
  43. return
  44. }
  45. if err := logic.SetState(oauth_state_string); err != nil {
  46. http.Redirect(w, r, servercfg.GetFrontendURL()+"/login?oauth=callback-error", http.StatusTemporaryRedirect)
  47. return
  48. }
  49. var url = auth_provider.AuthCodeURL(oauth_state_string)
  50. http.Redirect(w, r, url, http.StatusTemporaryRedirect)
  51. }
  52. func handleAzureCallback(w http.ResponseWriter, r *http.Request) {
  53. var content, err = getAzureUserInfo(r.FormValue("state"), r.FormValue("code"))
  54. if err != nil {
  55. logger.Log(1, "error when getting user info from azure:", err.Error())
  56. http.Redirect(w, r, servercfg.GetFrontendURL()+"/login?oauth=callback-error", http.StatusTemporaryRedirect)
  57. return
  58. }
  59. _, err = logic.GetUser(content.UserPrincipalName)
  60. if err != nil { // user must not exists, so try to make one
  61. if err = addUser(content.UserPrincipalName); err != nil {
  62. return
  63. }
  64. }
  65. var newPass, fetchErr = fetchPassValue("")
  66. if fetchErr != nil {
  67. return
  68. }
  69. // send a netmaker jwt token
  70. var authRequest = models.UserAuthParams{
  71. UserName: content.UserPrincipalName,
  72. Password: newPass,
  73. }
  74. var jwt, jwtErr = logic.VerifyAuthRequest(authRequest)
  75. if jwtErr != nil {
  76. logger.Log(1, "could not parse jwt for user", authRequest.UserName)
  77. return
  78. }
  79. logger.Log(1, "completed azure OAuth sigin in for", content.UserPrincipalName)
  80. http.Redirect(w, r, servercfg.GetFrontendURL()+"/login?login="+jwt+"&user="+content.UserPrincipalName, http.StatusPermanentRedirect)
  81. }
  82. func getAzureUserInfo(state string, code string) (*azureOauthUser, error) {
  83. oauth_state_string, isValid := logic.IsStateValid(state)
  84. if !isValid || state != oauth_state_string {
  85. return nil, fmt.Errorf("invalid oauth state")
  86. }
  87. var token, err = auth_provider.Exchange(context.Background(), code)
  88. if err != nil {
  89. return nil, fmt.Errorf("code exchange failed: %s", err.Error())
  90. }
  91. var data []byte
  92. data, err = json.Marshal(token)
  93. if err != nil {
  94. return nil, fmt.Errorf("failed to convert token to json: %s", err.Error())
  95. }
  96. var httpReq, reqErr = http.NewRequest("GET", "https://graph.microsoft.com/v1.0/me", nil)
  97. if reqErr != nil {
  98. return nil, fmt.Errorf("failed to create request to GitHub")
  99. }
  100. httpReq.Header.Set("Authorization", "Bearer "+token.AccessToken)
  101. response, err := http.DefaultClient.Do(httpReq)
  102. if err != nil {
  103. return nil, fmt.Errorf("failed getting user info: %s", err.Error())
  104. }
  105. defer response.Body.Close()
  106. contents, err := io.ReadAll(response.Body)
  107. if err != nil {
  108. return nil, fmt.Errorf("failed reading response body: %s", err.Error())
  109. }
  110. var userInfo = &azureOauthUser{}
  111. if err = json.Unmarshal(contents, userInfo); err != nil {
  112. return nil, fmt.Errorf("failed parsing email from response data: %s", err.Error())
  113. }
  114. userInfo.AccessToken = string(data)
  115. return userInfo, nil
  116. }
  117. func verifyAzureUser(token *oauth2.Token) bool {
  118. return token.Valid()
  119. }