首页 > 其他分享 >IdentityServer4 客户端模式(.net5)

IdentityServer4 客户端模式(.net5)

时间:2023-08-22 11:13:03浏览次数:44  
标签:5000 http supported token client IdentityServer4 net5 localhost 客户端

添加服务端(api)

1.添加Nuget包

Nuget添加 IdentityServer4

2.添加Config.cs配置类

public class Config
{
    /// <summary>
    /// 提示invalid_scope 添加
    /// </summary>
    public static IEnumerable<ApiScope> ApiScopes =>
        new ApiScope[] {new ApiScope("api")};
        
    public static IEnumerable<ApiResource> GetResources()
    {
        return new List<ApiResource>
        {
            new ApiResource("api","My Api")
        };
    }
    public static IEnumerable<Client> GetClients()
    {
        return new List<Client>
        {
            new Client
            {
                ClientId = "client",
                AllowedGrantTypes = GrantTypes.ClientCredentials,
                ClientSecrets =
                {
                    new Secret("secret".Sha256())
                },
                AllowedScopes = {"api"}
            }
        };
    }
}

3.StartUp.cs修改

public void ConfigureServices(IServiceCollection services)
{
    services.AddIdentityServer()
        .AddDeveloperSigningCredential()
        .AddInMemoryApiResources(Config.GetResources())
        .AddInMemoryClients(Config.GetClients())
        //这个ApiScopes需要新加上,否则访问提示invalid_scope
        .AddInMemoryApiScopes(Config.ApiScopes)
        ;
    services.AddControllers();
}
public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
    if (env.IsDevelopment())
    {
        app.UseDeveloperExceptionPage();
    }

    app.UseRouting();

    app.UseIdentityServer();

    app.UseEndpoints(endpoints =>
    {
        endpoints.MapControllers();
    });
}

4.查看IdentityServer4配置信息

http://localhost:5000/.well-known/openid-configuration

{
	"issuer": "http://localhost:5000",
	"jwks_uri": "http://localhost:5000/.well-known/openid-configuration/jwks",
	"authorization_endpoint": "http://localhost:5000/connect/authorize",
	"token_endpoint": "http://localhost:5000/connect/token",
	"userinfo_endpoint": "http://localhost:5000/connect/userinfo",
	"end_session_endpoint": "http://localhost:5000/connect/endsession",
	"check_session_iframe": "http://localhost:5000/connect/checksession",
	"revocation_endpoint": "http://localhost:5000/connect/revocation",
	"introspection_endpoint": "http://localhost:5000/connect/introspect",
	"device_authorization_endpoint": "http://localhost:5000/connect/deviceauthorization",
	"frontchannel_logout_supported": true,
	"frontchannel_logout_session_supported": true,
	"backchannel_logout_supported": true,
	"backchannel_logout_session_supported": true,
	"scopes_supported": ["api", "offline_access"],
	"claims_supported": [],
	"grant_types_supported": ["authorization_code", "client_credentials", "refresh_token", "implicit", "urn:ietf:params:oauth:grant-type:device_code"],
	"response_types_supported": ["code", "token", "id_token", "id_token token", "code id_token", "code token", "code id_token token"],
	"response_modes_supported": ["form_post", "query", "fragment"],
	"token_endpoint_auth_methods_supported": ["client_secret_basic", "client_secret_post"],
	"id_token_signing_alg_values_supported": ["RS256"],
	"subject_types_supported": ["public"],
	"code_challenge_methods_supported": ["plain", "S256"],
	"request_parameter_supported": true
}

5.获取token

  • localhost:5000/connect/token
  • post 请求
  • body,x-www-form-urlencode添加参数
    • client_id:client
    • client_secret:secret
    • grant_type:client_credentials
{
    "access_token": "eyJhbGciOiJSUzI1NiIsImtpZCI6IkFDMEU3NUU4QzdGNjI0NkRBNjY2RDE5RjVCMDdCNjkyIiwidHlwIjoiYXQrand0In0.eyJuYmYiOjE2NDEzMTAxMjksImV4cCI6MTY0MTMxMzcyOSwiaXNzIjoiaHR0cDovL2xvY2FsaG9zdDo1MDAwIiwiY2xpZW50X2lkIjoiY2xpZW50IiwianRpIjoiNEZCMUNCMTU3ODJCNzgwM0U4NUQ2NTNCNTY0RkIzQzEiLCJpYXQiOjE2NDEzMTAxMjksInNjb3BlIjpbImFwaSJdfQ.ysbsX8tUFpg3QzHewF3-hR5soC2SBc0wCiqMBS3Y6TjYeCLud_W97s9t3DW8JmZR6HE5Kx9M6rakDx1xsgbzUuo9VXGQFQCI6Oe__ALzPDglkygRikr6QmQ7zOpKcefd2mFXP1ILLC8DUr-oUa9n_-SkixFMDVk4siIpv4bXG2sVIMFmo-hkBLwIS0SCe0o0sgzu_bfMBKIKtmbc89Kq2ZSe2abDIF7D6ecNS0nXUInh8B1uYiRohdB8jmfMRcE0qm5-ztrEIfOXhlfaI_dP0hGVOFNHYFqiFcLj-0ShqAYwijVNaGXtZ79agIacmozkmtWszEtvuE4VdlSiUcIBMw",
    "expires_in": 3600,
    "token_type": "Bearer",
    "scope": "api"
}

获取token

添加客户端(api)

1.api添加[Authorize]

  [Authorize] //授权
  [ApiController]
  [Route("[controller]")]
  public class WeatherForecastController : ControllerBase{}

2.startup.cs配置

  1. Nuget安装 IdentityServer4.AccessTokenValidation
  2. StartUp.cs 文件修改
public void ConfigureServices(IServiceCollection services)
{
    services.AddAuthentication("Bearer")
        .AddJwtBearer("Bearer",options =>
        {
            options.Authority = "http://localhost:5000";
            //如果不使用Https,则需要配置这个
            options.RequireHttpsMetadata = false;
            options.TokenValidationParameters = new TokenValidationParameters
            {
                ValidateAudience = false
            };
        })
        ;

    services.AddControllers();
}
public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
    if (env.IsDevelopment())
    {
        app.UseDeveloperExceptionPage();
    }
    app.UseRouting();
    app.UseAuthentication();
    app.UseAuthorization();
    app.UseEndpoints(endpoints =>
    {
        endpoints.MapControllers();
    });
}

3.postman 调用

Bearer eyJhbGciOiJSUzI1NiIsImtpZCI6IkFDMEU3NUU4QzdGNjI0NkRBNjY2RDE5RjVCMDdCNjkyIiwidHlwIjoiYXQrand0In0.eyJuYmYiOjE2NDEzMTE5MDYsImV4cCI6MTY0MTMxNTUwNiwiaXNzIjoiaHR0cDovL2xvY2FsaG9zdDo1MDAwIiwiY2xpZW50X2lkIjoiY2xpZW50IiwianRpIjoiNUE1QzQzRTkzOTJGM0U0QTNCOTIxNThERkM4QjNDRjIiLCJpYXQiOjE2NDEzMTE5MDYsInNjb3BlIjpbImFwaSJdfQ.Tu1LhlxOCvLlxKbrpGEN6npvjLmLw2R3_GXkhqpZqIID09Sj5y5fRqZe2WQN2kXmxms8AHON6rS_DRePb7ZA_YVBk9DrWxL8QG3JpHor8RTk1qQZHxwfnlRtkGNqLsN9g7gBTxaAvzTInPwSE9EbFkUCvP_iGdawrvzwFPovcP31FlNWL4eUkINcsLr8nuPchIWjLaVRydrq8O_c_OBBURGiiCvN4YO-0VLPV3vaFjkv1MQxRR3UvxnfXFN1M1-nsHqXzLPXCdNi3ubh58nraKc4IjPHSm2M-1ELZ2htLOzLwtGTL37qtL1QOs-L5vZ7V1Zz7PpSNJa6ngnJ9pzgww

获取token

至此,postman调用成功。

第三方调用api

1.创建控制台应用程序(ThirdPartyDemo)

2.添加Nuget包

Nuget添加 IdentityModel

3.具体代码

static async Task Main(string[] args)
{
    var client = new HttpClient();
    var disco = await client.GetDiscoveryDocumentAsync("http://localhost:5000");
    if (disco.IsError)
    {
        Console.WriteLine(disco.Error);
    }
    var tokenResponse = await client.RequestClientCredentialsTokenAsync(new ClientCredentialsTokenRequest
    {
        Address = disco.TokenEndpoint,
        ClientId = "client",
        ClientSecret = "secret",
        Scope = "api"
    });
    if (tokenResponse.IsError)
    {
        Console.WriteLine(tokenResponse.Error);
        return;
    }
    Console.WriteLine(tokenResponse.Json);

    //调用api
    var apiClient = new HttpClient();
    apiClient.SetBearerToken(tokenResponse.AccessToken);

    var response = await apiClient.GetAsync("http://localhost:5001/WeatherForecast");
    if (!response.IsSuccessStatusCode)
    {
        Console.WriteLine(response.StatusCode);
    }
    else
    {
        var content = await response.Content.ReadAsStringAsync();
        Console.WriteLine(JArray.Parse(content));
    }

    Console.ReadKey();
}

aa

参考官网地址:https://identityserver4.readthedocs.io/en/latest/

标签:5000,http,supported,token,client,IdentityServer4,net5,localhost,客户端
From: https://www.cnblogs.com/huiteresa/p/17648027.html

相关文章

  • Web_JavaScript_客户端监测;
    //client_detection.js客户端监测//client自动运行varclient=function(){//呈现引擎varengine={ie:0,gecko:0,webkit:0,khtml:0,opera:0,//完整版本号ver:null......
  • gRPC 客户端调用服务端需要连接池吗?
    发现的问题在微服务开发中,gRPC的应用绝对少不了,一般情况下,内部微服务交互,通常是使用RPC进行通信,如果是外部通信的话,会提供https接口文档对于gRPC的基本使用可以查看文章gRPC介绍对于gRPC,我们需要基本知道如下的一些知识点:gRPC的基本四种模式的应用场景请求响应......
  • c2工具sliver的python客户端无法修改grpc超时时间的解决办法
    业务需要,调用了很多implants来执行对应系统上的命令,但是无论怎么指定interactive.py中execute方法参数,命令执行超时时间总是30.后面通过扩展execute方法增加一个grpc超时参数后解决;具体方法如下:asyncdefexecute_ex(self,exe:str,args:List[str],output:bool,tim......
  • 多级反向代理[Squid]下获取客户端真实IP地址
    在很多应用下都可能有需要将用户的真实IP记录下来,这时就要获得用户的真实IP地址,在JSP里,获取客户端的IP地址的方法是:request.getRemoteAddr(),这种方法在大部分情况下都是有效的。但是在通过了Apache,Squid等反向代理软件就不能获取到客户端的真实IP地址了。这段时间在做IP统计的......
  • 解决Windows远程桌面“由于安全设置错误, 客户端无法连接到远程计算机”
    用windows2008远程桌面连接Ubuntu系统,出现如下错误: 但我用win10可以进入登录界面,查了一下,需要修改安全策略,设置为如下: 参考资料:https://it.cha138.com/python/show-1249300.html ......
  • MQTTnet4入门(二)实现客户端
    上一篇写服务端的文章《MQTTnet4入门(一)实现服务端》已经是去年年底,现在MQTTnet的版本是4.2.1.781,总的来说改动不大。下面以新版为例实现一个客户端。varmqttClientOptions=newMqttClientOptionsBuilder().WithTcpServer("地址",端口).Wit......
  • .net5 npoi扩展 获取单元格合并区域
    核心逻辑为通过sheet.GetMergedRegion(i)获取所有的合并区域信息,随后检测单元格是否在此区域内新增对象识别合并单元格的开始、结束位置///<summary>///获取指定行列的数据///</summary>///<paramname="row"></param>///<paramname......
  • 让SignalR客户端回调支持强类型
    几天写一个小程序的时候用到了SignalR,发现现在SingalRServer支持强类型了,也就是说,我们可以定义一个客户端的通知契约:    public interface IClient    {        void SayHello(string message);    }然后Hub就可以这么写了:    public class Me......
  • MySQL客户端工具 phpMyAdmin MySQL Workbench HeidiSQL Sequel Pro DBeaver
    MySQL是一种流行的关系型数据库管理系统,它被广泛用于Web应用程序和企业级应用程序的开发中。目前,市面上有不少好用的MySQL客户端工具,如Navicat,SQLyog等。但这些产品虽然功能强大,却都是收费的,而且费用还不低。幸运的是,收费产品并不是你的唯一选择,目前也有不少开源的工具。如果你不想......
  • SignalR 客户端源生成器 客户端强类型方法
     SignalR客户端源生成器根据您定义的接口生成强类型的发送和接收代码。您可以在客户端上重用来自强类型SignalR集线器的相同接口来代替松散类型的.On("methodName",...)方法。同样,您的集线器可以为其方法实现一个接口,并且客户端可以使用该相同接口来调用集线器方法。要使......