Google API Consoleでの設定
- Google API Consoleにアクセスして新しいプロジェクトを作成
2.「認証情報」ページで「認証情報を作成」を選択し、「OAuth クライアント ID」を作成 - アプリケーションタイプを「ウェブアプリケーション」とし、承認済みのリダイレクトURIに、あなたのアプリケーションのリダイレクトURI(例: https://localhost:5001/signin-google)を追加
- クライアントIDとクライアントシークレットを生成
NuGetパッケージのインストール
dotnet add package Microsoft.AspNetCore.Authentication.Google
シークレットマネージャーの使用
プロジェクト ディレクトリで次のコマンドを実行
dotnet user-secrets init
クライアントIDとシークレットをセット
dotnet user-secrets set "Authentication:Google:ClientId" "CLIENT_ID"
dotnet user-secrets set "Authentication:Google:ClientSecret" "CLIENT_SECRET"
※プロジェクトを右クリック→ ユーザーシークレットの管理 からsecrets.json
に正しく設定されているかを確認
Program.csの設定
var builder = WebApplication.CreateBuilder(args);
// 他のサービス設定...
builder.Services.AddIdentity<ApplicationUser, IdentityRole>(options =>
options.SignIn.RequireConfirmedAccount = false) // 外部ログインではアカウント確認を求めない
.AddEntityFrameworkStores<ApplicationDbContext>()
.AddDefaultTokenProviders();
// 認証サービスを追加
builder.Services.AddAuthentication(options =>
{
// 既存の認証設定...
})
.AddGoogle(googleOptions =>
{
// Google API Consoleで取得したクライアントIDとシークレットを使用
googleOptions.ClientId = builder.Configuration["Authentication:Google:ClientId"];
googleOptions.ClientSecret = builder.Configuration["Authentication:Google:ClientSecret"];
});
var app = builder.Build();
// 他のミドルウェア設定...
app.UseAuthentication();
app.UseAuthorization();
// 他のミドルウェア設定...
app.Run();
コントローラーの設定
public IActionResult GoogleLogin()
{
var redirectUrl = Url.Action("GoogleResponse", "Account");
var properties = _signInManager.ConfigureExternalAuthenticationProperties("Google", redirectUrl);
return new ChallengeResult("Google", properties);
}
public async Task<IActionResult> GoogleResponse()
{
var info = await _signInManager.GetExternalLoginInfoAsync();
if (info == null)
{
return RedirectToAction(nameof(Login));
}
var result = await _signInManager.ExternalLoginSignInAsync(info.LoginProvider, info.ProviderKey, isPersistent: false);
if (result.Succeeded)
{
return RedirectToAction("Index", "Home");
}
else
{
return RedirectToAction(nameof(Register));
}
}