Contents

Google登入-.NET Core Identity簡化版

Google登入-.NET Core Identity簡化版

就在我以為抽離Identity只使用第三方驗證的部分很簡單的時候,瞬間被打臉…一開始不管怎麼做都不會過,但過幾天後,回來截圖,重新改回正常流程,又能過…我個人猜測是憑證問題或是google回傳路徑設定,這也是我在Google SDK API那篇中,強烈建議使用預設的回傳路徑/signin-google的原因。

環境

Note
先到Google Cloud Platform 建立應用程式服務,步驟請參考

實作

  1. 先安裝Microsoft.AspNetCore.Authentication.Google

    /static/Google_NETCore_Identity簡化版_c9c4426739a049b391e43d99ceb4434d/2020-09-28_11-48-59.png
  2. 在Startup.cs 中設置服務

     1
     2
     3
     4
     5
     6
     7
     8
     9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    
    public void ConfigureServices(IServiceCollection services)
    {
        services.AddAuthentication(options =>
        {
            options.DefaultAuthenticateScheme = CookieAuthenticationDefaults.AuthenticationScheme;
            options.DefaultChallengeScheme = CookieAuthenticationDefaults.AuthenticationScheme;
            options.DefaultSignInScheme = CookieAuthenticationDefaults.AuthenticationScheme;
        })
        .AddGoogle(options =>
        {
            options.ClientId = "{應用程式編號}";
            options.ClientSecret = "{應用程式密鑰}";
        }).AddCookie(options =>
        {
            options.LoginPath = "/Login/Index";
        });
    
        services.AddControllersWithViews();
    }
    
  3. Controller 和 View 設置連結與回傳網址

    1
    2
    3
    4
    5
    6
    
    <a  asp-controller="Login" 
        asp-action="SignInGoogle" 
        asp-route-provider="Google" 
        class="btn btn-primary" 
        title="Log in your account">
        Google
    
     1
     2
     3
     4
     5
     6
     7
     8
     9
    10
    11
    12
    
    public IActionResult SignInGoogle(string provider, string returnUrl = null)
    {
        var redirectUrl = Url.Action("Callback", controller: "Login", values: new { returnUrl });
        return new ChallengeResult(provider, new AuthenticationProperties { RedirectUri = redirectUrl ?? "/" });
    }
    
    public IActionResult Callback(string returnUrl = null, string remoteError = null)
    {
        var claims = HttpContext.User;
        // 略...後續流程可直接參考官方範例,或自訂
        return Ok();
    }
    
  4. 登入後,用戶資料都會出現在HttpContext.User中

    /static/Google_NETCore_Identity簡化版_c9c4426739a049b391e43d99ceb4434d/_2020-09-11_152741.png

備註

一開始沒有設置options.DefaultSignInScheme = CookieAuthenticationDefaults.AuthenticationScheme;會提示你沒有預設DefaultSignInScheme

/static/Google_NETCore_Identity簡化版_c9c4426739a049b391e43d99ceb4434d/2020-09-28_14-02-57.png

如果設置後還是出現錯誤,有可能是cookie暫存問題,清除暫存就好了

參考

ASP.NET Core Google 外部登入設定

https://docs.microsoft.com/zh-tw/aspnet/core/security/authentication/social/google-logins?view=aspnetcore-3.1

結論

撇除掉Google 回傳路徑的問題,這設置跟Facebook是一模一樣,同樣推薦單純驗證登入使用。

另外我發現Authentication.Google設置取得個人資訊服務並非來自於Google People API,如果是登入驗證並且只需要最基本的Id、Name、Email,似乎不啟用任何API服務也沒有關係,我只在憑證頁新增一個認證憑證即可使用。