Asp.Net Core服务集成Identityserver4认证

  • Post author:
  • Post category:其他





前言


上一篇文章创建成功了IdentityServer4资源服务(

Asp.NET Core集成Identityserver4

),并集成了两种模式(客户端模式和密码模式),这一篇讲客户端请求资源进行认证。代码框架环境Asp.net Core 3.1



提示:以下是本篇文章正文内容,下面案例可供参考



使用步骤



1.创建一个webapi项目,命名OrderConsumer

在这里插入图片描述



2.引入IdentityServer4.AccessTokenValidation库 版本3.0.1

在这里插入图片描述



3.控制器修改


代码如下(示例):

 [HttpGet]
        [Authorize]
        [Route("Get")]
        public string Get()
        {
            StringBuilder sb = new StringBuilder();
            foreach (var item in User.Claims)
            {
               sb.AppendFormat("Type:"+item.Type + "======Value:" + item.Value.ToString()+ "\r\n");
            }
            string str = (Request.HttpContext.Connection.LocalIpAddress.MapToIPv4().ToString() + ":" + Request.HttpContext.Connection.LocalPort) + DateTime.Now;
            return "我是订单消费者==="+str+ "\r\n"+ sb.ToString();
        }



4.Startup类修改


代码如下(示例):

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

        public IConfiguration Configuration { get; }

        // This method gets called by the runtime. Use this method to add services to the container.
        public void ConfigureServices(IServiceCollection services)
        {
            services.AddControllers();
            //配置认证
            services.AddAuthentication("Bearer")
                .AddJwtBearer("Bearer", options =>
                {
                    //认证服务器地址
                    options.Authority = "http://localhost:5000"; //
                    //获取或设置元数据地址或颁发机构是否需要HTTPS。这个默认值为true。只有在开发环境中才应禁用此功能。
                    options.RequireHttpsMetadata = false;
                    options.TokenValidationParameters = new Microsoft.IdentityModel.Tokens.TokenValidationParameters
                    {
                        ValidateIssuer = true,
                        //将用于对照令牌的访问群体进行检查的访问群体,就是
                        //scope
                        ValidAudiences = new List<string>
                    {
                        "api",
                        "secretapi"
                    }
                    };
              
            });
        }

        // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
        public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
        {
            if (env.IsDevelopment())
            {
                app.UseDeveloperExceptionPage();
            }

            app.UseRouting();

            app.UseAuthentication();//认证
            app.UseAuthorization();//授权

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



5.通过postman进行测试

	请求地址:http://localhost:5000/connect/token
	注:参数传递,只需在

在这里插入图片描述

一:测试客户端模式

1.获取token

参数:

grant_type=client_credentials

client_id=client

client_secret=secret

Scope=api

在这里插入图片描述

2.带token值请求服务(http://localhost:5001/weatherforecast/get)

在这里插入图片描述

3.输出效果

在这里插入图片描述

二:测试密码模式

参数:

grant_type=password

client_id=client

client_secret=secret

Scope=api offline_access (必须配置offline_access,才能获取到refresh_token)

Username=apiUser

Password=apiUserPassword

	1.获取token

在这里插入图片描述

2.带token值请求服务(http://localhost:5001/weatherforecast/get)

在这里插入图片描述

3.输出效果

在这里插入图片描述



版权声明:本文为qq_36819973原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。