• .Netcore 2.0 Ocelot Api网关教程(5)- 认证和授权


    本文介绍Ocelot中的认证和授权(通过IdentityServer4),本文只使用最简单的IdentityServer,不会对IdentityServer4进行过多讲解。

    1、Identity Server 4

    (1)新建一个新的WebApi项目命名为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)新建一个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如下所示,可以获得一个token

     
    token.png


    至此,IdentityServer建立完成。

    2、修改OcelotGetway

    (1)修改Api网关项目中Startup中的ConfigureServices方法,添加IdentityServer认证:

    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 的路由配置中的配置项中添加

    "AuthenticationOptions": {
        "AuthenticationProviderKey": "TestKey",
        "AllowScopes": []
    }
    

    注意:配置中的TestKey必须与添加IdentityServer认证时的 authenticationScheme 一致。
    并添加一个获取Token的路由如下:

    {
        "DownstreamPathTemplate": "/api/Token",
        "DownstreamScheme": "http",
        "DownstreamHostAndPorts": [
        {
            "Host": "localhost",
            "Port": 6000
        }],
        "UpstreamPathTemplate": "/GetToken",
        "UpstreamHttpMethod": [ "Get" ]
    }
    

    分别运行IdentityServer、OcelotGetway、WebApiA三个项目,然后使用Postman请求http://localhost:5000/webapia/values

     
    unauthorized.png


    可以看到提示未授权,
    接着请求http://localhost:5000/GetToken获取token,并将token携带至上一个请求

     
    authorized.png


    可以看到正常请求到数据。
    源码下载

    完,下一篇介绍配置管理

    作者:Weidaicheng
    链接:https://www.jianshu.com/p/57d4d2fcec00
    来源:简书
    著作权归作者所有。商业转载请联系作者获得授权,非商业转载请注明出处。

  • 相关阅读:
    建议自学
    大牛之术
    学习榜样
    .net源码
    练习题
    学习-如何克服拖延
    如何解决困难问题
    最近阅读
    如何学习一门新语言
    安全问题关注博客
  • 原文地址:https://www.cnblogs.com/lhxsoft/p/11724764.html
Copyright © 2020-2023  润新知