我通过带有 POST 请求的 url 连接/ token 从我的身份服务器 4 获取 token :
然后我将 access_token 键的值作为 header 复制/粘贴到我的 API GET 请求中:
mytokenstring
eyJhbGciOiJSUzI1NiIsImtpZCI6IkYxMDhCODA2NUNFMTRBOEEwOTZBODUyMkIxQUNBMkFDMTdEQjQwNEEiLCJ0eXAiOiJKV1QiLCJ4NXQiOiI4UWk0Qmx6aFNvb0phb1Vpc2F5aXJCZmJRRW8ifQ.eyJuYmYiOjE1MDg1OTU5MzIsImV4cCI6MTUwODU5OTUzMiwiaXNzIjoiaHR0cDovL2xvY2FsaG9zdDo2NTUzNSIsImF1ZCI6WyJodHRwOi8vbG9jYWxob3N0OjY1NTM1L3Jlc291cmNlcyIsInRlYWNoZXJzX3Rlc3RfcGxhbm5lciJdLCJjbGllbnRfaWQiOiJ0ZWFjaGVyc190ZXN0X3BsYW5uZXIiLCJzY29wZSI6WyJ0ZWFjaGVyc190ZXN0X3BsYW5uZXIiXX0.g2x31JcYrXyIavfxCu7UKY3kndznI_gYHJYCxl0dQn3u7l7vWo6qKr13XYMo6P1Lqtu68T2FEXL-5kyS0XwFClpdJE6m13-hfKZsd2QHBmOlgZ2ANwghXW4hfU5nWiwkUACwkP9wfDCULV3oQm5i49L5TQmUiiqcy0TTS2FDBdS5ymFBi1bCKnPh5ErsD8V_4eTqLzxv8CyVkPx2gPd6aBIf_2JNrjrMrrm69kghOHnktVG17KPQhppbIeJO8RP-URiJUJGXIY09yRGVF7YXtkFj-I5QOMvNIAWgUeqNYqH0cuQol9nglA4mtU1MfXtnRoEpRRzGViw7gxJ_-MFadA
授权:不记名mytokenstring
什么会导致来自身份服务器的 token 对我的 API 无效?
我在使用 POSTMAN 时遇到 401 错误
查看 kestrel 服务器的输出,我得到了这个:
Api> fail: Microsoft.AspNetCore.Server.IISIntegration.IISMiddleware[0]
Api> 'MS-ASPNETCORE-TOKEN' does not match the expected pairing token '52da49ee-6599-483a-b97a-15ced1603005', request rejected.
我做错了什么,那是什么配对标记 Guid?
API HttpGet:
标题:
授权持有人 eyJh...UntilTheEndOfTheString
IdentityServer 设置:
public void ConfigureServices(IServiceCollection services)
{
string certificateFilePath = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "certifiateselfsigned.pfx");
var certificate = new X509Certificate2(certificateFilePath, "test");
services.AddIdentityServer()
.AddSigningCredential(certificate)
.AddInMemoryApiResources(InMemoryConfiguration.GetApiResources())
.AddInMemoryClients(InMemoryConfiguration.GetClients())
.AddTestUsers(InMemoryConfiguration.GetUsers());
services.AddMvc();
}
更新
应用程序接口(interface)
public void ConfigureServices(IServiceCollection services)
{
services.AddAuthentication(options =>
{
options.DefaultScheme = JwtBearerDefaults.AuthenticationScheme;
})
.AddIdentityServerAuthentication(opt =>
{
opt.RequireHttpsMetadata = false;
opt.Authority = "http://localhost:65535"; // IdentityProvider => port running IDP on
opt.ApiName = "teachers_test_planner"; // IdentityProvider => api resource name
});
services.AddMvc();
}
身份提供者
public static class InMemoryConfiguration
{
public static List<TestUser> GetUsers()
{
return new List<TestUser>
{
new TestUser{ SubjectId = "6ed26693-b0a1-497e-aa14-7b880536920f", Username = "orders.tatum@gmail.com", Password = "mypassword",
Claims = new List<Claim>
{
new Claim("family_name", "tatum")
}
}
};
}
public static IEnumerable<ApiResource> GetApiResources()
{
return new List<ApiResource>
{
new ApiResource("teachers_test_planner", "Mein Testplaner")
};
}
public static IEnumerable<IdentityResource> GetIdentyResources()
{
return new List<IdentityResource>
{
new IdentityResources.OpenId(),
new IdentityResources.Profile(),
};
}
public static IEnumerable<Client> GetClients()
{
return new List<Client>
{
new Client
{
ClientId = "teachers_test_planner",
ClientSecrets = new[]{ new Secret("secret".Sha256()) },
AllowedGrantTypes = GrantTypes.ResourceOwnerPasswordAndClientCredentials,
AllowedScopes = new []{ "teachers_test_planner" }
}
};
}
}
更新 2
你可以在这里找到测试项目:
https://github.com/LisaTatum/IdentityServer4Test
更新 3
因为没有人问我如何将 http_post 发送到这里的连接/ token 端点,所以它是:
最佳答案
您只错过了 app.UseAuthentication()
.您必须将其添加到 Configure
中Api 上的方法 startup.cs
public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory)
{
loggerFactory.AddConsole(); // Configuration.GetSection("Logging"));
loggerFactory.AddDebug();
app.UseAuthentication();// The missing line
app.UseStaticFiles();
app.UseMvc();
}
我编写了以下控制台应用程序来测试调用您的 api
class Program
{
public static void Main(string[] args) => MainAsync().GetAwaiter().GetResult();
private static async Task MainAsync()
{
// discover endpoints from metadata
var disco = await DiscoveryClient.GetAsync("http://localhost:65535");
// request token
var tokenClient = new TokenClient(disco.TokenEndpoint, "teachers_test_client", "secret");
var tokenResponse = await tokenClient.RequestClientCredentialsAsync("teachers_test_planner");
if (tokenResponse.IsError)
{
Console.WriteLine(tokenResponse.Error);
return;
}
Console.WriteLine(tokenResponse.Json);
Console.WriteLine("\n\n");
// call api
var client = new HttpClient();
client.SetBearerToken(tokenResponse.AccessToken);
var response = await client.GetAsync("http://localhost:52129/api/values/1");
if (!response.IsSuccessStatusCode)
{
Console.WriteLine(response.StatusCode);
}
else
{
var content = await response.Content.ReadAsStringAsync();
Console.WriteLine(content);
}
Console.ReadKey();
}
}
你可以试试 postman ,我没试过
但是,我必须对您的项目 (github) 进行一些更改才能使其在我的机器上运行。而他们是
项目:IdentityProvider
-
mytestplanner.pfx
未设置为始终复制
项目:Api2
- 卸载 IdentityServer4 包。为什么客户端需要 IdentityServer4?
- 从
<TargetFramework>net462</TargetFramework>
更改目标框架至<TargetFramework>netcoreapp2.0</TargetFramework>
,(原因是我的机器上没有安装4.6.2)
无论如何,让我知道这是否适合你
更新
我已经添加了工作项目 here
关于c# - 来自身份服务器连接\ token 的 token 对我的 API 无效,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46695567/