ASP.NET CORE3.0 API Swagger+IdentityServer4授权验证

摘要:
如果为空,则客户端无法访问},};}打开Startup.cs文件配置,修改如下:publicvoid ConfigureServices{services.AddControllersWithViews();//配置身份服务器和内存存储、密钥、客户端和资源服务。AddIdentityServer().AddDeveloperSigningCredential().AAddInMemoryPiResources/添加api资源。AddInMemooryClient/添加客户端。AddInMemory identity resources/添加对OpenIDConnect.AddTestUsers的支持;//添加测试用户}//此方法按时间缩放。使用此方法配置HTTPrequestpipeline.publicvoidConfigure{if{app.UseDeveloperExceptionPage();}app.Use Routing();//IdentityServeap.UseIdentityServer();//添加静态资源以访问应用程序。UseStaticFiles();app.UseAuthorization();app.UseEndpoints;}第二个是创建一个新的ASP。NET核心项目。在此处选择空白项。新的空白项创建完成后,右键单击项目中的依赖项,然后选择Manage NuGet Package。搜索IdentityServer4并安装它。安装完成后,下载官方UI文件并将其拖到项目中。

一、配置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项目。

ASP.NET CORE3.0 API Swagger+IdentityServer4授权验证第1张

这里选择空白项,新建空白项目

 ASP.NET CORE3.0 API Swagger+IdentityServer4授权验证第2张

 等待创建完成后,右键单击项目中的依赖项选择管理NuGet程序包,搜索IdentityServer4并安装

 等待安装完成后,下载官方提供的UI文件,并拖放到项目中。(注意只需要复制文件夹就行)

修改启动端口为5000,启动访问:http://localhost:5000/,效果如下

ASP.NET CORE3.0 API Swagger+IdentityServer4授权验证第3张

二、配置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注意加上验证

ASP.NET CORE3.0 API Swagger+IdentityServer4授权验证第4张

修改Properties文件夹下的launchSettings启动端口为5001,并且修改launchUrl为swagger即可一运行就访问swagger页面

访问呈现效果如下,从中效果图中可以看出添加登录按钮,API控制器中如果添加Authorize特性,对应接口会有一把锁的标志:

ASP.NET CORE3.0 API Swagger+IdentityServer4授权验证第5张

 如果未授权访问接口返回401,未授权提示:

ASP.NET CORE3.0 API Swagger+IdentityServer4授权验证第6张

 点击Authorize按钮会跳转到IdentityServer4登录页面,登录授权成功后会自动获取登录后服务器返回Token,再次访问接口即可正常访问,授权前后效果如下:

ASP.NET CORE3.0 API Swagger+IdentityServer4授权验证第7张

授权会自动跳转到identityserver4授权页面

ASP.NET CORE3.0 API Swagger+IdentityServer4授权验证第8张

 参考文献:https://www.cnblogs.com/miskis/p/10083985.html

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

免责声明:文章转载自《ASP.NET CORE3.0 API Swagger+IdentityServer4授权验证》仅用于学习参考。如对内容有疑问,请及时联系本站处理。

上篇Oracle ORA12514 监听程序当前无法识别连接描述符中请求的服务检测当前运行环境——移动端与PC端。下篇

宿迁高防,2C2G15M,22元/月;香港BGP,2C5G5M,25元/月 雨云优惠码:MjYwNzM=

相关文章

Tweepy1_抓取Twitter数据

python机器学习-乳腺癌细胞挖掘(博主亲自录制视频)https://study.163.com/course/introduction.htm?courseId=1005269003&utm_campaign=commission&utm_source=cp-400000000398149&utm_medium=share...

Spring Cloud Security集成CAS (单点登录)对微服务认证

一、前言   由于leader要求在搭好的spring cloud 框架中加入对微服务的认证包括单点登录认证,来确保系统的安全,所以研究了Spring Cloud Security这个组件。在前面搭好的demo中,如何确保微服务的安全,为整个系统添加安全控制,就需要用到Spring Cloud Security。用户通过服务网关zuul来访问任何一个微服务...

前端测试Mock API工具——EoLinker API管理平台

之前开发一直在使用Production和QA环境,但是这两种环境下rest api 返回来的数据并不能保证各种极端的数据存在。 比如正常情况下服务器返回这样的json { "status": { "code": 0, "message": "It works!" }, "server": {...

Google API快速生成QR二维码

Google API快速生成QR二维码现在来说生成二维码最简单的方法是使用Google Chart API来实现,再次膜拜Google大神~ Google Chart API是一套可以让你在线生成报表图的系统,通过URL你可以得到各种图表。举个例子:你在浏览器中输入 https://chart.googleapis.com/chart?cht=qr&...

小白都看得懂的Javadoc使用教程

Javadoc是什么 官方回答: Javadoc is a tool for generating API documentation in HTML format from doc comments in source code. 译:Javadoc是一款能根据源代码中的文档注释来产生HTML格式的API文档的工具。 说人话:只要你在java源码中按一...

devServer之proxy跨域

一、配置devServer:{ contentBase:'./', proxy:{ // 当你请求是以/api开头的时候,代理会访问到http://localhost:3000 // 例如: // /api/users 则访问到 http://local...