记录IdentityServer4在.net core3.1上的使用 (一)

IdentityServer4在.net core上不同的版本上的使用方式有微小的差别,我在网上找了一些文章,按照他们的写总有问题,有些是因为.net core版本的问题  有些是因为IdentityServer4的dll版本的问题  不过总算是东找西找,实现了功能  这篇文章先写通过Token获取资源

写两个项目 一个是api的项目,一个是IdentityServer的项目,在api的项目里使用IdentityServer中间件, 受保护的方法需要向先IdentityServer项目获取Token,然后携带Token进行访问。

首先 写IdentityServer项目  第一步:安装IdentityServer4包

第二步:创建Config类  根据自己的项目情况添加配置

    public class Config
    {
        /// <summary>
        /// 定义API范围
        /// </summary>
        public static IEnumerable<ApiScope> ApiScopes =>
        new List<ApiScope>
        {
           new ApiScope("api1","MY_API")
        };

        /// <summary>
        /// 定义API资源
        /// </summary>
        /// <returns></returns>
        public static IEnumerable<ApiResource> GetApiResources()
        {
            return new List<ApiResource>()
            {
                new ApiResource("api1","MY_API"){ Scopes={ "api1" } }
            };
        }


        public static IEnumerable<IdentityResource> GetIdentityResources()
        {
            return new IdentityResource[]
            {
                new IdentityResources.OpenId()
            };
        }

        public static IEnumerable<Client> GetClients()
        {
            return new List<Client>
            {
                new Client
                {
                    ClientId = "Client",
                    AllowedGrantTypes = GrantTypes.ClientCredentials,
                    ClientSecrets = {
                        new Secret("secret".Sha256()),
                    },
                    AllowedScopes = {"api1"}
                },
            // resource owner password grant client
               new Client
               {
                  ClientId = "ro.client",
                  AllowedGrantTypes = GrantTypes.ResourceOwnerPassword,

                  ClientSecrets =
                  {
                      new Secret("secret".Sha256())
                  },
                  AllowedScopes = { "openid" }
               }
            };
        }
    }

第三步:在Startup类里面进行配置

    public class Startup
    {
        public Startup(IConfiguration configuration)
        {
            Configuration = configuration;
        }

        public IConfiguration Configuration { get; }

        public void ConfigureServices(IServiceCollection services)
        {

            services.AddControllers();

            var builder = services.AddIdentityServer()
                .AddInMemoryClients(Config.GetClients())
                .AddInMemoryIdentityResources(Config.GetIdentityResources())
                .AddInMemoryApiResources(Config.GetApiResources())
                .AddInMemoryApiScopes(Config.ApiScopes);

            builder.AddDeveloperSigningCredential();
        }

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

            app.UseRouting();

            app.UseIdentityServer(); //这个一定要在UseRouting和UseEndpoints之间

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

    }

IdentityServer项目添加完毕,启动项目访问/.well-known/openid-configuration  出现以下信息

获取token:

前两个参数的值和Config类里设置的对应,第三个参数是固定的

 

然后就是添加api项目进行使用了 

在api项目的Startup类里添加如下配置: 在ConfigureServices方法里添加

            services.AddAuthentication("Bearer").AddJwtBearer("Bearer", option =>
            {
                option.Authority = "http://localhost:8432"; //IdentityServer项目域名
                option.RequireHttpsMetadata = false;//如果不使用Https,则需要配置这个
                option.TokenValidationParameters = new TokenValidationParameters
                {
                    ValidateAudience = false
                };

                IdentityModelEventSource.ShowPII = true;
            });

在Configure方法里添加认证   app.UseAuthentication();  这个认证同样也要添加在UseRouting和UseEndpoints之间 因为请求进入管道是依次通过各个中间件

使用身份认证的方式是在Controller或者方法上面添加[Authorize]特性,下面是两个测试方法,第一个是需要进行Token验证,第二个不需要

        [Authorize]
        [HttpGet, Route("GetWithIden")]
        public async Task<IActionResult> GetWithIden()
        {
            return Ok("get it");
        }

        [HttpGet, Route("GetWithoutIden")]
        public async Task<IActionResult> GetWithoutIden()
        {
            return Ok("get it");
        }

启动两个项目用postman访问api访问不带[Authorize]特性的方法直接返回结果  访问带[Authorize]特性的方法 报401

访问/connect/token方法获取Token

添加上认证信息  再次请求  请求成功

本文只写了IdentityServer4的基本使用方法,关于它的原理方面的知识就自行搜索其他博客或者视频学习,下一篇写IdentityServer4的进一步的使用

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 2
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值