【发布时间】:2019-06-08 12:31:10
【问题描述】:
我正在研究在 github 上开发的 IdentityServer4.AdminUI GitHub IdentityServer4.AdminUI
首先我简单地创建了一个新用户并设置了密码,然后我创建了名为 Api_Name 的新 ApiResource。然后我创建了具有相同名称 Api_Name 的 IdentityResource。最后,我创建了名为 Api_Client 的新客户端,并将客户端允许的范围设置为 Api_Name,将允许的授权类型设置为 Password,最后将客户端密码设置为 秘密
现在,我创建了新的 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 返回 UnAuthorized 401。所以为什么我收到这个错误,因为我使用了从身份服务器接收到的访问令牌
【问题讨论】:
-
response..的返回结果呢??
-
响应从 api 返回值,但未授权。我说它是为了确保一切正常
-
您是否尝试将用户添加到角色并授予对该角色的 API 访问权限...
标签: c# security access-token identityserver4