+-
我正在研究在 github上开发的IdentityServer4.AdminUI
GitHub IdentityServer4.AdminUI
GitHub IdentityServer4.AdminUI
首先,我简单地创建了一个新用户并设置了密码,然后创建了名称为Api_Name的新ApiResource.然后,我创建了具有相同名称Api_Name的IdentityResource.最后,我创建了一个名称为Api_Client的新客户端,并将客户端的“允许范围”设置为Api_Name并将“允许的授予类型”设置为“密码”,最后将客户端密码设置为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控制器中使用了[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返回未经授权的401.所以为什么出现此错误,因为我使用了从身份服务器接收到的访问令牌
最佳答案
您还需要在令牌请求中添加一个请求的范围(即使您说允许客户端访问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中,仅针对已请求的范围颁发令牌,这与IDS3不同,在IDS3中,您将获得允许客户端的所有范围.因此,就您的Api身份验证中间件而言,由于令牌不足,因此不允许您的客户端访问它.
点击查看更多相关文章
转载注明原文:C#-IdentityServer4管理界面 - 乐贴网