[英]Storing access token from Identity Server in NET Core web application
[英]How to get access token from Identity Server by passing username and password?
我们正在使用身份服务器为我们的网络服务生成访问令牌。 我们也添加了 swagger。 但我们面临的问题是,通过使用 API 自动化的代码片段来生成访问令牌。 有没有使用用户名和密码自动获取访问令牌的方法?
谢谢你。
我解决这个问题的方法是添加一个客户端凭证客户端,如果有配置的测试客户端密码,我只在测试环境中配置这个密码,但显然不是在更高的环境中,这意味着客户端永远不会被添加到那里。
因此,无论是在您的 appsettings.{appropriate_environment}.settings 中还是通过环境变量设置客户端密码,然后在您的 IdentityServer 配置中您可以添加:
//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." }
});
};
然后我有一个邮递员测试集合,首先发布到:
https://{{idp_base_url}}/connect/token
使用带有测试客户端名称的用户名和密码的基本身份验证作为客户端密码(其中 {{idp_base_url}} 是包含适合环境的 IdentityServer 主机的邮递员环境变量)。
然后我运行一些测试,但也将访问令牌存储到 API:
//tests...
var tokenData = JSON.parse(responseBody);
//more tests...
postman.setEnvironmentVariable("cc_token", tokenData.access_token);
然后集合中的后续测试可以使用此令牌和使用上述 Postman 环境变量的不记名令牌身份验证标头运行您的 API 测试:
首先声明一个名为 Token 的类。
public class Token
{
[JsonProperty("access_token")]
public string AccessToken { get; set; }
[JsonProperty("token_type")]
public string TokenType { get; set; }
[JsonProperty("expires_in")]
public int ExpiresIn { get; set; }
[JsonProperty("userName")]
public string Username { get; set; }
[JsonProperty(".issued")]
public string IssuedAt { get; set; }
[JsonProperty(".expires")]
public string ExpiresAt { get; set; }
}
在 Postman 中,我们在 POST 方法中使用用户名、密码和 grant_type 从 baseURl/token uri 生成 access_token。 要知道您应该使用什么 url,请查看 App_Start 文件夹中的 Startup.Auth.cs 文件。
OAuthOptions = new OAuthAuthorizationServerOptions
{
TokenEndpointPath = new PathString("/Token"),
.....
}
适当的 URL 由 PathString() 构造函数中的字符串确定。
知道要调用什么 url 后,现在要获取访问令牌,请考虑以下代码。
var keyValues = new List<KeyValuePair<string, string>>
{
new KeyValuePair<string, string>("username", username),
new KeyValuePair<string, string>("password",password),
new KeyValuePair<string, string>("grant_type", "password")
};
var request = new HttpRequestMessage(HttpMethod.Post, "baseUrl/Token");
request.Content = new FormUrlEncodedContent(keyValues);
var client = new HttpClient();
var response = await client.SendAsync(request);
var content = await response.Content.ReadAsStringAsync();
var accessTokenVar = JsonConvert.DeserializeObject<AuthenticationToken>(content);
现在可以使用 accessTokenVar 访问访问令牌。
另一种方法是使用IdentityModel
NuGet 获取令牌。 例子:
var client = new HttpClient();
var tokenResponse = await client.RequestClientCredentialsTokenAsync(new ClientCredentialsTokenRequest
{
Address = $"{IdentityServerUrl}/connect/token",
ClientId = "THE_CLIENT_ID",
ClientSecret = IdentityServerPass,
Scope = "api.read"
}).ConfigureAwait(false);
tokenResponse.HttpResponse.EnsureSuccessStatusCode();
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.