通過 Dapr 實現一個簡單的基於 dotnet 的微服務電商系統——一步一步教你如何擼 Dapr 之 OAuth2 授權 - 百度版
本來想集成微信 / QQ / 微博的,結果發現不是需要企業資質就是要個人認證,就百度開放平臺不需要,就用百度來演示吧。
首先我們需要註冊並登錄百度開發者平臺,同時創建一個應用,獲取它的 API Key 和 Secret Key
進入應用詳情後在點擊左下角的安全設置,配置我們的鑑權域名【http://oauth.dapreshop.com:30882】到授權回調頁並禁用 Implicit Grant 授權方式,其他不用填如下圖:
接着修改我們的 component 文件,錄入剛纔我們獲取的 API Key 和 Secret Key 到 clientid 和 clientsecret 一欄,並修改 scopes、authURL、redirectURL 如下所示,修改完畢後記得重新 apply 一下
apiVersion: dapr.io/v1alpha1
kind: Component
metadata:
name: baiduauth
namespace: dapreshop
spec:
type: middleware.http.oauth2
version: v1
metadata:
- name: clientId
value: ""
- name: clientSecret
value: ""
- name: scopes
value: "basic"
- name: authURL
value: "http://openapi.baidu.com/oauth/2.0/authorize"
- name: tokenURL
value: "https://openapi.baidu.com/oauth/2.0/token"
- name: redirectURL
- name: authHeaderName
if (HttpContextExt.Current.Headers.Any(x => x.Key.ToLower().Equals("myauth")))
{
var requestUri = new Uri($"https://openapi.baidu.com/rest/2.0/passport/users/getLoggedInUser?access_token={HttpContextExt.Current.Headers.FirstOrDefault(x => x.Key.ToLower().Equals("myauth")).Value.Replace("Bearer ","")}");
var result = await httpClientFactory.CreateClient().GetAsync(requestUri);
if (result.IsSuccessStatusCode)
{
var content = await result.Content.ReadAsStringAsync();
baidumodel obj = JsonSerializer.Deserialize(content);
HttpContextExt.Current.Response.Cookies.Append("githubuser", JsonSerializer.Serialize(new Model() { login = obj.openid.Substring(0,8), name = obj.uname, avatar_url = $"http://tb.himg.baidu.com/sys/portraitn/item/{obj.portrait}" }),
new Microsoft.AspNetCore.Http.CookieOptions() { Domain = "dapreshop.com"});
HttpContextExt.Current.Response.Redirect("http://admin.dapreshop.com:30882");
}
}
return model;
重新啓動整個 demo,這時候再次點擊圖標,我們會跳轉至百度的授權頁
回跳後重新初始化就能看到我們取到了百度授權的用戶信息
本文由 Readfog 進行 AMP 轉碼,版權歸原作者所有。
來源:https://mp.weixin.qq.com/s/IkAMUmI8VJajSlSw-EEoUw