简体   繁体   English

来自身份服务器连接\\令牌的令牌对我的API无效

[英]Token from identity server connection\token is not valid for my API

I am getting a token from my identityserver 4 via url connection/token with a POST request: 我通过POST请求通过URL连接/令牌从我的Identityserver 4获取令牌:

Then I copy/paste the value of the access_token key to my API GET request as a header: 然后,将access_token键的值复制/粘贴到我的API GET请求中作为标头:

mytokenstring mytokenstring

eyJhbGciOiJSUzI1NiIsImtpZCI6IkYxMDhCODA2NUNFMTRBOEEwOTZBODUyMkIxQUNBMkFDMTdEQjQwNEEiLCJ0eXAiOiJKV1QiLCJ4NXQiOiI4UWk0Qmx6aFNvb0phb1Vpc2F5aXJCZmJRRW8ifQ.eyJuYmYiOjE1MDg1OTU5MzIsImV4cCI6MTUwODU5OTUzMiwiaXNzIjoiaHR0cDovL2xvY2FsaG9zdDo2NTUzNSIsImF1ZCI6WyJodHRwOi8vbG9jYWxob3N0OjY1NTM1L3Jlc291cmNlcyIsInRlYWNoZXJzX3Rlc3RfcGxhbm5lciJdLCJjbGllbnRfaWQiOiJ0ZWFjaGVyc190ZXN0X3BsYW5uZXIiLCJzY29wZSI6WyJ0ZWFjaGVyc190ZXN0X3BsYW5uZXIiXX0.g2x31JcYrXyIavfxCu7UKY3kndznI_gYHJYCxl0dQn3u7l7vWo6qKr13XYMo6P1Lqtu68T2FEXL-5kyS0XwFClpdJE6m13-hfKZsd2QHBmOlgZ2ANwghXW4hfU5nWiwkUACwkP9wfDCULV3oQm5i49L5TQmUiiqcy0TTS2FDBdS5ymFBi1bCKnPh5ErsD8V_4eTqLzxv8CyVkPx2gPd6aBIf_2JNrjrMrrm69kghOHnktVG17KPQhppbIeJO8RP-URiJUJGXIY09yRGVF7YXtkFj-I5QOMvNIAWgUeqNYqH0cuQol9nglA4mtU1MfXtnRoEpRRzGViw7gxJ_-MFadA eyJhbGciOiJSUzI1NiIsImtpZCI6IkYxMDhCODA2NUNFMTRBOEEwOTZBODUyMkIxQUNBMkFDMTdEQjQwNEEiLCJ0eXAiOiJKV1QiLCJ4NXQiOiI4UWk0Qmx6aFNvb0phb1Vpc2F5aXJCZmJRRW8ifQ.eyJuYmYiOjE1MDg1OTU5MzIsImV4cCI6MTUwODU5OTUzMiwiaXNzIjoiaHR0cDovL2xvY2FsaG9zdDo2NTUzNSIsImF1ZCI6WyJodHRwOi8vbG9jYWxob3N0OjY1NTM1L3Jlc291cmNlcyIsInRlYWNoZXJzX3Rlc3RfcGxhbm5lciJdLCJjbGllbnRfaWQiOiJ0ZWFjaGVyc190ZXN0X3BsYW5uZXIiLCJzY29wZSI6WyJ0ZWFjaGVyc190ZXN0X3BsYW5uZXIiXX0.g2x31JcYrXyIavfxCu7UKY3kndznI_gYHJYCxl0dQn3u7l7vWo6qKr13XYMo6P1Lqtu68T2FEXL-5kyS0XwFClpdJE6m13-hfKZsd2QHBmOlgZ2ANwghXW4hfU5nWiwkUACwkP9wfDCULV3oQm5i49L5TQmUiiqcy0TTS2FDBdS5ymFBi1bCKnPh5ErsD8V_4eTqLzxv8CyVkPx2gPd6aBIf_2JNrjrMrrm69kghOHnktVG17KPQhppbIeJO8RP-URiJUJGXIY09yRGVF7YXtkFj-I5QOMvNIAWgUeqNYqH0cuQol9nglA4mtU1MfXtnRoEpRRzGViw7gxJ_-MFadA

Authorization: Bearer mytokenstring 授权:不记名mytokenstring

What can cause that the token from the identity server is not valid for my API? 是什么导致身份服务器的令牌对我的API无效?

I get a 401 error with POSTMAN 我收到POSTMAN的401错误

Looking into the output of the kestrel server I get this: 查看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.

What do I wrong and what pairing token Guid is that? 我错了什么,那是什么配对令牌Guid?

API HttpGet: API HttpGet:

header: 标头:

Authorization Bearer eyJh...UntilTheEndOfTheString 授权承载eyJh ... UntilTheEndOfTheString

IdentityServer setup: 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();
}

UPDATE 更新

Api 阿皮

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();
}

IdentityProvider 身份提供者

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" }
        }
    };
    }
}

UPDATE 2 更新2

You can find the test project here: 您可以在此处找到测试项目:

https://github.com/LisaTatum/IdentityServer4Test https://github.com/LisaTatum/IdentityServer4Test

UPDATE 3 更新3

As nobody asked how I do the http_post to the connect/token endpoint here it is: 正如没有人问我如何在连接/令牌端点上执行http_post一样,它是:

在此处输入图片说明

All you missed is app.UseAuthentication() . 您只错过了app.UseAuthentication() You have to add this into Configure method on Api startup.cs 您必须将此添加到Api startup.cs Configure方法中

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();
}

I write the following consle app to test calling your api 我编写以下consle应用程序来测试调用您的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();
    }
}

You could try on the postman, i haven't tried that 你可以试穿邮递员,我还没试过

However, I had to change few more things on your project(github) to make it run on my machine. 但是,我不得不在您的项目(github)上更改几件事,以使其在我的机器上运行。 And they are 他们是

Project: IdentityProvider 项目: IdentityProvider

  • mytestplanner.pfx was not set to Copy Always mytestplanner.pfx未设置为“始终复制”

Project: Api2 项目: Api2

  • uninstall IdentityServer4 package. 卸载IdentityServer4软件包。 Why do you need IdentityServer4 on the client? 为什么在客户端上需要IdentityServer4?
  • Change target framework from <TargetFramework>net462</TargetFramework> to <TargetFramework>netcoreapp2.0</TargetFramework> , (the reason is that 4.6.2 is not installed on my machine) 将目标框架从<TargetFramework>net462</TargetFramework>更改为<TargetFramework>netcoreapp2.0</TargetFramework> (原因是我的计算机上未安装4.6.2)

Anyway, let me know if this works for you 无论如何,请告诉我这是否适合您

Update 更新资料

I have added the working project here 在这里添加了工作项目

This can happen if you request a "wrong" token. 如果您请求“错误”令牌,则可能会发生这种情况。

Assuming you have Client C calling API A, "POST GetToken" would look something like this: 假设您有客户端C调用API A,则“ POST GetToken”将如下所示:

  • ClientId: C.ClientId 客户编号:C.ClientId
  • Resource: A.Resource ("audience") 资源:A.Resource(“受众”)

Your token suggests that you are doing the following request 您的令牌表明您正在执行以下请求

Is " http://localhost:65535/resources " the audience of your target API? http:// localhost:65535 / resources ”是您的目标API的受众吗?

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM