ASP.NET CORE API Swagger+IdentityServer4授權驗證


簡介

本來不想寫這篇博文,但在網上找到的文章博客都沒有完整配置信息,所以這里記錄下。

不了解IdentityServer4的可以看看我之前寫的入門博文

Swagger 官方演示地址

源碼地址

配置IdentityServer4服務端

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

 

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

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

等待安裝完成后,下載官方提供的UI文件,並拖放到項目中。下載地址:https://github.com/IdentityServer/IdentityServer4.Quickstart.UI

配置IdentityServer4

在項目中新建文件Config.cs文件,源碼如下:

using IdentityServer4;
using IdentityServer4.Models;
using IdentityServer4.Test;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;

namespace IdentityServer
{
    public static class 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("demo_api", "Demo API with Swagger")
            };
        }
        /// <summary>
        /// 客服端信息
        /// </summary>
        /// <returns></returns>
        public static IEnumerable<Client> GetClients()
        {
            return new[]
            {
                new Client
                {
                    ClientId = "demo_api_swagger",//客服端名稱
                    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 = { "demo_api" }//指定客戶端請求的api作用域。 如果為空,則客戶端無法訪問
                }
            };
        }
    }
}

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

using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using IdentityServer4.Quickstart.UI;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.DependencyInjection;

namespace IdentityServer
{
    public class Startup
    {
        // This method gets called by the runtime. Use this method to add services to the container.
        // For more information on how to configure your application, visit https://go.microsoft.com/fwlink/?LinkID=398940
        public void ConfigureServices(IServiceCollection services)
        {
            services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_1);
            //配置身份服務器與內存中的存儲,密鑰,客戶端和資源
            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, IHostingEnvironment env)
        {
            if (env.IsDevelopment())
            {
                app.UseDeveloperExceptionPage();
            }

            //IdentityServe
            app.UseIdentityServer();
            //添加靜態資源訪問
            app.UseStaticFiles();
            //
            app.UseMvcWithDefaultRoute();
        }
    }
}

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

API配置

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

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

using Microsoft.AspNetCore.Authorization;
using Swashbuckle.AspNetCore.Swagger;
using Swashbuckle.AspNetCore.SwaggerGen;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;

namespace TPL.API
{
    /// <summary>
    /// IdentityServer4認證過濾器
    /// </summary>
    public class AuthorizeCheckOperationFilter : IOperationFilter
    {
        public void Apply(Operation operation, OperationFilterContext context)
        {
            //獲取是否添加登錄特性
            var authAttributes = context.MethodInfo.DeclaringType.GetCustomAttributes(true)
             .Union(context.MethodInfo.GetCustomAttributes(true))
             .OfType<AuthorizeAttribute>().Any();

            if (authAttributes)
            {
                operation.Responses.Add("401", new Response { Description = "暫無訪問權限" });
                operation.Responses.Add("403", new Response { Description = "禁止訪問" });
                //給api添加鎖的標注
                operation.Security = new List<IDictionary<string, IEnumerable<string>>>
                {
                    new Dictionary<string, IEnumerable<string>> {{"oauth2", new[] {"demo_api"}}}
                };
            }
        }
    }
}

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

using System;
using System.Collections.Generic;
using IdentityServer4.AccessTokenValidation;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Swashbuckle.AspNetCore.Swagger;

namespace TPL.API
{
    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.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_1);
            //用戶校驗
            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 Info { Title = "Protected API", Version = "v1" });
                //向生成的Swagger添加一個或多個“securityDefinitions”,用於API的登錄校驗
                options.AddSecurityDefinition("oauth2", new OAuth2Scheme
                {
                    Flow = "implicit", // 只需通過瀏覽器獲取令牌(適用於swagger)
                    AuthorizationUrl = "http://localhost:5000/connect/authorize",//獲取登錄授權接口
                    Scopes = new Dictionary<string, string> {
                        { "demo_api", "Demo API - full access" }//指定客戶端請求的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, IHostingEnvironment env)
        {
            if (env.IsDevelopment())
            {
                app.UseDeveloperExceptionPage();
            }
            app.UseAuthentication();

            // Swagger JSON Doc
            app.UseSwagger();

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

修改Properties文件夾下的launchSettings啟動端口為5001,這里端口必須跟IdentityServer4中的Config配置的客服端資源中保持一致。

{
  "$schema": "http://json.schemastore.org/launchsettings.json",
  "iisSettings": {
    "windowsAuthentication": false, 
    "anonymousAuthentication": true, 
    "iisExpress": {
      "applicationUrl": "http://localhost:5001",
      "sslPort": 0
    }
  },
  "profiles": {
    "IIS Express": {
      "commandName": "IISExpress",
      "launchBrowser": true,
      "launchUrl": "swagger",
      "environmentVariables": {
        "ASPNETCORE_ENVIRONMENT": "Development"
      }
    },
    "TPL.API": {
      "commandName": "Project",
      "launchBrowser": true,
      "launchUrl": "swagger",
      "applicationUrl": "http://localhost:5001",
      "environmentVariables": {
        "ASPNETCORE_ENVIRONMENT": "Development"
      }
    }
  }
}

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

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

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

到此演示項目完畢。如果需求配合自己的數據庫使用請看我前面寫過的博文 自定義登錄即可。

 


免責聲明!

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



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