@@ -109,6 +109,31 @@ public string RefreshAccessToken(string refreshToken, string clientId, string cl
109109 return accessToken ;
110110 }
111111
112+ /// <summary>
113+ /// Refresh and create new access token with given refresh token. This overload only works if credentials stored in appsettings.json.
114+ /// </summary>
115+ /// <param name="refreshToken"></param>
116+ /// <returns></returns>
117+ public string RefreshAccessToken ( string refreshToken )
118+ {
119+ string clientId = GetClientId ( ) ;
120+ string clientSecret = GetClientSecret ( ) ;
121+ string encodedRedirectUrl = HttpUtility . UrlEncode ( GetRedirectUrl ( ) ) ;
122+
123+ var client = HttpClientFactory . CreateClient ( ) ;
124+ client . DefaultRequestHeaders . Accept . Add ( new MediaTypeWithQualityHeaderValue ( "application/x-www-form-urlencoded" ) ) ;
125+ var content = new StringContent ( $ "refresh_token={ refreshToken } &client_id={ clientId } &client_secret={ clientSecret } &redirect_uri={ encodedRedirectUrl } &scope=&grant_type=refresh_token", Encoding . UTF8 , "application/x-www-form-urlencoded" ) ;
126+
127+ var request = client . PostAsync ( "https://oauth2.googleapis.com/token" , content ) . Result ;
128+
129+ var result = request . Content . ReadAsStringAsync ( ) . Result ;
130+
131+ var jsonResult = JsonDocument . Parse ( result ) ;
132+ string accessToken = jsonResult . RootElement . GetProperty ( "access_token" ) . ToString ( ) ;
133+
134+ return accessToken ;
135+ }
136+
112137 /// <summary>
113138 /// Get client id. Only works when client id stored in appsettings.json. You can choose the root value that google credentials stored.
114139 /// </summary>
@@ -129,6 +154,16 @@ public string GetClientSecret(string rootValue = "GoogleClient")
129154 return Configuration . GetSection ( rootValue ) . GetSection ( "client_secret" ) . Value ;
130155 }
131156
157+ /// <summary>
158+ /// Get redirect url. Only works when url stored in appsettings.json. You can choose the root value that google credentials stored.
159+ /// </summary>
160+ /// <param name="rootValue"></param>
161+ /// <returns></returns>
162+ public string GetRedirectUrl ( string rootValue = "GoogleClient" )
163+ {
164+ return Configuration . GetSection ( rootValue ) . GetSection ( "redirect_url" ) . Value ;
165+ }
166+
132167 /// <summary>
133168 /// Get project id. Only works when client id stored in appsettings.json. You can choose the root value that google credentials stored.
134169 /// </summary>
0 commit comments