azure-ad.go 4.0 KB

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