---
# System prepended metadata

title: Net Core 使用google登入(openId 套件)
tags: [.net core, openId, 第三方登入, google]

---

# Net Core 使用google登入(openId 套件)
###### tags: `google` `.net core` `openId` `第三方登入`

#### 在Google中設定服務

設定連結 : https://console.cloud.google.com/apis/dashboard?hl=zh-tw

需要套件
Microsoft.AspNetCore.Authentication.OpenIdConnect
Microsoft.AspNetCore.Identity.EntityFrameworkCore(for EntityFrameworkStores)

##### Startup

```
        services.AddIdentityCore<IdentityUser>()
            .AddRoles<IdentityRole>()
            .AddEntityFrameworkStores<ApplicationDbContext>()
            .AddSignInManager()
            .AddDefaultTokenProviders();


        services.AddAuthentication(options =>
        {
           options.DefaultScheme = "Google";
        }).AddOpenIdConnect(
            authenticationScheme: "Google",
            displayName: "Google",
            options =>
            {
                options.Authority = "https://accounts.google.com/";
                options.ClientId = "";    //services id
                options.CallbackPath = "/signin-google";
                // Add email scope
                options.Scope.Add("email");
            });
```

#### Controller

        private readonly SignInManager<IdentityUser> _signInManager;
        public AccountController( SignInManager<IdentityUser> signInManager)
        {   
            //需要先DI signInManager
            _signInManager = signInManager;
        }



           [HttpGet]    
        [AllowAnonymous]
        [Route("~/signin-google")]
        public async Task<IActionResult> ExternalLoginCallback()
        {
            var result = await HttpContext.AuthenticateAsync("Google");
            if (!result.Succeeded)
            {
                return RedirectToAction("Login", "Account"); ;
            }
            return RedirectToAction("Index", "Home");
        }
        [HttpGet]
 
        public IActionResult ExternalLogin()
        {
            var redirectUrl = Url.Action(nameof(ExternalLoginCallback)); //以此方式設定路徑比較不會有奇怪的問題
            var properties = _signInManager.ConfigureExternalAuthenticationProperties("Google", redirectUrl);
            return Challenge(properties, "Google"); //轉址到redirecUrl
        }
    
#### View


        <div class="d-flex justify-content-center mgB20">
            <button type="button" class="btn btn-loginType btn-transition" onclick="location.href='@Url.Action("ExternalLogin","Parent",new { @ViewBag.SchoolId,type=1 })'">
                <img src="~/img/image_google.png">
                <span>透過 Google 登入</span>
            </button>
        </div>