ASP.NET Core IdentityServer4 新手上路
OAuth2.0資料
今天看到一篇博主寫了該系列文章,貼圖和過程都比較詳細,俗話說實踐是檢驗真理的唯一標準(如果是按照參考文章復制粘貼,應該不會出現踩坑,但是我喜歡自己手動敲一遍),發現幾個坑,因而總結下經驗,讓其他小白同學少走彎路
參考第一篇:https://www.cnblogs.com/cby-love/p/9281955.html
參考第二篇:https://www.cnblogs.com/wyt007/p/8284482.html
博客園曉晨的關于identityServer4的中文文檔地址:?http://www.cnblogs.com/stulzq/p/8119928.html
Docker中文文檔?https://yeasy.gitbooks.io/docker_practice/content/
OAuth2.0(Open Authorization)是一個開放授權協議;第三方應用不需要接觸到用戶的賬戶信息(如用戶名密碼),通過用戶的授權訪問用戶資源
OAuth的步驟一般如下:
1、客戶端要求用戶給予授權
2、用戶同意給予授權
3、根據上一步獲得的授權,向認證服務器請求令牌(token)
4、認證服務器對授權進行認證,確認無誤后發放令牌
5、客戶端使用令牌向資源服務器請求資源
6、資源服務器使用令牌向認證服務器確認令牌的正確性,確認無誤后提供資源
服務端代碼實現
第一步:新建一個webapi空項目
第二步:添加Nuget包:IdentityServer4
第三步:新建一個幫助類(類名自定義即可),用來創建IdentityServer4.Model生成授權token
public class Config{/// <summary>/// 所有可以訪問的Resource/// </summary>/// <returns></returns>public static IEnumerable<ApiResource> GetResources(){return new List<ApiResource>{//第一個參數需要與下面標記紅色字體保持一致,可以隨意命名,但是請注意大小寫,第二個參數 我干了,你隨意。new ApiResource("api","My Api")};}/// <summary>/// 客戶端/// </summary>/// <returns></returns>public static IEnumerable<Client> GetClients(){return new List<Client>{new Client(){ClientId="client",////模式:最簡單的模式AllowedGrantTypes=GrantTypes.ClientCredentials,ClientSecrets={new Secret("secret".Sha256())},AllowedScopes={ "api"}}};}}
第一處坑講解:上面代碼紅色標記,請注意大小寫,如果一個大寫,一個小寫。當你授權的時候會提示錯誤
第四步:修改Startup.cs? 紅色字體是需要加的方法和中間件
public class Startup{public Startup(IConfiguration configuration){Configuration = configuration;}public IConfiguration Configuration { get; }// This method gets called by the runtime. Use this method to add services to the container.public void ConfigureServices(IServiceCollection services){ services.AddIdentityServer().AddDeveloperSigningCredential()//添加開發人員簽名憑據.AddInMemoryApiResources(Config.GetResources())//添加內存apiresource.AddInMemoryClients(Config.GetClients());//添加內存client services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_1);}// This method gets called by the runtime. Use this method to configure the HTTP request pipeline.public void Configure(IApplicationBuilder app, IHostingEnvironment env){if (env.IsDevelopment()){app.UseDeveloperExceptionPage();}app.UseIdentityServer();//使用IdentityServer app.UseMvc();}}第五步:修改Program.cs? 其實這一步可以省略掉,因為這一部將api不托管在IIS Express上,通過控制臺程序啟動。? 自定義路徑配置如下
public class Program{public static void Main(string[] args){CreateWebHostBuilder(args).Build().Run();}public static IWebHostBuilder CreateWebHostBuilder(string[] args) =>WebHost.CreateDefaultBuilder(args).UseStartup<Startup>()//該處端口可以自定義 只要不與你其他端口沖突就好.UseUrls("http://localhost:5000");}
第二處坑講解:生成token的服務端已經全部設置完成,如果你按照以前習慣,啟動F5---會發現自定義端口未起作用。你需要設置一下才行
http://localhost:5000/.well-known/openid-configuration訪問?;可以看到是一個restful的api
?然后用postman神器 服務端成功,咱們開始用客戶端
客戶端代碼實現
第一步:新建一個webapi空項目??
第二步:添加Nuget包:IdentityServer4.AccessTokenValidation
第三步:修改Startup.cs? 紅色字體是需要加的方法和中間件
public class Startup{public Startup(IConfiguration configuration){Configuration = configuration;}public IConfiguration Configuration { get; }// This method gets called by the runtime. Use this method to add services to the container.public void ConfigureServices(IServiceCollection services){ services.AddAuthentication("Bearer")//添加授權模式.AddIdentityServerAuthentication(Options =>{Options.Authority = "http://localhost:5000";//授權服務器地址Options.RequireHttpsMetadata = false;//是否是httpsOptions.ApiName = "api";});services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_1);}// This method gets called by the runtime. Use this method to configure the HTTP request pipeline.public void Configure(IApplicationBuilder app, IHostingEnvironment env){if (env.IsDevelopment()){app.UseDeveloperExceptionPage();}app.UseAuthentication();//使用授權中間件 app.UseMvc();}}第三處坑講解:
1.授權服務地址端口號,請按照服務端配置的端口號來,如果用IIS Express,請右鍵項目屬性->調試查看。
2.Options.ApiName = "api";? ?請看上述踩坑一配置的名稱,大小寫需要統一
第四步:修改Program.cs? 其實這一步可以省略掉,因為這一部將api不托管在IIS Express上,通過控制臺程序啟動。與上述服務端配置一樣。記得將端口號修改
第四處需要注意的地方
需要將服務端運行起來,然后再運行客戶端(順序不重要,重要的是必須兩個程序都啟動起來。可以將服務端發布到IIS上,客戶端通過vs運行。我比較懶,分別打開兩個,一個設置為啟動服務端,一個設置為啟動客戶端)
第五步:添加授權標簽? ?可以在action和controller上添加
[HttpGet][Authorize] public ActionResult<IEnumerable<string>> Get(){return new string[] { "value1", "value2" };}添加在action上,表示這個方法需要授權才能訪問,否則訪問不了
添加在controller上,表示整個controller下的所有action方法都需要授權后才能訪問? ?
下圖是成功,如果空白表示授權失敗(你可以打個斷點)。?
出現一些錯誤碼html(<title>Internal Server Error</title>)在里面,是因為服務端沒啟動成功
需要注意的地方:授權碼? 前面必須加Bearer 然后空格
在客戶端配置第三步中 services.AddAuthentication("Bearer")//添加授權模式? 有的同學可能會想? 那我將這個改掉? 然后保持一致應該可以
恭喜這位同學想法非常棒,但是你可以試一試。這個格式是固定規范
轉載于:https://www.cnblogs.com/xiaobai123/p/9284874.html
總結
以上是生活随笔為你收集整理的ASP.NET Core IdentityServer4 新手上路的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 研究人员成功训练深度学习模型通过键盘敲击
- 下一篇: WPF 实现水纹效果