IdentityServer

摘要:
1、 创建IdentityServer4服务器。1.创建空ASP。NET核心项目。2.使用IdentityServer4.模型创建Config类;使用System.Collections。通用的namespaceSample{publicstaticclassConfig{publicstaticEnumerable<ApiScope>ApiScopes=>n

一、创建IdentityServer4服务器

1、创建一个ASP.NET Core空项目

2、创建一个Config类

using IdentityServer4.Models;
using System.Collections.Generic;

namespace Sample
{
    public static class Config
    {
        public static IEnumerable<ApiScope> ApiScopes => new ApiScope[]
        {
            new ApiScope{Name="sample_api",DisplayName="Sample Api"},
            new ApiScope{Name="scope2",DisplayName="Scope"}
        };
        public static IEnumerable<Client> Clients => new Client[]
        {
            new Client
            {
                ClientId="sample_Client",
                ClientName="Client Credentials Client",  //客户端名称
                AllowedGrantTypes=GrantTypes.ClientCredentials,//客户端验证(验证模式)
                ClientSecrets={new Secret("511536EF-F270-4058-80CA-1C89C192F69A".Sha256())},
                AllowedScopes={ "sample_api" } //访问资源范围
            }
        };
    }
}

3、配置服务和管道,IdentityServer4采用的中间件形式,必须进行管道配置

1)添加服务

        public void ConfigureServices(IServiceCollection services)
        {
            var builder= services.AddIdentityServer();//添加服务
            builder.AddDeveloperSigningCredential();//配置开发验证模式
            builder.AddInMemoryApiScopes(Config.ApiScopes);//配置内存API资源形式
            builder.AddInMemoryClients(Config.Clients);//配置内存客户端访问形式
        }

2)注册应用

        public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
        {
            if (env.IsDevelopment())
            {
                app.UseDeveloperExceptionPage();
            }

            app.UseIdentityServer();
        }

4、测试https://localhost:5001/.well-known/openid-configuration进行GET请求,查看

IdentityServer第1张

 2)使用https://localhost:5001/connect/token获取token

IdentityServer第2张

 3)token为jwt加密,解析查看

IdentityServer第3张

 二、创建ASP.NET Core API

1、nuget安装Microsoft.AspNetCore.Authentication.JwtBearer

编写API控制器

   public class IdentityController : ControllerBase
    {
        [Route("api/Identity")]
        [Authorize]
        public IActionResult Get()
        {
            return new JsonResult(
                from claim in User.Claims
                select new{ claim.Type, claim.Value }
                );
        }
    }

2、配置认证服务

         public void ConfigureServices(IServiceCollection services)
        {
            services.AddControllers();
            services.AddAuthentication("Bearer")
                .AddJwtBearer("Bearer", options =>
                {
                    options.Authority = "https://localhost:5001";
                    options.TokenValidationParameters = new TokenValidationParameters
                    {
                        ValidateAudience = false
                    };
                });

        }

3、将服务加入请求管道

app.UseAuthentication();

4、测试

IdentityServer第4张

三、创建客户端程序访问

测试客户端代码

            var client = new HttpClient();
            var disco = await client.GetDiscoveryDocumentAsync("https://localhost:5001");
            if (disco.IsError)
            {
                Console.WriteLine(disco.Error);
                return;
            }
            var tokenResponse = await client.RequestClientCredentialsTokenAsync(
                new ClientCredentialsTokenRequest
                {
                    Address=disco.TokenEndpoint,
                    ClientId= "sample_Client",
                    ClientSecret= "511536EF-F270-4058-80CA-1C89C192F69A"
                });
            if (tokenResponse.IsError)
            {
                Console.WriteLine(tokenResponse.Error);
                return;
            }
            Console.WriteLine(tokenResponse.Json);

测试结果

IdentityServer第5张

 测试请求资源

            var apiclient = new HttpClient();
            apiclient.SetBearerToken(tokenResponse.AccessToken);
            var response = await apiclient.GetAsync("https://localhost:6001/api/Identity");
            if (!response.IsSuccessStatusCode)
            {
                Console.WriteLine(response.StatusCode);
                return;
            }
            var context = await response.Content.ReadAsStringAsync();
            Console.WriteLine();
            Console.WriteLine(JArray.Parse(context));
            Console.ReadLine();

配置API资源的授权

            services.AddAuthorization(options =>
            {
                options.AddPolicy("ApiScope", builder =>
                {
                    builder.RequireAuthenticatedUser();
                    builder.RequireClaim("scope", "sample_api");
                });
            });

免责声明:文章转载自《IdentityServer》仅用于学习参考。如对内容有疑问,请及时联系本站处理。

上篇压力测试php:// 访问各个输入/输出流下篇

宿迁高防,2C2G15M,22元/月;香港BGP,2C5G5M,25元/月 雨云优惠码:MjYwNzM=

随便看看

svn常见问题汇总

要添加到版本库,必须更新工作副本中的文件。5.更新时,系统会提示您文件冲突,将工作副本中的文件与服务器中的文件进行比较“当版本管理系统更改计算机上的工作副本时”,它会尝试将您的意图写入计算机上的日志文件,因此日志文件记录可能与您的上次工作状态不一致。Subversion客户端将在提交内容之前在本地工作副本中写入日志。首先删除隐藏文件夹中tmp下的临时文件。服...

oracle的序列号(sequence)

Oracle的自动递增列应使用序列号。在初始化阶段,需要手动创建序列,然后在插入序列时手动读取分配给相关字段(如ID)的序列的nextval。这很麻烦。但是,这对于SQL Server来说不是问题,可以获得。oracle的序列号也有缓存。默认情况下,一次生成20个。如果没有用完,它们可能会丢失,这可能会导致ID不一致。此外,有时这可能会引起误解。例如,我有一...

图论介绍(Graph Theory)

G-v具有比G更多的连通分支,因此v被称为G的截断点G-e具有比G多的连通分支。定理:连通图G,其中e是桥e不属于G的任何环有顶点u,v,使得任何路径u-v都通过e连通图G;而w是存储在顶点u,v处的割点,使得任意路径u-v通过w定义:顶点之间的距离x-y:所有x-y路径的最小长度。...

java 服务接口API限流 Rate Limit

服务接口的流量控制策略:分流、降级、流量限制等。2)使用Reids的列表结构,而不是incr命令1FUNCTIONLIMIT_API_CALLL2current=LLEN3IFcurrent˃10THEN4ERROR“toomanyrequestsperssecond”5ELSE6IFEXIST==FALSE7MULTI8RPUSH9EXPIRE10EXEC...

electron用默认浏览器打开链接的3种实现方式

在使用Electron开发桌面程序的过程中,我们可能经常需要使Electron程序中包含的链接在单击后直接调用系统的默认浏览器打开。仔细阅读文档后,我们都知道它的核心原理是调用系统的默认浏览器,通过Electron shell模块中的openExternal方法打开链接。然而,它的实现有不同的方法,彻底接管和选择性接管。介绍第3章中的有效方法。以上三种方法都...

DB2锁表或超时解决方案

命令如下:db2"forceapplication"4、使用命令listapplication查看是否已经断开了哪些进行了死锁的进程。...