且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

如何通过传递用户名和密码从身份服务器获取访问令牌?

更新时间:2022-04-20 23:27:28

我解决这个问题的方法是添加一个客户端凭据客户端,如果有配置的测试客户端机密,我只在测试环境中配置这个机密,但是显然不是在更高的环境中意味着客户端永远不会被添加到那里.

The way I've tackled this is to add a client credentials client if there is a configured test client secret, I configure this secret only in the test environments but obviously not in higher environments meaning the client never gets added there.

因此,无论是在您的 appsettings.{property_environment}.settings 还是通过环境变量设置客户端密钥,然后在您的 IdentityServer 配置中,您都可以添加:

So either in your appsettings.{appropriate_environment}.settings or via an environment variable set up a client secret, then in your IdentityServer config you can add:

//attempt to get the test client secret
var testClientSecret = configuration["TestClientSecret"];
if (!String.IsNullOrWhiteSpace(testClientSecret))
{
    clients.Add(new Client
    {
        ClientId = "MyTestClient",

        AllowedGrantTypes = GrantTypes.ClientCredentials,

        ClientSecrets =
        {
            new Secret(testClientSecret.Sha256())
        },

        AllowedScopes = { "MyApiScope", "MyOtherApiScope", "etc." }
    });
};

然后我有一个 Postman 测试集合,它首先发布到:

Then I have a Postman collection of tests which first POSTs to:

https://{{idp_base_url}}/connect/token

使用基本身份验证和测试客户端名称的用户名和密码作为客户端机密(其中 {{idp_base_url}} 是邮递员环境变量,包含适合环境的 IdentityServer 主机).

Using basic auth with username of the test client name and password as the client secret (where {{idp_base_url}} is a postman environment variable containing the IdentityServer host appropriate for the environment).

然后我运行了一些测试,同时将访问令牌存储到 API:

Then I run a few tests but also store the access token to the API:

//tests...
var tokenData = JSON.parse(responseBody);
//more tests...
postman.setEnvironmentVariable("cc_token", tokenData.access_token);

集合中的后续测试然后可以使用此令牌和使用上述 Postman 环境变量的不记名令牌 auth 标头运行您的 API 测试:

Subsequent tests in the collection can then run your API tests using this token with a bearer token auth header using the above Postman environment variable: