前面的OAuth2認證,里面的授權服務器都是用的identityserver4搭建的
ids4沒有之前一般都是Owin搭建授權服務器,博客園有很多
ids4出來后,一般都是用ids4來做認證和授權了,
所以這里簡單說下AuthorizationCode認證,但授權服務器依然是ids4
下篇接受ids4的認證和授權
ConfigureServices配置:
#region OAuth認證 services.AddAuthentication(options => { //options.DefaultAuthenticateScheme=OAuthDefaults.DisplayName //options.DefaultAuthenticateScheme = CookieAuthenticationDefaults.AuthenticationScheme; options.DefaultAuthenticateScheme = "Cookies"; options.DefaultSignInScheme = "Cookies"; //options.DefaultSignOutScheme = "Cookies"; options.DefaultChallengeScheme = "OAuth"; }) .AddCookie() .AddOAuth("OAuth", options => { options.ClientId = "OAuth.Client"; options.ClientSecret = "secret"; options.AuthorizationEndpoint = "http://localhost:5003/connect/authorize"; options.TokenEndpoint = "http://localhost:5003/connect/token"; options.CallbackPath = new PathString("/OAuth"); options.SaveTokens = true; options.Scope.Add("OAuth1"); options.Scope.Add("OAuth2"); options.Scope.Add("OAuth3"); //options.Scope.Add("offline_access"); options.Events = new OAuthEvents() { //OnRedirectToAuthorizationEndpoint = t => //{ // t.Response.Redirect("http://localhost:5001/Account/userinfo"); // return Task.FromResult(0); //}, //遠程異常觸發 OnRemoteFailure = OAuthFailureHandler => { //var msg = OAuthFailureHandler.Failure.Message; var authProperties = options.StateDataFormat.Unprotect(OAuthFailureHandler.Request.Query["state"]); var redirectUrl = authProperties.RedirectUri; if (redirectUrl.Contains("/")) { redirectUrl = string.Format($"{redirectUrl.Substring(0, redirectUrl.LastIndexOf("/") + 1)}#");
// redirectUrl.Substring(0, redirectUrl.IndexOf("/") + 1); } //"http://localhost:5001/#" OAuthFailureHandler.Response.Redirect(redirectUrl); OAuthFailureHandler.HandleResponse(); return Task.FromResult(0); } }; }); #endregion
中間件:
app.UseAuthentication();
授權服務器的ApiResource配置
var oauth = new ApiResource { Name = "OAuth.ApiName", //這是資源名稱 Description = "2", DisplayName = "33", Scopes = { new Scope{ Name="OAuth1", //這里是指定客戶端能使用的范圍名稱 , 是唯一的 Description="描述", DisplayName="獲得你的個人信息,好友關系", Emphasize=true, Required=true, //ShowInDiscoveryDocument=true, }, new Scope{ Name="OAuth2", Description="描述", DisplayName="分享內容到你的博客", Emphasize=true, Required=true, }, new Scope{ Name="OAuth3", Description="描述", DisplayName="獲得你的評論", } } };
當選擇使用微博登陸。就會跳轉到授權服務器,使用微博賬號登陸
當然,如果你取消,則會跳轉回來,是根據OnRemoteFailure事件來的
登陸成功后,則提示是否同意授權
如果取消,則也會跳回之前的頁面
同意授權后,則跳轉回來,拿到了access_token ,可以請求資源服務器獲取資源了
從5003跳轉到了5001
就這么一個簡單的過程,下篇詳細接受下ids4,感覺那才是重點