首页 > 其他分享 >Duende.IdentityServer——快速开始

Duende.IdentityServer——快速开始

时间:2023-02-08 10:57:09浏览次数:40  
标签:api app 添加 new cs IdentityServer Duende 快速 鉴权

一、新建鉴权中心服务
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

标签:api,app,添加,new,cs,IdentityServer,Duende,快速,鉴权
From: https://www.cnblogs.com/wl-blog/p/17100947.html

相关文章

  • 快速傅里叶逆变换(IFFT)
    本文作者为JustinRochester。目录地址上一篇下一篇快速傅里叶逆变换(IFFT)......
  • 快速上手Java开发工具Eclipse之简易手册
    Eclipse下载,可以下载最新版本,文档是以2020-12R版本为例http://www.eclipse.org/downloads/ 下载Packages即可安装Eclipse 解压安装除了我的电脑----高级---环境变......
  • 阿里云产品-智能语音交互快速测评
    一,产品概述阿里云的智能语音交互产品提供语音识别、语音合成、自然语言理解等技术,实现“能听、会说、懂你”式的智能人机交互体验,适用于智能客服、质检、会议纪要、实时字......
  • Mabatis-Plus快速入门
    1. 在SpringBoot启动类中添加 @MapperScan 注解  2.编写实体类和接口  3.在控制层编写代码就可以直接用辣  useerMapper.xxxxx都有什么用法?......
  • 阿里云产品-图像搜索快速测评
    背景知识什么是云计算对于纯新人,首先我们需要了解下什么是云计算。所谓云计算,就是指通过互联网,以按需服务的形式提供计算资源。这样企业就无需自行采购、配置或管理资源,......
  • 快速实现一个简单阉割版的HashMap
    简单实现一个底层数据结构为数组+链表的HashMap,不考虑链表长度超过8个时变为红黑树的情况。1.示例图2.分析需求put数据时:key值hash后的索引处没有元素,需要创建链......
  • javaWeb01-使用idea快速搭建web项目
    本文主要讲述如何使用idea【这里的idea是2021年的】快速搭建web项目【没有使用maven创库】第一步:new->project第二步:选择java空项目第三步:选择路径以及......
  • 开发&运维如何对接口响应时间慢问题,快速定界排查?
    01问题背景自建机房,生产环境上某接口耗时超过2s,接口实现逻辑包含:数据库读写下游api调用数据统计开发本地自测,接口耗时却只有106ms。于是开发问运维:“生产环境的网络确定没......
  • LeaRun快速开发平台:自由搭建个性化门户
    门户是一个应用软件呈现给用户的第一印象,它作为应用框架,将各种应用系统、数据资源和互联网资源集成整合到一个信息管理平台上,再用统一界面呈现给用户,使企业可以快速建立企......
  • LeaRun快速开发平台:自由搭建个性化门户
    门户是一个应用软件呈现给用户的第一印象,它作为应用框架,将各种应用系统、数据资源和互联网资源集成整合到一个信息管理平台上,再用统一界面呈现给用户,使企业可以快速建立企业......