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

簡介

原本不想寫這篇博文,但在網上找到的文章博客都沒有完整配置信息,因此這裏記錄下。html

不瞭解IdentityServer4的能夠看看我以前寫的入門博文git

Swagger 官方演示地址github

源碼地址數據庫

配置IdentityServer4服務端

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

 

這裏選擇空白項,新建空白項目windows

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

等待安裝完成後,下載官方提供的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文件配置,修改以下:app

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,再次訪問接口便可正常訪問,受權先後效果以下:

到此演示項目完畢。若是需求配合本身的數據庫使用請看我前面寫過的博文 自定義登陸便可。

相關文章
相關標籤/搜索