在上一篇文章中案例使用了github的oauht2.0授權,實際上使用哪個平台並不局限,只要平台實現了oauth2.0標准都可以接入。本節我們聊聊如何集成百度oauth2.0。
本來想集成微信/QQ/微博的,結果發現不是需要企業資質就是要個人認證,就百度開放平台不需要,就用百度來演示吧。
首先我們需要注冊並登錄百度開發者平台,同時創建一個應用,獲取它的API Key和Secret Key
進入應用詳情后在點擊左下角的安全設置,配置我們的鑒權域名【http://oauth.dapreshop.com:30882】到授權回調頁並禁用
接着修改我們的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 value: "http://oauth.dapreshop.com:30882" - name: authHeaderName value: "myauth"
4、修改一下獲取用戶信息的代碼(這里是演示所以百度返回的openid我取前n位做登錄名):
var model = new Model() { login = "" }; 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<baidumodel>(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,這時候再次點擊圖標,我們會跳轉至百度的授權頁
回跳后重新初始化就能看到我們取到了百度授權的用戶信息