本文介紹Ocelot中的認(rèn)證和授權(quán)(通過IdentityServer4)糠馆,本文只使用最簡單的IdentityServer娄涩,不會對IdentityServer4進(jìn)行過多講解嘲驾。
1系忙、Identity Server 4
(1)新建一個(gè)新的WebApi項(xiàng)目命名為IdentityServer诵盼,添加 IdentityServer4
Nuget包。
(2)添加Config類银还,添加如下代碼:
public static IEnumerable<ApiResource> GetApiResources()
{
return new List<ApiResource>()
{
new ApiResource("api1", "My Api")
};
}
public static IEnumerable<Client> GetClients()
{
return new List<Client>()
{
new Client()
{
ClientId = "client",
AllowedGrantTypes = GrantTypes.ClientCredentials,
ClientSecrets =
{
new Secret("secret".Sha256())
},
AllowedScopes =
{
"api1"
}
}
};
}
(3)修改Startup中的ConfigureServices方法风宁,添加如下代碼:
services
.AddIdentityServer()
.AddDeveloperSigningCredential()
.AddInMemoryApiResources(Config.GetApiResources())
.AddInMemoryClients(Config.GetClients());
修改Startup中的Config方法,在 app.UseMvc()
之前添加 app.UseIdentityServer()
(4)新建一個(gè)TokenController用于獲取Token蛹疯,代碼如下:
[Produces("application/json")]
[Route("api/Token")]
public class TokenController : Controller
{
public async Task<JObject> Get()
{
var disco = await DiscoveryClient.GetAsync($"{Request.Scheme}://{Request.Host}");
if(disco.IsError)
{
Console.WriteLine(disco.Error);
return null;
}
var tokenClient = new TokenClient(disco.TokenEndpoint, "client", "secret");
var tokenResponse = await tokenClient.RequestClientCredentialsAsync("api1");
if(tokenResponse.IsError)
{
Console.WriteLine(tokenResponse.Error);
return null;
}
return tokenResponse.Json;
}
}
使用Postman請求http://localhost:6000/api/Token如下所示戒财,可以獲得一個(gè)token
至此,IdentityServer建立完成捺弦。
2饮寞、修改OcelotGetway
(1)修改Api網(wǎng)關(guān)項(xiàng)目中Startup中的ConfigureServices方法,添加IdentityServer認(rèn)證:
services
.AddAuthentication(JwtBearerDefaults.AuthenticationScheme)
.AddIdentityServerAuthentication("TestKey", options =>
{
options.Authority = "http://localhost:6000";
options.RequireHttpsMetadata = false;
options.ApiName = "api1";
});
并在Configuration方法中添加 app.UseAuthentication();
(2)修改configuration.json
在上游請求路徑為 /webapia/values
的路由配置中的配置項(xiàng)中添加
"AuthenticationOptions": {
"AuthenticationProviderKey": "TestKey",
"AllowScopes": []
}
注意:配置中的TestKey必須與添加IdentityServer認(rèn)證時(shí)的 authenticationScheme
一致列吼。
并添加一個(gè)獲取Token的路由如下:
{
"DownstreamPathTemplate": "/api/Token",
"DownstreamScheme": "http",
"DownstreamHostAndPorts": [
{
"Host": "localhost",
"Port": 6000
}],
"UpstreamPathTemplate": "/GetToken",
"UpstreamHttpMethod": [ "Get" ]
}
分別運(yùn)行IdentityServer幽崩、OcelotGetway、WebApiA三個(gè)項(xiàng)目寞钥,然后使用Postman請求http://localhost:5000/webapia/values
可以看到提示未授權(quán)慌申,
接著請求http://localhost:5000/GetToken獲取token,并將token攜帶至上一個(gè)請求
可以看到正常請求到數(shù)據(jù)理郑。
源碼下載