【发布时间】:2018-01-17 04:47:37
【问题描述】:
我现在正在努力尝试从 Xamarin Forms Android 应用程序访问 azure 存储的 web api(它是默认的 web api,带有值控制器等)。我找到了大量关于如何实现这一点的文档,但我不想使用“传统方式”,如处理 AuthenticationContext\Authentication Result。该请求是在应用程序中使用自定义登录表单,而不是 Microsoft、Google 等提供的登录表单。
我的登录是这样的:
HttpClient client = new HttpClient();
var tokenEndpoint = "https://login.microsoftonline.com/testdir.onmicrosoft.com/oauth2/token";
var body = "resource=www.graph.microsoft.com&client_id=" + App.ClientId + "&grant_type=password&username=" + UsernameEntry.Text + "&password=" + PasswordEntry.Text + "";
var stringContent = new StringContent(body, Encoding.UTF8, "application/x-www-form-urlencoded");
var result = await client.PostAsync(tokenEndpoint, stringContent).ContinueWith<string>(response => response.Result.Content.ReadAsStringAsync().Result);
var jobject = JObject.Parse(result);
App.AccessToken = jobject["access_token"].Value<string>();
这就像一个魅力。我现在有了访问令牌,我可以使用它从 Azure AD 中检索用户或任何内容。
我想要一些类似的东西来从 web api 中检索数据。我希望在幕后进行登录,而不是通过提供 Microsoft 登录表单并提示用户登录。
我尝试过这样的事情:
tokenEndpoint = "https://login.microsoftonline.com/testdir.onmicrosoft.com/oauth2/authorize";
body = "client_id=xxxx&response_type=code&redirect_uri=https://testapi.azurewebsites.net/";
result = await client.PostAsync(tokenEndpoint, stringContent).ContinueWith<string>(response => response.Result.Content.ReadAsStringAsync().Result);
jobject = JObject.Parse(result);
但我总是收到一条错误消息,指出用户必须登录。 (我认为基本上它会尝试生成一个 Microsoft 登录表单,并且在成功尝试后它将直接使用访问 api 所需的授权代码)。
如果我能从一次调用中检索授权码,然后用它来查询 web api,那就太棒了。
以下是我发现的一些有用的问题,描述了类似的问题\场景,但我没有设法将所有信息包装成一段工作代码:
Getting Authorization has been denied for this request in Fiddler with Azure AD
Use OAuth2 for authentication against Azure AD to call WebAPI
Unable to use bearer token to access AAD-secure Web API
任何帮助将不胜感激。谢谢!
【问题讨论】:
标签: oauth-2.0 xamarin.android asp.net-web-api2 azure-active-directory