Google OAuth 2.0
今天來複習一下OAuth 2.0部分,以下以google來當作登入範例:
角色定義:
- Resource Owner: 使用者(擁有資源的人)
- Client: 應用程式(想要存取資源的應用)
- Authorization Server: 授權伺服器(如 Google)
- Resource Server: 資源伺服器(存放使用者資源的伺服器)
重要術語:
- Client ID: 應用程式的唯一識別碼
- Client Secret: 應用程式的密鑰
- Access Token: 存取令牌,用於存取受保護的資源
- Refresh Token: 更新令牌,用於取得新的存取令牌
- Scope: 存取範圍,定義可以存取的資源類型
授權流程:
1. 初始請求
2. 授權過程3. 資源存取程式碼部分:
Program.cs:
builder.Services.AddAuthentication(options =>
{
options.DefaultScheme = CookieAuthenticationDefaults.AuthenticationScheme;
options.DefaultChallengeScheme = GoogleDefaults.AuthenticationScheme;
})
.AddCookie(options =>
{
options.LoginPath = "/Account/Login";
options.LogoutPath = "/Account/Logout";
options.ExpireTimeSpan = TimeSpan.FromDays(7);
})
.AddGoogle(options =>
{
IConfiguration googleAuth = builder.Configuration.GetSection("Authentication:Google");
options.ClientId = googleAuth["ClientId"];
options.ClientSecret = googleAuth["ClientSecret"];
options.CallbackPath = "/signin-google";
options.Scope.Add("email");
options.Scope.Add("profile");
options.SaveTokens = true;
});
AccountController.cs:
[HttpGet]
public IActionResult Login(string returnUrl = "/")
{
// 觸發 OAuth 挑戰
return Challenge(new AuthenticationProperties
{
RedirectUri = returnUrl
}, GoogleDefaults.AuthenticationScheme);
}
HomeController.cs:
[Authorize]
public IActionResult Profile()
{
// 從 Claims 中讀取用戶資訊
var profile = new UserProfile
{
Id = User.FindFirst("sub")?.Value,
Name = User.Identity.Name,
Email = User.FindFirst("email")?.Value
};
return View(profile);
}
appsettings.json:
{
"Logging": {
"LogLevel": {
"Default": "Information",
"Microsoft.AspNetCore": "Warning"
}
},
"AllowedHosts": "*",
"Authentication": {
"Google": {
"ClientId": "your-google-client-id",
"ClientSecret": "your-google-client-secret"
}
}
}
留言
張貼留言