Skip to content

Instantly share code, notes, and snippets.

View chenZhenTom's full-sized avatar

cz tom chenZhenTom

View GitHub Profile
public string DecodeIdToken(string idToken, string claim)
{
var handler = new JwtSecurityTokenHandler();
var jwtSecurityToken = handler.ReadJwtToken(idToken);
return jwtSecurityToken.Claims.First(c => c.Type == claim).Value;
}
namespace CloudBackup.Settings
{
public class AppSettings
{
public GoogleDrive GoogleDrive { get; set; }
}
public class GoogleDrive
{
public string ClientId { get; set; }
using System.Text.Json;
using System.Web;
using CloudBackup.Dtos;
using CloudBackup.Settings;
using Google.Apis.Auth.OAuth2;
using Google.Apis.Auth.OAuth2.Flows;
using Google.Apis.Auth.OAuth2.Responses;
using Google.Apis.Drive.v3;
using Microsoft.Extensions.Options;
using CloudBackup.Dtos;
using CloudBackup.Services;
using Microsoft.AspNetCore.Mvc;
namespace CloudBackup.Controllers;
[ApiController]
[Route("api/[Controller]")]
public class GoogleController : ControllerBase
{
[HttpPut("Refresh/AccessToken")]
public async Task<IActionResult> RefreshAccessToken(RefreshAccessTokenRequest request)
{
var token = await GoogleService.RefreshAccesstoken(request.AccessToken, request.RefreshToken);
return Ok(token);
}
public async Task<UpdateCredentialResponse> RefreshAccesstoken(string accessToken, string refreshToken)
{
var uri = "https://oauth2.googleapis.com/token";
var postData = new Dictionary<string, string>
{
{ "grant_type", "refresh_token" },
{ "client_id", AppSettings.Value.GoogleDrive.ClientId },
{ "client_secret", AppSettings.Value.GoogleDrive.ClientSecret },
{ "refresh_token", refreshToken }
[HttpGet("Auth")]
public async Task<IActionResult> Auth([FromQuery]string code, [FromQuery]string state)
{
var token = await GoogleService.ExchangeCodeForToken(code);
return Ok(token);
}
public async Task<string> GetOAuthUri(string state)
{
// 此處的 GoogleDrive.ClientId & GoogleDrive.ClientSecret 就是上一篇申請的用戶端憑證。
// 正常開發請勿將此資料放在 appsettings.json 中,以免洩漏。
var flow = new GoogleAuthorizationCodeFlow(new GoogleAuthorizationCodeFlow.Initializer
{
ClientSecrets = new ClientSecrets
{
ClientId = AppSettings.Value.GoogleDrive.ClientId,
ClientSecret = AppSettings.Value.GoogleDrive.ClientSecret
public async Task<TokenResponse> ExchangeCodeForToken(string code)
{
// 下面的 ClientSecrets, Scopes, RedirectUri 都需要跟上面產生 OAuth URI 時使用的一模一樣才行。
var flow = new GoogleAuthorizationCodeFlow(new GoogleAuthorizationCodeFlow.Initializer
{
ClientSecrets = new ClientSecrets
{
ClientId = AppSettings.Value.GoogleDrive.ClientId,
ClientSecret = AppSettings.Value.GoogleDrive.ClientSecret
},
@chenZhenTom
chenZhenTom / program.cs
Created February 16, 2023 08:17
執行測試
await Task.Run(() =>
{
var calculator = app.Services.GetService<Calculator>();
try
{
calculator.Divide(10, 2);
calculator.Divide(20, 1);
calculator.Divide(10, 0);
}catch (Exception ex)