2
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 1 year has passed since last update.

.NET8 OAuth Googleログイン

Last updated at Posted at 2024-01-28

Google API Consoleでの設定

  1. Google API Consoleにアクセスして新しいプロジェクトを作成
    2.「認証情報」ページで「認証情報を作成」を選択し、「OAuth クライアント ID」を作成
  2. アプリケーションタイプを「ウェブアプリケーション」とし、承認済みのリダイレクトURIに、あなたのアプリケーションのリダイレクトURI(例: https://localhost:5001/signin-google)を追加
  3. クライアント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));
    }
}

Reference

2
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
2
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?