创建IdentityServer4 (2)

该项目使用dotnet版本3.1 ,vs code创建

创建Web Api项目

创建命令

dotnet new webapi --name WebApi

修改./properties/launchSettings.json

"profiles": {
    "WebApi": {
      "commandName": "Project",
      "launchBrowser": true,
      "launchUrl": "weatherforecast",
      "applicationUrl": "http://localhost:5001",
      "environmentVariables": {
        "ASPNETCORE_ENVIRONMENT": "Development"
      }
    }
  }

运行下面命令安装

dotnet add package Microsoft.AspNetCore.Authentication.JwtBearer --version 3.1.0

在startup.cs文件的configureservices添加

services.AddAuthentication("Bearer")
    .AddJwtBearer("Bearer", options =>
    {
        options.RequireHttpsMetadata = false;
        options.Authority ="http://localhost:5000";
        options.Audience = "api1";
    });
                    

在startup.cs文件的configure添加

app.UseAuthentication(); 

在controller/WeatherForecastController.cs文件添加 [Authorize]

然后开启AuthServer、WebApi的程序

使用postman访问 http://localhost:5001/api/value 结果报401,没有认证

使用postman 访问 http://localhost:5000/connect/token 来获取 access_token

再将access_token加载 http://localhost:5001/api/value 中的Authorization进行请求

posted @ 2020-04-28 19:44  Cody&  阅读(212)  评论(0编辑  收藏  举报