如何通过传递用户名和密码从身份服务器获取访问令牌? [英] How to get access token from Identity Server by passing username and password?

查看:32
本文介绍了如何通过传递用户名和密码从身份服务器获取访问令牌?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我们正在使用身份服务器为我们的网络服务生成访问令牌.我们还添加了招摇.但是我们面临的问题是,通过使用 API 自动化的代码片段来生成访问令牌.是否有任何使用用户名和密码自动获取访问令牌的方法?

We are using identity server to generate access token for our web services. We have added swagger also. But the problem we faced is, to generate an access token by using a code snippet for API automation. Is there any automated way to get access token by using the username and password?

谢谢.

推荐答案

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

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:

这篇关于如何通过传递用户名和密码从身份服务器获取访问令牌?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆