Duende.IdentityServer——快速开始

一、新建鉴权中心服务
1、安装Duende.IdentityServer模板
打开命令行工具,输入以下命令(若已安装,直接跳过)

dotnet new --install Duende.IdentityServer.Templates

2、新建 ROC.Identity.Center项目,框架选择.net 6
打开vs 2022 新建解决方案命名为ROC.Identity.Center,选择Duende IdentityServer Empty(Duende Software)

创建完成之后的项目结构

 

 

 

3、添加Duende.IdentityServer Nuget包

4、定义api scope
打开Config.cs文件,添加/修改以下代码

public static IEnumerable<ApiScope> ApiScopes =>
new ApiScope[]
{
new ApiScope(name:"api",displayName:"MyApi")
};

 

 

5、定义client
打开Config.cs文件,添加/修改以下代码

复制代码
public static IEnumerable<Client> Clients =>
    new Client[]
        {
            new Client{
                ClientId ="client",
                AllowedGrantTypes = GrantTypes.ClientCredentials,

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

                AllowedScopes = {"api"}
            }
        };
复制代码

 

 


6、配置IdentityServer
打开HostingExtensions.cs文件,添加以下代码

builder.Services.AddIdentityServer(options =>
{
options.EmitStaticAudienceClaim = true;
})
.AddInMemoryIdentityResources(Config.IdentityResources)
.AddInMemoryApiScopes(Config.ApiScopes)
.AddInMemoryClients(Config.Clients);

 

 

 

7、启动鉴权中心服务
打开服务根目录,运行dotnet run --urls="https://localhost:5001"

 

 

 

8、访问知识中心

 

 

 

二、新建测试webApi服务
1、新建ROC.WebApi.Demo解决方案,框架选择.net 6

 

 

 


2、添加Microsoft.AspNetCore.Authentication.JwtBearer Nuget包

 

 

 


3、新建HostingExtensions扩展类

复制代码
public static WebApplication ConfigureServices(this WebApplicationBuilder builder)
{
// Add services to the container.

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

return builder.Build();
}

public static WebApplication ConfigurePipeline(this WebApplication app)
{
// Configure the HTTP request pipeline.
if (app.Environment.IsDevelopment())
{
app.UseSwagger();
app.UseSwaggerUI();
}

app.UseHttpsRedirection();

app.MapControllers();


return app;
}
复制代码

 

4、添加Bearer认证
(1)修改HostingExtensions类的ConfigureServices方法,添加以下代码

复制代码
//添加鉴权认证
builder.Services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme)
.AddJwtBearer(JwtBearerDefaults.AuthenticationScheme, options =>
{
//鉴权中心服务地址
options.Authority = "https://localhost:5001";

options.TokenValidationParameters = new TokenValidationParameters
{
ValidateAudience = false
};
});
复制代码

 

(2)修改HostingExtensions类的ConfigurePipeline方法,添加以下代码

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


5、修改Program.cs

 

 

将默认创建的Program.cs中的代码修改为

复制代码
using ROC.WebApi.Demo;

var builder = WebApplication.CreateBuilder(args);

var app = builder
.ConfigureServices()
.ConfigurePipeline();

app.Run();
复制代码


6、添加api 控制器
新建DemoController.cs,并添加Authorize特性,代码如下

复制代码
[ApiController]
[Route("[controller]")]
[Authorize]
public class DemoController : ControllerBase
{
private readonly ILogger<DemoController> _logger;

public DemoController(ILogger<DemoController> logger)
{
_logger = logger;
}

[HttpGet(Name = "GetClaims")]
public IActionResult GetClaims()
{
return new JsonResult(from c in User.Claims select new { c.Type, c.Value });
}
}
复制代码


6、修改api启动url端口
打开Properties文件夹下的launchSettings.json文件,将applicationUrl的值修改为
https://localhost:6001(端口可以自定义)

 

 


7、启动api
打开项目根目录,运行dotnet run命令

 

 


8、使用Apifox(或postman)请求api
(1)直接请求:https://127.0.0.1:6001/Demo

 

 

返回401状态码,提示无权限,因为DemoController上添加了Authorize认证特性,所以访问控制器之前需要到鉴权中心校验用户携带的token是否有效及是否有权限访问该api,由于没有此次访问未携带token,显然直接访问是没有权限的,因此需要先到鉴权中心申请token。

(2)访问https://localhost:5001/connect/token ,申请一个token

 

 

如图需要添加POST请求的body部分,参数类型选择x-www-form-urlencoded,如下

grant_type:client_credentials
client_id:client
client_secret:secret
参数key固定,value对应鉴权中中定义的Client的值,对应关系如下

 

 

申请到的token信息如下

 

 

(3)携带token请求api

请求结果,返回200状态码,则说明请求及认证成功

三、新建测试客户端
1、新建ROC.Console.Client控制台项目,框架选择.net 6

2、添加IdentityModel Nuget包


3、获取发现文档
在Program.cs中添加以下代码

复制代码
using IdentityModel.Client;

HttpClient client = new HttpClient();

//获取发现文档
DiscoveryDocumentResponse disco = await client.GetDiscoveryDocumentAsync("https://localhost:5001");
if (disco.IsError)
{
Console.WriteLine(disco.Error);
return;
}
复制代码

 

4、获取token
在Program.cs中添加以下代码

复制代码
//申请token
TokenResponse tokenResponse = await client.RequestClientCredentialsTokenAsync(new ClientCredentialsTokenRequest
{
Address = disco.TokenEndpoint,
ClientId = "client", //与鉴权中心Config.cs中 client定义的相同
ClientSecret = "secret", //与鉴权中心Config.cs中 client定义的相同
Scope = "api" //与鉴权中心Config.cs中 ApiScope定义的相同
});
if (tokenResponse.IsError)
{
Console.WriteLine(tokenResponse.Error);
return;
}
Console.WriteLine(tokenResponse.AccessToken);
复制代码

 


5、请求webApi
在Program.cs中添加以下代码

复制代码
//请求api
HttpClient apiClient = new HttpClient();
apiClient.SetBearerToken(tokenResponse.AccessToken);

var response = await apiClient.GetAsync("https://localhost:6001/Demo");
if (!response.IsSuccessStatusCode)
{
Console.WriteLine(response.StatusCode);
}
else {
var doc = JsonDocument.Parse(await response.Content.ReadAsStringAsync()).RootElement;
Console.WriteLine(JsonSerializer.Serialize(doc, new JsonSerializerOptions { WriteIndented = true }));
}
复制代码

 

完整代码

 

 


6、运行

 

 

 

————————————————
版权声明:本文为CSDN博主「菜鸟爱飞不飞」的原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接及本声明。
原文链接:https://blog.csdn.net/weixin_39305029/article/details/123497673

posted @   dreamw  阅读(1184)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· 分享4款.NET开源、免费、实用的商城系统
· 全程不用写代码,我用AI程序员写了一个飞机大战
· MongoDB 8.0这个新功能碉堡了,比商业数据库还牛
· 白话解读 Dapr 1.15:你的「微服务管家」又秀新绝活了
· 上周热点回顾(2.24-3.2)
点击右上角即可分享
微信分享提示