IdentityServer4客户端认证(慎重踩坑)

微软提供了一些针对IdentityServer4的项目模板,在命令行中输入” dotnet new -i IdentityServer4.Templates“即可安装,安装好后可以看到当前已安装的项目模板,其中有一个"is4empty",其实就是一个asp.net core 应用装了IdentityServer4包。在命令行中输入:dotnet new is4empty -n Projectname 就会根据这个模板生成一个新项目。下图是我的项目,一个api客户端(idsapi或者jwtdemo)、一个mvc客户端(那个client),一个identityserver4服务端(idstest),其中Api客户端是受保护的Api资源,Mvc客户端是第三方客户端,用于访问被保护的Api客户端,可以看成是任意后端程序。

 

 2:idstest:内部结构

 

 直接贴代码:

Config.cs

复制代码
 public static class Config
    {
        public static IEnumerable<IdentityResource> IdentityResources =>
            new IdentityResource[]
            {
            new IdentityResources.OpenId(),
            new IdentityResources.Profile(),
            };

        public static IEnumerable<ApiScope> ApiScopes =>
            new ApiScope[]
            {
            new ApiScope("secretapi"),
                //new ApiScope("scope2"),
            };

        public static IEnumerable<ApiResource> ApiResources =>
            new ApiResource[]
            {
            new ApiResource("secretapi","Secret Api")
            {
                //!!!重要  请注意 在ApiSource里面一定要添加这个,不然永远是401
                Scopes = { "secretapi" }
            },
                //new ApiResource("api2","#api2")
                //{
                //    //!!!重要
                //    Scopes = { "scope2"}
                //},
            };

        public static IEnumerable<Client> Clients =>
            new Client[]
            {
            new Client
            {
                ClientId = "apiClientCd",
                ClientName = "Client Credentials Client",

                AllowedGrantTypes = GrantTypes.ClientCredentials,
                ClientSecrets = { new Secret("apiSecret".Sha256()) },

                AllowedScopes = { "secretapi" }
            },
            };
    }
复制代码

StartUp.cs

复制代码
public void ConfigureServices(IServiceCollection services)
        {
            // uncomment, if you want to add an MVC-based UI
            //services.AddControllersWithViews();

            var builder = services.AddIdentityServer(options =>
            {
                // see https://identityserver4.readthedocs.io/en/latest/topics/resources.html
                options.EmitStaticAudienceClaim = true;
            });
            //.AddInMemoryIdentityResources(Config.IdentityResources)
            //.AddInMemoryApiScopes(Config.ApiScopes)
            //.AddInMemoryApiResources(Config.GetApis())
            //.AddInMemoryClients(Config.GetClients());

            // in-memory, code config
            builder.AddInMemoryIdentityResources(Config.IdentityResources);
            builder.AddInMemoryApiScopes(Config.ApiScopes);
            //添加API资源
            builder.AddInMemoryApiResources(Config.ApiResources);
            builder.AddInMemoryClients(Config.Clients);

            // not recommended for production - you need to store your key material somewhere secure
            builder.AddDeveloperSigningCredential();
        }
复制代码

然后在添加中间件:app.UseIdentityServer();

 

2:idsapi

这个就是受保护的api资源。

首先定义一个api

我是直接使用的自带的api,然后加了一个特性:Authorize

 

 这个时候用postman访问就会出现401

 

 这个时候启动idtest,拿到token,这里使用的是客户端模式。

如图

 

 

 

 里面的值与配置相同。

 

在这里拿到token 之后还需要在API项目里面添加如下代码

1
2
3
4
5
6
7
8
9
10
services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_3_0);
           services.AddAuthentication("Bearer").AddIdentityServerAuthentication(r =>
           {
               //认证地址
               r.Authority = "http://localhost:6666";
               //权限标识
               r.ApiName = "secretapi";
               //是否必需HTTPS
               r.RequireHttpsMetadata = false;
           });

  添加中间件:

app.UseAuthentication();
app.UseAuthorization();

将token复制过去再访问就可成功:

 

 踩坑:在ApiSource里面一定要添加Scope,不然会不成功

原文参考:https://www.cnblogs.com/liujiabing/p/11460486.html

posted @   游园惊梦、  阅读(633)  评论(0编辑  收藏  举报
编辑推荐:
· 基于Microsoft.Extensions.AI核心库实现RAG应用
· Linux系列:如何用heaptrack跟踪.NET程序的非托管内存泄露
· 开发者必知的日志记录最佳实践
· SQL Server 2025 AI相关能力初探
· Linux系列:如何用 C#调用 C方法造成内存泄露
阅读排行:
· Manus爆火,是硬核还是营销?
· 终于写完轮子一部分:tcp代理 了,记录一下
· 别再用vector<bool>了!Google高级工程师:这可能是STL最大的设计失误
· 单元测试从入门到精通
· 震惊!C++程序真的从main开始吗?99%的程序员都答错了
历史上的今天:
2020-09-02 任务的取消
点击右上角即可分享
微信分享提示