Identity Server 4 从入门到落地(四)—— 创建Web Api

前面的部分:
Identity Server 4 从入门到落地(一)—— 从IdentityServer4.Admin开始
Identity Server 4 从入门到落地(二)—— 理解授权码模式
Identity Server 4 从入门到落地(三)—— 创建Web客户端
认证服务和管理的github地址: https://github.com/zhenl/IDS4Admin
客户端及web api示例代码的github地址:https://github.com/zhenl/IDS4ClientDemo

前面我们创建了使用Identity Server 4进行认证的客户端,现在创建受Identity Server 4认证服务保护的Web Api。在Visual Studio 2022中使用模板创建Asp.Net Core Web Api项目,不增加任何业务代码,就使用缺省的示例。创建完成后,引入程序包microsoft.aspnetcore.authentication.jwtbearer,然后修改lanuchSettings.json,将项目设置为自启动:

{
  "profiles": {
    "IDS4WebApi": {
      "commandName": "Project",
      "dotnetRunMessages": true,
      "launchBrowser": true,
      "launchUrl": "swagger",
      "applicationUrl": "http://localhost:5153",
      "environmentVariables": {
        "ASPNETCORE_ENVIRONMENT": "Development"
      }
    }
  }
}

接下来增加认证相关的代码,这里使用的是.Net 6的结构,与传统风格略有不同:

using Microsoft.IdentityModel.Tokens;

var builder = WebApplication.CreateBuilder(args);

// Add services to the container.
//增加代码
builder.Services.AddAuthentication("Bearer")
               .AddJwtBearer("Bearer", options =>
               {
                   options.Authority = "http://localhost:4010";
                   options.RequireHttpsMetadata = false;
                   options.TokenValidationParameters = new TokenValidationParameters
                   {
                       ValidateAudience = false
                   };
               });

// adds an authorization policy to make sure the token is for scope 'api1'
builder.Services.AddAuthorization(options =>
{
    options.AddPolicy("ApiScope", policy =>
    {
        policy.RequireAuthenticatedUser();
        policy.RequireClaim("scope", "myapi");
    });
});
//增加完成

builder.Services.AddControllers();
// Learn more about configuring Swagger/OpenAPI at https://aka.ms/aspnetcore/swashbuckle
builder.Services.AddEndpointsApiExplorer();
builder.Services.AddSwaggerGen();

var app = builder.Build();

// Configure the HTTP request pipeline.
if (app.Environment.IsDevelopment())
{
    app.UseSwagger();
    app.UseSwaggerUI();
}

app.UseHttpsRedirection();
app.UseAuthentication(); //增加代码
app.UseAuthorization();

app.MapControllers()
    .RequireAuthorization("ApiScope");//增加代码

app.Run();

增加的代码用注释进行了标注。需要注意的几个部分是:

  • 认证服务器的地址不能写错
  • 定义的ApiScope的名称,需要在认证服务器进行配置,这里是myapi
  • 由于认证服务器使用非SSL协议,需要增加选项options.RequireHttpsMetadata = false;

下面在认证服务器中增加Api资源和Api Scope:


到此,受保护的Web Api就完成了。可以为客户端授权访问myapi。下面我们改造前面的客户端来访问这个web api。

首先在前面的客户端项目中增加IdentityModel程序包,然后在可访问的scope中增加myapi:

        options.Scope.Add("myapi");

然后在HomeController中增加访问Web Api的代码:

        public async Task<IActionResult> GetApiData()
        {
            var auth = await HttpContext.AuthenticateAsync();

            var token = auth.Properties.Items[".Token.access_token"];

            var apiClient = new HttpClient();
            apiClient.SetBearerToken(token);

            var response = await apiClient.GetAsync("http://localhost:5153/WeatherForecast");
            string result;
            if (!response.IsSuccessStatusCode)
            {
                result = response.StatusCode.ToString();
            }
            else
            {
                var content = await response.Content.ReadAsStringAsync();
                result = content;// JArray.Parse(content);
            }
            return Json(result);
        }

不要忘了,在认证服务的客户端定义中,为客户端增加myapi的访问权限:

如果从Visual Studio 中运行,需要同时启动客户端和Web Api,可以将解决方案设置为多项目启动:

登录后访问https://localhost:7002/Home/GetApiData,结果如下:

以上示例的相关代码可以从github中获取: https://github.com/zhenl/IDS4ClientDemo

posted @ 2021-12-03 16:18  寻找无名的特质  阅读(1576)  评论(0编辑  收藏  举报