我试图从身份服务器4使用密码从.net核心api控制器获取令牌。我收到错误invalid_client。
这是控制器。
[HttpGet]
public async Task<IActionResult> Get()
{
var client = new HttpClient();
var disco = await client.GetDiscoveryDocumentAsync("https://localhost:44321");
var tokenResponse = await client.RequestPasswordTokenAsync(new PasswordTokenRequest
{
Address = disco.TokenEndpoint,
ClientId = "htmlClient",
ClientSecret = "secretpassword",
UserName = "[email protected]",
Password = "password",
Scope = "WebApi.ReadAccess"
});
return Ok();
}
这是配置
public class Config
{
public static IEnumerable<ApiResource> GetApiResources()
{
return new List<ApiResource>
{
new ApiResource(
"WebApi.ReadAccess",
"WebApi API",
new List<string> {
JwtClaimTypes.Id,
JwtClaimTypes.Email,
JwtClaimTypes.Name,
JwtClaimTypes.GivenName,
JwtClaimTypes.FamilyName
}
),
new ApiResource("WebApi.FullAccess", "WebApi API")
};
}
public static IEnumerable<Client> GetClients()
{
return new[]
{
new Client
{
Enabled = true,
ClientName = "HTML Page Client",
ClientId = "htmlClient",
AllowedGrantTypes = GrantTypes.ResourceOwnerPassword,
ClientSecrets =
{
new Secret("secretpassword")
},
AllowedScopes = { "WebApi.ReadAccess" }
}
};
}
}
在configureServices中的startup.cs中
services.AddIdentityServer()
.AddInMemoryApiResources(Config.GetApiResources())
.AddInMemoryClients(Config.GetClients())
.AddProfileService<ProfileService>()
.AddDeveloperSigningCredential();
services.AddAuthentication(options =>
{
options.DefaultAuthenticateScheme =
JwtBearerDefaults.AuthenticationScheme;
options.DefaultChallengeScheme =
JwtBearerDefaults.AuthenticationScheme;
}).AddJwtBearer(o =>
{
o.Authority = "https://localhost:44321";
o.Audience = "WebApi.ReadAccess";
o.RequireHttpsMetadata = false;
});
在配置中我有app.UseIdentityServer();
public void Configure(IApplicationBuilder app, IHostingEnvironment env, BooksContext booksContext)
{
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
}
else
{
app.UseHsts();
}
app.UseHttpsRedirection();
app.UseIdentityServer();
app.UseMvc();
app.UseSwagger();
app.UseSwaggerUI(options =>
options.SwaggerEndpoint("/swagger/v2/swagger.json", "Book Chapter Service"));
app.UseDefaultFiles();
app.UseStaticFiles();
}
尝试将代码更改为以下内容。我已经给出了通用代码,您可以根据需要进行更改。
return new List<ApiResource>
{
new ApiResource
{
Name = "api",
DisplayName = "WebApi API",
Scopes =
{
new Scope("WebApi.ReadAccess", "Read write access to web api")
}
},
new ApiResource
{
Name = "api",
DisplayName = "WebApi API",
Scopes =
{
new Scope("WebApi.FullAccess", "Full access to web api")
}
}
}
和
o.Audience = "api";
原因是,您的o.Audience名称应与ApiResource.Name匹配,因为它表示您的权限和受众之间的映射。例如,在您的情况下,权威https://localhost:44321让观众称为“api”。 “api”也是您的ApiResource的名称,它授予创建访问令牌的权限。希望这可以帮助!