webApi安全訪問之 IdentityServer4使用總結


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 staticvoid 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過期。

做完才發現個不錯的帖子。也可以參考。
---------------------
作者:業余程序猿
來源:CSDN
原文:https://blog.csdn.net/jacky_zh/article/details/78603161
版權聲明:本文為博主原創文章,轉載請附上博文鏈接!


免責聲明!

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



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