gpt4 book ai didi

c# - IdentityServer4 管理界面

转载 作者:行者123 更新时间:2023-11-30 15:14:39 37 4
gpt4 key购买 nike

我正在研究在 github 上开发的 IdentityServer4.AdminUI GitHub IdentityServer4.AdminUI

首先,我简单地创建了一个新用户并设置了密码,然后我创建了名为 Api_Name 的新 ApiResource。然后我创建了同名 Api_Name 的 IdentityResource。最后,我创建了名为 Api_Client 的新客户端并将客户端允许的范围设置为 Api_Name 并将允许的授权类型设置为 密码 最后将客户端密码设置为 < strong> secret

现在,我创建了新的 WebApi 项目(Core 2.1)并在启动类中使用它

public void ConfigureServices(IServiceCollection services) {
services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_1);

services.AddMvcCore().AddAuthorization().AddJsonFormatters();

services.AddAuthentication("Bearer")
.AddIdentityServerAuthentication(options => {
options.Authority = "http://localhost:5000"; //Identity Server URL
options.RequireHttpsMetadata = false; // make it false since we are not using https
options.ApiName = "Api_Name"; //api name which should be registered in IdentityServer
});
}

// This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
public void Configure(IApplicationBuilder app, IHostingEnvironment env) {
if (env.IsDevelopment()) {
app.UseDeveloperExceptionPage();
}
else {
app.UseHsts();
}

app.UseAuthentication();

app.UseHttpsRedirection();
app.UseMvc();
}

确定我在 WebApi Controller 中使用了 [Authorize] 属性

最后,测试。我创建了控制台应用程序并使用了这段代码

var identityServer = await DiscoveryClient.GetAsync("http://localhost:5000"); //discover the IdentityServer
if (identityServer.IsError) {
Console.Write(identityServer.Error);
return;
}

HttpClient client = new HttpClient();

var tokenResponse = await client.RequestPasswordTokenAsync(new PasswordTokenRequest {
Address = identityServer.TokenEndpoint,
ClientId = "Api_Client",
ClientSecret = "secret",

UserName = "Majd",
Password = "P@ssw0rd@123"
});

if (tokenResponse.IsError) {
Console.WriteLine(tokenResponse.Error);
return;
}

//Call the API

client.SetBearerToken(tokenResponse.AccessToken);

var response = await client.GetAsync("https://localhost:44368/api/values");
var response2 = await client.GetAsync("https://localhost:44368/api/values/1");
var content = await response.Content.ReadAsStringAsync();
Console.WriteLine(JArray.Parse(content));
Console.ReadKey();

问题是 response2 返回 UnAuthorized 401。为什么我会收到这个错误,因为我使用了从身份服务器接收到的访问 token

最佳答案

您还需要在 token 请求中添加请求的范围(即使您说允许客户端访问 Api_Name)。

    var tokenResponse = await client.RequestPasswordTokenAsync(new PasswordTokenRequest {
Address = identityServer.TokenEndpoint,
ClientId = "Api_Client",
ClientSecret = "secret",

UserName = "Majd",
Password = "P@ssw0rd@123",
Scope = "Api_Name"
});

在 IDS4 中, token 仅针对已请求的范围颁发,这与 IDS3 不同,在 IDS3 中您可以获得客户端允许的所有范围。所以就你的Api认证中间件而言,你的客户端没有被允许访问它,因为 token 不够。

关于c# - IdentityServer4 管理界面,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54182875/

37 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com