我正在关注this教程,尝试设置一个Web应用程序+ web api项目。
从我的WebApp - 我可以注册+登录,但当我尝试与我的WebAPI通信时 - 我收到了401.
此外 - 代码说使用result.AccessToken
但是我的是空的,但是result.IdToken
有一个值。
AuthenticationResult的值:
{
"AccessToken": null,
"UniqueId": "2330f777-f482-4e1d-860d-9bf93efb6d6a",
"ExpiresOn": "1970-01-01T00:00:00+00:00",
"TenantId": null,
"User": {
"DisplayableId": null,
"Name": null,
"IdentityProvider": "https://login.microsoftonline.com/930e788f-7b2a-47b1-b880-2370750dd255/v2.0/",
"Identifier": "123456789zctZjQ4Mi00ZTFkLTg2MGQtOWJmOTNlZmI2ZDZhLWIyY18xX3NpdXBpbg.OTMwZTc4OGYtN123456789IxLWI4ODAtMjM3MDc1MGRkMjU1"
},
"IdToken": "123456789iJKV1QiLCJhbGciOiJSUzI1NiIsImtpZCI6Ilg1ZVhrNHh5b2pORnVtMWtsMll0djhkbE5QNC1jNTdkTzZRR1RWQndhTmsifQ.123456789jE1Mjg0NTYyOTUsIm5iZiI6MTUyODQ1MjY5NSwidmVyIjoiMS4wIiwiaXNzIjoiaHR0cHM6Ly9sb2dpbi5taWNyb3NvZnRvbmxpbmUuY29tLzkzMGU3ODhmLTdiMmEtNDdiMS1iODgwLTIzNzA3NTBkZDI1NS92Mi4wLyIsInN1YiI6IjIzMzBmNzc3LWY0ODItNGUxZC04NjBkLTliZjkzZWZiNmQ2YSIsImF1ZCI6ImQyZmVhODBlLTliNmUtNGJkOC1iMDc5LTFhMjA5ZWY5ZjQ1MiIsIm5vbmNlIjoiNjM2NjQwNDk0NzU2NjM3NDI1Lk9XUTBOekUzTjJNdE16QXdNaTAwTnpnNUxXSTFOMlF0WVRoaU5tTmtaREl3WVdObU5HVTBNbUppWm1JdE5UTXpOUzAwTVRWbUxXSm1aalF0WmpZeE1qRm1NR0ptWVRRMiIsImlhdCI6MTUyODQ1MjY5NSwiYXV0aF90aW1lIjoxNTI4NDUyNjk1LCJvaWQiOiIyMzMwZjc3Ny1mNDgyLTRlMWQtODYwZC05YmY5M2VmYjZkNmEiLCJlbWFpbHMiOlsibXJ5YW5AY29uc3VtZXJkYXRhcHJvdGVjdGlvbi5vcmciXSwidGZwIjoiQjJDXzFfU2lVcEluIn0.PPbccK1yEvf2PeeCPSxe3rbhUuKhOmclBotIWw1kdDEaes-ljbzOWovac439g1nBiGwUlyOhx2wx6zjccQO1azPAl1TUqYQgWnmObU-CPRyosFF5k2XDLfSdmAtb9I_-8B_kb0WDXIGF3WeH8AXiVop1mqp-wzot93IwFxaovKrs6ZEbe5Yoef4dTeoGrYYXx1nYyCjWVNRs-oj2LpVA2mpq0ML7vziU09ukNGE2KhPv4nMmovpIXE53A0qiurU4SXotGkA4Okt4LGx_JMsLaqcfyOLI9wPPJipdkuLi_yN5QeLXMcp3w2E_BEujSdDRzLYBf7YXwlKVqQYvc_0l5A",
"Scopes": [
"https://MyTenant.onmicrosoft.com/demoapiread"
]
}
TaskWebApp:
public async Task<ActionResult> Index()
{
try
{
var scope = new string[] { Startup.ReadTasksScope };
string signedInUserID = ClaimsPrincipal.Current.FindFirst(ClaimTypes.NameIdentifier).Value;
TokenCache userTokenCache = new MSALSessionCache(signedInUserID, this.HttpContext).GetMsalCacheInstance();
ConfidentialClientApplication cca = new ConfidentialClientApplication(Startup.ClientId, Startup.Authority, Startup.RedirectUri, new ClientCredential(Startup.ClientSecret), userTokenCache, null);
var user = cca.Users.FirstOrDefault();
if (user == null)
{
throw new Exception("The User is NULL. Please clear your cookies and try again. Specifically delete cookies for 'login.microsoftonline.com'. See this GitHub issue for more details: https://github.com/Azure-Samples/active-directory-b2c-dotnet-webapp-and-webapi/issues/9");
}
AuthenticationResult result = await cca.AcquireTokenSilentAsync(scope, user, Startup.Authority, false);
HttpClient client = new HttpClient();
HttpRequestMessage request = new HttpRequestMessage(HttpMethod.Get, apiEndpoint);
// TODO: ACCESS TOKEN IS NULL
//request.Headers.Authorization = new AuthenticationHeaderValue("Bearer", result.AccessToken);
request.Headers.Authorization = new AuthenticationHeaderValue("Bearer", result.IdToken);
HttpResponseMessage response = await client.SendAsync(request);
// 401 Here
switch (response.StatusCode)
{
case HttpStatusCode.OK:
String responseString = await response.Content.ReadAsStringAsync();
JArray tasks = JArray.Parse(responseString);
ViewBag.Tasks = tasks;
return View();
case HttpStatusCode.Unauthorized:
return ErrorAction("Please sign in again. " + response.ReasonPhrase);
default:
return ErrorAction("Error. Status code = " + response.StatusCode);
}
}
catch (Exception ex)
{
return ErrorAction("Error reading to do list: " + ex.Message);
}
}
TaskWebApp Web.config
<appSettings>
<add key="webpages:Version" value="3.0.0.0" />
<add key="webpages:Enabled" value="false" />
<add key="ClientValidationEnabled" value="true" />
<add key="UnobtrusiveJavaScriptEnabled" value="true" />
<add key="ida:Tenant" value="MyTenant.onmicrosoft.com" />
<add key="ida:ClientId" value="<my-web-app-client-id>" />
<add key="ida:ClientSecret" value="<my-web-app-client-secret>" />
<add key="ida:AadInstance" value="https://login.microsoftonline.com/tfp/{0}/{1}/v2.0/.well-known/openid-configuration" />
<add key="ida:RedirectUri" value="https://localhost:44316/" />
<add key="ida:SignUpSignInPolicyId" value="b2c_1_SiUpIn" />
<add key="ida:EditProfilePolicyId" value="b2c_1_edit_profile" />
<add key="ida:ResetPasswordPolicyId" value="b2c_1_reset" />
<add key="api:TaskServiceUrl" value="https://localhost:44332" />
<!-- The following settings is used for requesting access tokens -->
<add key="api:ApiIdentifier" value="https://MyTenant.onmicrosoft.com/demoapi" />
<add key="api:ReadScope" value="read" />
<add key="api:WriteScope" value="write" />
</appSettings>
答案 0 :(得分:3)
我的错误是/
中缺少ApiIdentifier
:
<appSettings>
value="https://MyTenant.onmicrosoft.com/demoapi" />
</appSettings>
应该是:
<appSettings>
value="https://MyTenant.onmicrosoft.com/demoapi/" />
</appSettings>