在Google API控制台中创建一个OAuth客户端ID,并设置重定向URI。保存客户端ID和客户端机密。
安装'Google.Apis.Auth.AspNetCore”和'Google.Apis.Oauth2.v2”。
在'Startup.cs”文件中配置Google授权服务。在'ConfigureServices”方法中添加以下代码:
services
.AddAuthentication(options =>
{
options.DefaultScheme = CookieAuthenticationDefaults.AuthenticationScheme;
options.DefaultChallengeScheme = GoogleOpenIdConnectDefaults.AuthenticationScheme;
})
.AddCookie()
.AddGoogleOpenIdConnect(options =>
{
options.ClientId = Configuration["Google:ClientId"];
options.ClientSecret = Configuration["Google:ClientSecret"];
options.SaveTokens = true;
options.Events.OnCreatingTicket = async context =>
{
// 获取刷新令牌并保存到身份验证令牌中。
var refresh_token = context.Properties.GetTokenValue("refresh_token").ToString();
context.Properties.StoreTokens(new[]
{
new AuthenticationToken { Name = "refresh_token", Value = refresh_token }
});
};
});
注意:应'ClientId”和'ClientSecret”替换为Google API控制台中创建的OAuth客户端ID和客户端机密。
app.UseAuthentication();
app.UseAuthorization();
string refresh_token = await HttpContext.GetTokenAsync("refresh_token");
注意:应该先通过上述步骤进行身份验证才能获取刷新令牌。
完整的'Startup.cs”文件代码示例:
using Google.Apis.Auth.AspNetCore;
using Google.Apis.Oauth2.v2;
using Microsoft.AspNetCore.Authentication;
using Microsoft.AspNetCore.Authentication.Cookies;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;
namespace MyAppNamespace
{
public class Startup
{
public Startup(IConfiguration configuration)
{
Configuration = configuration;
}
public IConfiguration Configuration { get; }
public void ConfigureServices(IServiceCollection services)
{
services
.AddAuthentication(options =>
{
options.DefaultScheme = CookieAuthenticationDefaults.AuthenticationScheme;
options.DefaultChallengeScheme = GoogleOpenIdConnectDefaults.AuthenticationScheme;
})
.AddCookie()
.AddGoogleOpenIdConnect(options =>
{
options.ClientId = Configuration["Google:ClientId"];
options.ClientSecret = Configuration["Google:ClientSecret"];
options.SaveTokens = true;