【问题标题】:Generate bearer token client side C#生成不记名令牌客户端 C#
【发布时间】:2017-10-06 20:16:16
【问题描述】:

我正在使用部署在天蓝色环境中的 REST 服务。我想通过从单独的(控制台)应用程序调用各种 API 函数来运行一些集成测试。但是 REST api 使用不记名令牌身份验证。我是一个具有 azure 身份验证的菜鸟,所以我什至不知道这是否应该可行。

我已尝试使用找到的示例 here,但还没有成功。

无论如何,我有两个应用程序。一个是运行代码的控制台应用程序,另一个是我需要使用不记名令牌访问 API 调用的 Rest 服务。我将它们称为 ConsoleApp 和 RestService。

我运行的代码如下:

HttpClient client = new HttpClient();
string tenantId = "<Azure tenant id>";
string tokenEndpoint = $"https://login.microsoftonline.com/{tenantId}/oauth2/token";
string resourceUrl = "<RestService app id url>";
string clientId = "<azure id of the ConsoleApp>";
string userName = "derp@flerp.onmicrosoft.com";
string password = "somepassword";

string tokenEndpoint = $"https://login.microsoftonline.com/{tenantId}/oauth2/token";
var body = $"resource={resourceUrl}&client_id={clientId}&grant_type=password&username={userName}&password={password}";
var stringContent = new StringContent(body, Encoding.UTF8, "application/x-www-form-urlencoded");

var result=await client.PostAsync(tokenEndpoint, stringContent).ContinueWith<string>((response) =>
{
    return response.Result.Content.ReadAsStringAsync().Result;
});

JObject jobject = JObject.Parse(result);

我返回的 Json 消息:

错误:invalid_grant,error_description:AADSTS50105:已登录 用户未分配给应用程序“RestService”的角色 天蓝色”

这是什么意思,需要怎样做才能从中获得不记名令牌?

【问题讨论】:

    标签: c# rest oauth azure-active-directory


    【解决方案1】:

    请先检查您是否启用了控制台应用程序的User assignment required

    在您的 azure 广告刀片中,单击 Enterprise applications,在 All applications 刀片中搜索您的应用,单击 Properties

    如果启用,并且您的帐户未在您的应用程序中分配访问角色,那么您将收到错误消息。请尝试在您的应用中分配访问角色:

    在您的 azure 广告刀片中,单击 Enterprise applications,在 All applications 刀片中搜索您的控制台应用程序,单击 Users and groups,单击 Add User 按钮,选择您的帐户并分配角色(编辑用户并确保 select role 是不是None Selected):

    请告诉我是否有帮助。

    【讨论】:

    • 控制台应用关闭了用户分配,服务打开了它。我会看看我能不能用这些信息做点什么
    • 所以我添加了该服务的权限并设法解决了我的问题。非常感谢!
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2018-04-27
    • 2022-10-15
    • 2022-01-20
    • 1970-01-01
    • 2019-02-08
    • 1970-01-01
    • 2020-07-19
    相关资源
    最近更新 更多