azure-ad.go 4.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127
  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. 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. var url = auth_provider.AuthCodeURL(oauth_state_string)
  46. http.Redirect(w, r, url, http.StatusTemporaryRedirect)
  47. }
  48. func handleAzureCallback(w http.ResponseWriter, r *http.Request) {
  49. var content, err = getAzureUserInfo(r.FormValue("state"), r.FormValue("code"))
  50. if err != nil {
  51. logger.Log(1, "error when getting user info from azure:", err.Error())
  52. http.Redirect(w, r, servercfg.GetFrontendURL()+"/login?oauth=callback-error", http.StatusTemporaryRedirect)
  53. return
  54. }
  55. _, err = logic.GetUser(content.UserPrincipalName)
  56. if err != nil { // user must not exists, so try to make one
  57. if err = addUser(content.UserPrincipalName); err != nil {
  58. return
  59. }
  60. }
  61. var newPass, fetchErr = fetchPassValue("")
  62. if fetchErr != nil {
  63. return
  64. }
  65. // send a netmaker jwt token
  66. var authRequest = models.UserAuthParams{
  67. UserName: content.UserPrincipalName,
  68. Password: newPass,
  69. }
  70. var jwt, jwtErr = logic.VerifyAuthRequest(authRequest)
  71. if jwtErr != nil {
  72. logger.Log(1, "could not parse jwt for user", authRequest.UserName)
  73. return
  74. }
  75. logger.Log(1, "completed azure OAuth sigin in for", content.UserPrincipalName)
  76. http.Redirect(w, r, servercfg.GetFrontendURL()+"/login?login="+jwt+"&user="+content.UserPrincipalName, http.StatusPermanentRedirect)
  77. }
  78. func getAzureUserInfo(state string, code string) (*azureOauthUser, error) {
  79. if state != oauth_state_string {
  80. return nil, fmt.Errorf("invalid oauth state")
  81. }
  82. var token, err = auth_provider.Exchange(context.Background(), code)
  83. if err != nil {
  84. return nil, fmt.Errorf("code exchange failed: %s", err.Error())
  85. }
  86. var data []byte
  87. data, err = json.Marshal(token)
  88. if err != nil {
  89. return nil, fmt.Errorf("failed to convert token to json: %s", err.Error())
  90. }
  91. var httpReq, reqErr = http.NewRequest("GET", "https://graph.microsoft.com/v1.0/me", nil)
  92. if reqErr != nil {
  93. return nil, fmt.Errorf("failed to create request to GitHub")
  94. }
  95. httpReq.Header.Set("Authorization", "Bearer "+token.AccessToken)
  96. response, err := http.DefaultClient.Do(httpReq)
  97. if err != nil {
  98. return nil, fmt.Errorf("failed getting user info: %s", err.Error())
  99. }
  100. defer response.Body.Close()
  101. contents, err := io.ReadAll(response.Body)
  102. if err != nil {
  103. return nil, fmt.Errorf("failed reading response body: %s", err.Error())
  104. }
  105. var userInfo = &azureOauthUser{}
  106. if err = json.Unmarshal(contents, userInfo); err != nil {
  107. return nil, fmt.Errorf("failed parsing email from response data: %s", err.Error())
  108. }
  109. userInfo.AccessToken = string(data)
  110. return userInfo, nil
  111. }
  112. func verifyAzureUser(token *oauth2.Token) bool {
  113. return token.Valid()
  114. }