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

时间:2017-10-11 18:53:27

标签: c# oauth-2.0 openid identityserver4

我通过url connection / token通过POST请求从我的身份服务器4获取一个令牌:

然后我将access_token键的值复制/粘贴到我的API GET请求中作为标题:

mytokenstring

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

授权:持票人 mytokenstring

什么可能导致身份服务器的令牌对我的API无效?

我使用 POSTMAN

收到401错误

查看红宝石服务器的输出我得到了:

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 ......直到TheEndOfTheString

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

更新

阿比

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

更新2

您可以在此处找到测试项目:

https://github.com/LisaTatum/IdentityServer4Test

更新3

由于没有人问我如何对连接/令牌端点执行http_post,所以它是:

enter image description here

2 个答案:

答案 0 :(得分:2)

你错过的只有app.UseAuthentication()。您必须将此添加到Api Configure

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

你可以试试邮递员,我没试过那个

但是,我必须在你的项目(github)上更改一些东西才能让它在我的机器上运行。他们是

项目:IdentityProvider

  • mytestplanner.pfx未设置为始终复制

项目:Api2

  • 卸载IdentityServer4包。为什么在客户端上需要IdentityServer4?
  • 将目标框架从<TargetFramework>net462</TargetFramework>更改为<TargetFramework>netcoreapp2.0</TargetFramework>,(原因是我的计算机上未安装4.6.2)

无论如何,请告诉我这是否适合您

更新

我添加了工作项目here

答案 1 :(得分:0)

如果您要求“错误”,可能会发生这种情况。令牌。

假设您有客户端C调用API A,&#34; POST GetToken&#34;看起来像这样:

  • ClientId:C.ClientId
  • 资源:A.Resource(&#34;观众&#34;)

您的令牌表明您正在执行以下请求

&#34; http://localhost:65535/resources&#34;您的目标API的受众群体?