我正在开发IdghtyServer4. working,它是在github GitHub IdghtyServer4.上开发的。
首先,我简单地创建了一个新用户并设置了密码,然后创建了名为ApiResource Api_Name的新用户。然后,我创建了同名为IdentityResource的Api_Name。最后,我创建了名为Api_Client的新客户端,并将客户端允许Scopes设置为Api_Name,并允许格兰特类型为密码,最后将客户端机密设置为 secret
现在,我创建了新的WebApi项目(Core2.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控制器中使用了授权属性。
终于,考试了。我创建了控制台应用程序并使用以下代码
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。那么我为什么会出现这个错误,因为我使用了来自身份服务器的接收访问令牌。
发布于 2019-01-14 21:03:13
您还需要在令牌请求中添加请求的作用域(即使您说客户端可以访问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身份验证中间件而言,您的客户端不允许访问它,因为令牌还不够。
https://stackoverflow.com/questions/54182875
复制相似问题