webApi安全訪問之 IdentityServer4使用總結

來源:互聯網
上載者:User

     webapi項目通常需要考慮跨域,安全性等問題。今天總結一種最簡單的方式,來保障webapi不被別人隨便調用。這裡總結下identityserver4的使用。

IdentityServer4 是最新也是比較容易上手的一個開源架構,你要是從IdentityServer3開始用,會很容易頭大,搞不清楚所以然。就github上面的使用例

子看,IdentityServer4是比較容易理解上手的。這次我們使用了類似openId connect的方式。用戶端訪問apiServer的時候,先去IdentityServer上面請求

一個訪問token。使用這個token,訪問ApiServer的各個介面。


如上圖: IdentityServer4 需要增加IdentityServer4 架構的引用,同時webapiserver,需要增加IdentityServer4 .AccessTokenValidation的引用,用戶端可以通過多種方式,請求。可以參考git上面的sample。我這裡使用的控制台程式測試用,Client 引入identityModel  的引用。

下面搭建架構:

1 首先是identityserver4 ,主要是從demo裡改寫配置即可。基本不需要增加代碼。

在Startup.cs 中 配置IdentityServer4

        public void ConfigureServices(IServiceCollection services)        {            services.AddDeveloperIdentityServer()                .AddInMemoryScopes(Config.GetScopes())                .AddInMemoryClients(Config.GetClients());        }
        public void Configure(IApplicationBuilder app, IHostingEnvironment env)        {            app.UseIdentityServer();        }
在Config中配置可用的client,注意AllowdGrantTypes 是ClientCredentials類型的。

        public static IEnumerable<Client> GetClients()        {            List<Client> lst = new List<Client>();            var client = new Client()            {                ClientId = setting.ClientID,                AllowedGrantTypes = GrantTypes.ClientCredentials,                ClientSecrets =                    {                        new Secret(setting.SercetKey.Sha256())                    },                AccessTokenLifetime = setting.TokenLiftTime * 3600, //AccessToken的到期時間, in seconds                 AllowedScopes = { setting.APPName }            };            lst.Add(client);            return lst;                   }

2 webapi 服務配置

由於新的identityserver4都是可以基於.net core平台的,發布在iis上使用useIISintegration屬性代替useUrls。

        public static void Main(string[] args)        {            var host = new WebHostBuilder()                .UseKestrel()                .UseIISIntegration()  //.UseUrls("http://localhost:5001")                 .UseContentRoot(Directory.GetCurrentDirectory())                .UseIISIntegration()                .UseStartup<Startup>()                .Build();            host.Run();        }

然後在Startup.cs 中 配置需要綁定的授權伺服器的ip。即修改 Authority屬性,指定apiName,這些資訊都是會被寫到token的簽名裡,所以一個字元

都不能錯。否則,n多的401錯誤。unauthroity public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory)

        {            loggerFactory.AddConsole(Configuration.GetSection("Logging"));            loggerFactory.AddDebug();              app.UseIdentityServerAuthentication(new IdentityServerAuthenticationOptions            {                Authority = Configuration["Server"],                RequireHttpsMetadata = false,               // BackChannelTimeouts = t                ApiName = "TempSenGoApi"            });            app.UseCors("any");            app.UseMvc();        }

下面我們來定義API,添加一個Web API 控制器 ClientController  使用 【Authorize】注釋來標記類。則token的驗證全部由架構完成。如果token驗證通過,則進入get action的代碼中,進行商務邏輯的處理,如果驗證非法。則不會進入get的代碼裡。 [Route( " api/[controller] " )]

    [Authorize]    public class ClientController : Controller    {        [HttpGet]        public IActionResult Get()        {            return new JsonResult(from c in User.Claims select new { c.Type, c.Value });        }    }
3.請求token

用戶端代碼如下: public static void Main( string [] args)

        {            //訪問授權伺服器擷取token            var disco = DiscoveryClient.GetAsync("http://localhost:5000").Result;            var tokenClient = new TokenClient(disco.TokenEndpoint, "linezeroclient", "secret");            var tokenResponse = tokenClient.RequestClientCredentialsAsync("zeroapi").Result;                        //設定token 訪問API tokenResponse.AccessToken 就是請求到的token,可以使用這個token訪問webapi            var client = new HttpClient();            client.SetBearerToken(tokenResponse.AccessToken);            var response = client.GetAsync("http://localhost:5001/api/Identity").Result;            if (!response.IsSuccessStatusCode)            {                Console.WriteLine(response.StatusCode);            }            var content = response.Content.ReadAsStringAsync().Result;            Console.WriteLine(content);            Console.ReadKey();        }
4 使用postman測試該token。


總結: 我理解的處理流程是這樣的。token儲存在identityserver4伺服器上而不是臨時儲存,比如記憶體中,就算伺服器重新啟動,token依舊有效。只依賴於token本身的內容,時候到期。當應用client請求到了token以後,在head中加入token。請求發送給webapi,webapi中的AccessTokenValidation 會將token即時發送給identityserver4,去驗證。驗證通過後,進入action的處理函數中。也就是說無論webapi重新啟動,還是identityserver4重新啟動,都不會使token到期。

做完才發現個不錯的文章。也可以參考。

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.