ASP.NET CORE3.0 API Swagger+IdentityServer4授權驗證


一、配置IdentityServer4服務端

這里介紹兩種方法

①直接創建identityserver4的模板,在模板的基礎上修改

②創建新項目,自己搭建

第一種

參考 我的identityServer4學習,創建一個identityServer4模板后

修改config文件

public static IEnumerable<IdentityResource> GetIdentityResources()
        {
            return new IdentityResource[]
            {
                new IdentityResources.OpenId(),
                new IdentityResources.Profile(),
            };
        }
        /// <summary>
        /// API信息
        /// </summary>
        /// <returns></returns>
        public static IEnumerable<ApiResource> GetApis()
        {
            return new[]
            {
                new ApiResource("ProjectApiScope", "Demo API with Swagger")
            };
        }
        /// <summary>
        /// 客服端信息
        /// </summary>
        /// <returns></returns>
        public static IEnumerable<Client> GetClients()
        {
            return new[]
            {
                new Client
                {
                    ClientId = "projectClient",//客服端名稱
                    ClientName = "Swagger UI for demo_api",//描述
                    AllowedGrantTypes = GrantTypes.Implicit,//指定允許的授權類型(AuthorizationCode,Implicit,Hybrid,ResourceOwner,ClientCredentials的合法組合)。
                    AllowAccessTokensViaBrowser = true,//是否通過瀏覽器為此客戶端傳輸訪問令牌
                    RedirectUris =
                    {
                        "http://localhost:5001/swagger/oauth2-redirect.html"
                    },
                    AllowedScopes = { "ProjectApiScope" }//指定客戶端請求的api作用域。 如果為空,則客戶端無法訪問
                },
            };
        }

打開Startup.cs文件配置,修改如下:

public void ConfigureServices(IServiceCollection services)
        {
            services.AddControllersWithViews();
            //配置身份服務器與內存中的存儲,密鑰,客戶端和資源
            services.AddIdentityServer()
                   .AddDeveloperSigningCredential()
                   .AddInMemoryApiResources(Config.GetApis())//添加api資源
                   .AddInMemoryClients(Config.GetClients())//添加客戶端
                   .AddInMemoryIdentityResources(Config.GetIdentityResources())//添加對OpenID Connect的支持
                   .AddTestUsers(TestUsers.Users); //添加測試用戶
        }

        // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
        public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
        {
            if (env.IsDevelopment())
            {
                app.UseDeveloperExceptionPage();
            }
            app.UseRouting();
            //IdentityServe
            app.UseIdentityServer();
            //添加靜態資源訪問
            app.UseStaticFiles();

            app.UseAuthorization();

            app.UseEndpoints(endpoints =>
            {
                endpoints.MapDefaultControllerRoute();
            });
        }

第二種,直接干代碼

首先創建一個新的ASP.NET Core項目。

 

這里選擇空白項,新建空白項目

 

 

 

 

 等待創建完成后,右鍵單擊項目中的依賴項選擇管理NuGet程序包,搜索IdentityServer4並安裝

 等待安裝完成后,下載官方提供的UI文件,並拖放到項目中。(注意只需要復制文件夾就行)

修改啟動端口為5000,啟動訪問:http://localhost:5000/,效果如下

 

 

 

二、配置ProjectAPI

新建ASP.NET CORE API項目,使用NuGet添加包:IdentityServer4.AccessTokenValidation、Swashbuckle.AspNetCore

在API中添加 AuthorizeCheckOperationFilter用於管理IdentityServer4認證處理,代碼如下:

public class AuthorizeCheckOperationFilter: IOperationFilter
    {
        public void Apply(OpenApiOperation operation, OperationFilterContext context)
        {
            //獲取是否添加登錄特性
            //策略名稱映射到范圍
            var requiredScopes = context.MethodInfo
                .GetCustomAttributes(true)
                .OfType<AuthorizeAttribute>()
                .Select(attr => attr.Policy)
                .Distinct();

            if (requiredScopes.Any())
            {
                operation.Responses.Add("401", new OpenApiResponse { Description = "未經授權" });
                operation.Responses.Add("403", new OpenApiResponse { Description = "禁止訪問" });

                var oAuthScheme = new OpenApiSecurityScheme
                {
                    Reference = new OpenApiReference { Type = ReferenceType.SecurityScheme, Id = "oauth2" }
                };

                operation.Security = new List<OpenApiSecurityRequirement>
                {
                    new OpenApiSecurityRequirement
                    {
                        [ oAuthScheme ] = requiredScopes.ToList()
                    }
                };
            }
        }
    }

修改API的Startup文件,修改如下:

public void ConfigureServices(IServiceCollection services)
        {
            services.AddControllersWithViews();
            //用戶校驗
            services.AddAuthentication(IdentityServerAuthenticationDefaults.AuthenticationScheme)
              .AddIdentityServerAuthentication(options =>
              {
                  options.Authority = "http://localhost:5000"; // IdentityServer服務器地址
                  options.ApiName = "demo_api"; // 用於針對進行身份驗證的API資源的名稱
                  options.RequireHttpsMetadata = false; // 指定是否為HTTPS
              });
            //添加Swagger.
            services.AddSwaggerGen(options =>
            {
                options.SwaggerDoc("v1", new OpenApiInfo { Title = "Project API", Version = "v1" });
                //向生成的Swagger添加一個或多個“securityDefinitions”,用於API的登錄校驗
                options.AddSecurityDefinition("oauth2", new OpenApiSecurityScheme
                {
                    Type = SecuritySchemeType.OAuth2,
                    Flows = new OpenApiOAuthFlows
                    {
                        Implicit = new OpenApiOAuthFlow
                        {
                            //授權地址
                            AuthorizationUrl = new Uri("http://localhost:5000/connect/authorize"),
                            Scopes = new Dictionary<string, string>
                            {
                                { "ProjectApiScope", "請選擇授權API" },
                            }
                        }
                    }

                });

                options.OperationFilter<AuthorizeCheckOperationFilter>(); // 添加IdentityServer4認證過濾
            });
        }

        // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
        public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
        {
            if (env.IsDevelopment())
            {
                app.UseDeveloperExceptionPage();
            }
            app.UseStaticFiles();

            app.UseRouting();
            app.UseAuthorization();
            // Swagger JSON Doc
            app.UseSwagger();

            // Swagger UI
            app.UseSwaggerUI(options =>
            {
                options.SwaggerEndpoint("/swagger/v1/swagger.json", "My API V1");
                options.OAuthClientId("projectClient");//客服端名稱
                options.OAuthAppName("Demo API - Swagger-演示"); // 描述
            });
            app.UseEndpoints(endpoints =>
            {
                endpoints.MapControllers();
            });
        }

這里要注意api中的ClientId和identityserver中的ClientId要是一樣的,Scopes也要一樣

控制器中的api注意加上驗證

修改Properties文件夾下的launchSettings啟動端口為5001,並且修改launchUrl為swagger即可一運行就訪問swagger頁面

訪問呈現效果如下,從中效果圖中可以看出添加登錄按鈕,API控制器中如果添加Authorize特性,對應接口會有一把鎖的標志:

 

 

 如果未授權訪問接口返回401,未授權提示:

 

 點擊Authorize按鈕會跳轉到IdentityServer4登錄頁面,登錄授權成功后會自動獲取登錄后服務器返回Token,再次訪問接口即可正常訪問,授權前后效果如下:

授權會自動跳轉到identityserver4授權頁面

 

 參考文獻:https://www.cnblogs.com/miskis/p/10083985.html

源碼地址:https://github.com/Aooys/ASP.NET-CORE3.0-API-Swagger-IdentityServer4


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM