美文网首页
Identity Server 4 学习(六)创建受认证保护的A

Identity Server 4 学习(六)创建受认证保护的A

作者: 寻找无名的特质 | 来源:发表于2021-11-11 08:31 被阅读0次

现在我们来创建一个Web Api并使用认证服务器负责对API进行认证。我们使用模板创建一个Asp.Net Core Web Api项目,我们不增加任何业务代码,就使用缺省的示例。创建完成后,修改lanuchSettings.json,将项目设置为自启动:

{
  "profiles": {
    "MyWebApi": {
      "commandName": "Project",
      "dotnetRunMessages": "true",
      "launchBrowser": true,
      "launchUrl": "weatherforecast",
      "applicationUrl": "http://localhost:5007",
      "environmentVariables": {
        "ASPNETCORE_ENVIRONMENT": "Development"
      }
    }
  }
}

运行项目,可以在浏览器上看到生成的模拟数据。现在增加认证相关的代码,首先引用包microsoft.aspnetcore.authentication.jwtbearer,然后修改Startup.cs:

 // accepts any access token issued by identity server
            services.AddAuthentication("Bearer")
                .AddJwtBearer("Bearer", options =>
                {
                    options.Authority = "https://localhost:44310";

                    options.TokenValidationParameters = new TokenValidationParameters
                    {
                        ValidateAudience = false
                    };
                });

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

这里增加了认证服务器的地址,还有允许访问的scope,我们设置为myapi。
修改Configure:

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

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

Api应就创建完成了。还需要在认证服务器进行配置,分别增加名称为myapi的Api Scope 和Api Resource。这样其它应用访问这个Web Api就需要进行过认证。

相关文章

网友评论

      本文标题:Identity Server 4 学习(六)创建受认证保护的A

      本文链接:https://www.haomeiwen.com/subject/alerzltx.html