diff --git a/pkg/api/pluginproxy/ds_proxy.go b/pkg/api/pluginproxy/ds_proxy.go index 69fe4a999a1..a3e8f05faff 100644 --- a/pkg/api/pluginproxy/ds_proxy.go +++ b/pkg/api/pluginproxy/ds_proxy.go @@ -307,7 +307,7 @@ func checkWhiteList(c *models.ReqContext, host string) bool { func addOAuthPassThruAuth(c *models.ReqContext, req *http.Request) { authInfoQuery := &models.GetAuthInfoQuery{UserId: c.UserId} if err := bus.Dispatch(authInfoQuery); err != nil { - logger.Error("Error fetching oauth information for user", "error", err) + logger.Error("Error fetching oauth information for user", "userid", c.UserId, "username", c.Login, "error", err) return } @@ -318,20 +318,21 @@ func addOAuthPassThruAuth(c *models.ReqContext, req *http.Request) { return } - // TokenSource handles refreshing the token if it has expired - token, err := connect.TokenSource(c.Req.Context(), &oauth2.Token{ + persistedToken := &oauth2.Token{ AccessToken: authInfoQuery.Result.OAuthAccessToken, Expiry: authInfoQuery.Result.OAuthExpiry, RefreshToken: authInfoQuery.Result.OAuthRefreshToken, TokenType: authInfoQuery.Result.OAuthTokenType, - }).Token() + } + // TokenSource handles refreshing the token if it has expired + token, err := connect.TokenSource(c.Req.Context(), persistedToken).Token() if err != nil { - logger.Error("Failed to retrieve access token from oauth provider", "provider", authInfoQuery.Result.AuthModule, "error", err) + logger.Error("Failed to retrieve access token from OAuth provider", "provider", authInfoQuery.Result.AuthModule, "userid", c.UserId, "username", c.Login, "error", err) return } // If the tokens are not the same, update the entry in the DB - if token.AccessToken != authInfoQuery.Result.OAuthAccessToken { + if !tokensEq(persistedToken, token) { updateAuthCommand := &models.UpdateAuthInfoCommand{ UserId: authInfoQuery.Result.UserId, AuthModule: authInfoQuery.Result.AuthModule, @@ -339,10 +340,19 @@ func addOAuthPassThruAuth(c *models.ReqContext, req *http.Request) { OAuthToken: token, } if err := bus.Dispatch(updateAuthCommand); err != nil { - logger.Error("Failed to update access token during token refresh", "error", err) + logger.Error("Failed to update auth info during token refresh", "userid", c.UserId, "username", c.Login, "error", err) return } + logger.Debug("Updated OAuth info while proxying an OAuth pass-thru request", "userid", c.UserId, "username", c.Login) } req.Header.Del("Authorization") req.Header.Add("Authorization", fmt.Sprintf("%s %s", token.Type(), token.AccessToken)) } + +// tokensEq checks for OAuth2 token equivalence given the fields of the struct Grafana is interested in +func tokensEq(t1, t2 *oauth2.Token) bool { + return t1.AccessToken == t2.AccessToken && + t1.RefreshToken == t2.RefreshToken && + t1.Expiry == t2.Expiry && + t1.TokenType == t2.TokenType +}