Programming C#

Google Sign In

Register ClientId and ClientSecret

Để tạo ClientId và ClientSecret trong Google Console ta thực hiện theo các bước sau:

B1: Truy cập vào link https://console.cloud.google.com/apis/credentials

B2: Chọn CREATE CREDENTIALS

B3: chọn OAuth client ID

B4: chọn Web Application

B5: rồi nhập Authorized JavaScript origins với url là đường dẫn của hosting ví dụ: http://ceb.net.vn

B6: Authorized redirect URIs là url của hosting ví dụ http://ceb.net.vn/signin- google

B7: Sau cùng ta chọn Save để lấy ClientId và ClientSecret

Configuration ClientId and ClientSecret

"Authentication":{
    "Google": {
        "ClientId": "Client Id Token",
        "ClientSecret": "Client Secret Token"
    }
}

Install package Authentication Google

dotnet add package Microsoft.AspNetCore.Authentication.Google

Configuration Authentication Google SignIn

builder.Services
    .AddAuthentication(CookieAuthenticationDefaults.AuthenticationScheme)
    .AddCookie()
    .AddGoogle(options =>
    {
        options.ClientId = builder.Configuration["Authentication:Google:ClientId"] ?? throw new Exception("Not found ClientId");
        options.ClientSecret = builder.Configuration["Authentication:Google:ClientSecret"] ?? throw new Exception("Not found ClientSecret");
    });

Authentication Controller

public class AuthController : Controller{
    public IActionResult GoogleSignin(){
        var properties = new AuthenticationProperties{ RedirectUri = "http://ceb.net.vn/auth/googleresponse" };
        return Challenge(properties, GoogleDefaults.AuthenticationScheme);
    }
    public async Task GoogleResponse(string? returnUrl){
        var result = await HttpContext.AuthenticateAsync(CookieAuthenticationDefaults.AuthenticationScheme);
        if(result.Principal != null){
            return Json(result.Principal.Claims);
        }
        return Json(null);
    }
}

Google Sigin with Identity

public IActionResult GoogleSignIn(){
    string? url = Url.Action("googleresponse", "auth", null, protocol: Request.Scheme);
    if(url != null){
        var properties = manager.ConfigureExternalAuthenticationProperties(GoogleDefaults.AuthenticationScheme, url);
        return Challenge(properties, GoogleDefaults.AuthenticationScheme);
    }
    return View();
}
public async Task<IActionResult> GoogleResponse(){
    var info = await manager.GetExternalLoginInfoAsync();
    if (info == null){
        throw new InvalidOperationException("External Login Info missing");
    }
    string? id = info.Principal.FindFirstValue(ClaimTypes.NameIdentifier);
    if(id != null){
        var user = await repository.Save(new IdentityUser{ 
            Id = id, 
            UserName = info.Principal.FindFirstValue(ClaimTypes.Email),
            Email = info.Principal.FindFirstValue(ClaimTypes.Email)
        });
        await manager.SignInAsync(user, new AuthenticationProperties());
        return Redirect("/auth");
    }
    return Redirect("/auth/error");
}