我想运行我的API测试用例,作为生成授权令牌的一部分。之前,应用程序端点要求将UserEmailId作为查询字符串传递,但是现在已对其进行了修改,以从授权令牌读取UserEmailId。我想修改我的GenerateAuthToken方法,以将EmailId包含在所生成的Auth令牌中。
我参考了其中的文档
https://docs.microsoft.com/en-us/azure/architecture/multitenant-identity/claims
我尝试使用UserAssertion传递UserEmailId,如下所示。
string authorityUrl = string.Format("https://login.microsoftonline.com/{0}", authority);
AuthenticationContext authContext = new AuthenticationContext(authorityUrl, false);
ClientCredential clientCredential = new ClientCredential(this.utils.GetClientId(), this.utils.GetClientSecret());
UserAssertion userAssertion = new UserAssertion("demoUser@tenant1.onmicrosoft.com");
AuthenticationResult authResult = authContext.AcquireTokenAsync(this.resource, clientCredential, userAssertion).Result;
但是我得到以下异常, AdalServiceException:AADSTS50027:JWT令牌无效或格式错误。
{
"aud": "1bbc71b1-56b3-404c-8961-76ed5f603fab",
"iss": "https://login.microsoftonline.com/e46fc01a-xxxx-xxxx-xxxx-xxxxxxxxxxxx/v2.0",
"iat": 1549957732,
"nbf": 1549957732,
"exp": 1549961632,
"aio": "42JgYGiUKZN6pn6WdbPPN9bLIW8ZAA==",
"azp": "1bbc71b1-56b3-404c-8961-76ed5f603fab",
"azpacr": "1",
"tid": "e46fc01a-xxxx-xxxx-xxxx-xxxxxxxxxxxx",
"uti": "rbpCCAb6TEuNRRaen_0DAA",
"ver": "2.0"
}
答案 0 :(得分:0)
这是我发现ROPC流程可用的极少数情况之一。 ADAL不会为此提供过载(主要是我想人们不会滥用此流程),因此您必须手动进行呼叫。 这是一个示例:
string tokenUrl = _authority + "oauth2/token";
var req = new HttpRequestMessage(HttpMethod.Post, tokenUrl)
{
Content = new FormUrlEncodedContent(new Dictionary<string, string>
{
["grant_type"] = "password",
["client_id"] = "your-clientid",
["client_secret"] = "your-clientsecret",
["resource"] = "resource-uri-or-client-id-of-api",
["username"] = "your-username",
["password"] = "your-password"
})
};
HttpResponseMessage res = await _client.SendAsync(req);
string json = await res.Content.ReadAsStringAsync();
AadTokenResponse tokenResponse = JsonConvert.DeserializeObject<AadTokenResponse>(json);
这里的响应类非常简单:
public class AadTokenResponse
{
[JsonProperty("access_token")]
public string AccessToken { get; set; }
}
请注意,只有在用户没有MFA,不需要通过ADFS进行身份验证等情况下,此方法才有效。 您不应将此流程用于生产租户,而只能用于测试租户中的测试用户。 本质上,您是在获取访问令牌以代表用户调用API,而不显示登录屏幕。 不应将其用于跳过应用程序中的登录屏幕。 但是,我发现它对于这种API测试非常有用。