ASP.NET Core IdentityServer4 新手上路

OAuth2.0資料

今天看到一篇博主寫了該系列文章,貼圖和過程都比較詳細,俗話說實踐是檢驗真理的惟一標準(若是是按照參考文章複製粘貼,應該不會出現踩坑,可是我喜歡本身手動敲一遍),發現幾個坑,於是總結下經驗,讓其餘小白同窗少走彎路html

參考第一篇:http://www.javashuo.com/article/p-cdzjgnix-hm.htmlgit

參考第二篇:http://www.javashuo.com/article/p-mtkmsggb-gs.htmlweb

博客園曉晨的關於identityServer4的中文文檔地址: http://www.cnblogs.com/stulzq/p/8119928.htmldocker

Docker中文文檔 https://yeasy.gitbooks.io/docker_practice/content/api

OAuth2.0(Open Authorization)是一個開放受權協議;第三方應用不須要接觸到用戶的帳戶信息(如用戶名密碼),經過用戶的受權訪問用戶資源服務器

OAuth的步驟通常以下:restful

一、客戶端要求用戶給予受權
二、用戶贊成給予受權
三、根據上一步得到的受權,向認證服務器請求令牌(token)
四、認證服務器對受權進行認證,確認無誤後發放令牌
五、客戶端使用令牌向資源服務器請求資源
六、資源服務器使用令牌向認證服務器確認令牌的正確性,確認無誤後提供資源app

服務端代碼實現

第一步:新建一個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"} } }; } }

第一處坑講解:上面代碼紅色標記,請注意大小寫,若是一個大寫,一個小寫。當你受權的時候會提示錯誤ide

1

第四步:修改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---會發現自定義端口未起做用。你須要設置一下才行post

3

http://localhost:5000/.well-known/openid-configuration訪問 ;能夠看到是一個restful的api

4

 而後用postman神器 服務端成功,我們開始用客戶端

5

客戶端代碼實現

第一步:新建一個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;//是不是https
                Options.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>)在裏面,是由於服務端沒啓動成功

6

須要注意的地方:受權碼  前面必須加Bearer 而後空格

在客戶端配置第三步中 services.AddAuthentication("Bearer")//添加受權模式  有的同窗可能會想  那我將這個改掉  而後保持一致應該能夠

恭喜這位同窗想法很是棒,可是你能夠試一試。這個格式是固定規範

相關文章
相關標籤/搜索