【问题标题】:How to get custom properties from Azure AD如何从 Azure AD 获取自定义属性
【发布时间】:2018-12-27 23:10:22
【问题描述】:

我通过 Microsoft 提供的本教程将 Azure Ad 集成到我的 Web 应用程序中进行身份验证。 https://docs.microsoft.com/en-us/azure/active-directory/develop/quickstart-v1-dotnet-webapi

代码按预期工作。我运行该程序,它会提示用户输入他们的 Microsoft 登录凭据,如果有效,他们将被重定向到主页。

但是,我只能访问有关用户的基本信息,例如 GivenName 和 SurName。我在 Azure 门户中创建了名为“extension_e3f9d0...”的扩展属性

问题是我不知道如何在用户登录后访问这些属性。当我在 Postman 中调用 API 时,我能够检索这些自定义属性,如下所示:

https://graph.microsoft.com/v1.0/users/[user@whatever]?$select=extension_e3f9d0...

我尝试在 c# 中进行此调用,但我不知道一旦用户登录后如何获取 accessToken,这是请求标头中所必需的

async static void GetRequest(string url)
    {
        Summary summary = new Summary();
        using(HttpClient client = new HttpClient())
        {
            client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
            client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", How do I get the user's accesstoken here?);
            using (HttpResponseMessage response = await client.GetAsync("https://graph.microsoft.com/v1.0/users/[user@whatever]?$select=extension_e3f9d0"))
            {
                using(HttpContent content = response.Content)
                {
                    string myContent = await content.ReadAsStringAsync();
                    System.Diagnostics.Debug.WriteLine("CONTENT " + myContent);
                }
            }
        }
    }

用户登录代码

// The Client ID (a.k.a. Application ID) is used by the application to uniquely identify itself to Azure AD
string clientId = System.Configuration.ConfigurationManager.AppSettings["ClientId"];

// RedirectUri is the URL where the user will be redirected to after they sign in
string redirectUrl = System.Configuration.ConfigurationManager.AppSettings["redirectUrl"];

// Tenant is the tenant ID (e.g. contoso.onmicrosoft.com, or 'common' for multi-tenant)
static string tenant = System.Configuration.ConfigurationManager.AppSettings["Tenant"];

// Authority is the URL for authority, composed by Azure Active Directory endpoint and the tenant name (e.g. https://login.microsoftonline.com/contoso.onmicrosoft.com)
string authority = String.Format(System.Globalization.CultureInfo.InvariantCulture, System.Configuration.ConfigurationManager.AppSettings["Authority"], tenant);

/// <summary>
/// Configure OWIN to use OpenIdConnect 
/// </summary>
/// <param name="app"></param>
public void Configuration(IAppBuilder app)
{
    app.SetDefaultSignInAsAuthenticationType(CookieAuthenticationDefaults.AuthenticationType);

    app.UseCookieAuthentication(new CookieAuthenticationOptions());
    app.UseOpenIdConnectAuthentication(
        new OpenIdConnectAuthenticationOptions
        {
            // Sets the ClientId, authority, RedirectUri as obtained from web.config
            ClientId = clientId,
            Authority = authority,
            RedirectUri = redirectUrl,

            // PostLogoutRedirectUri is the page that users will be redirected to after sign-out. In this case, it is using the home page
            PostLogoutRedirectUri = redirectUrl,

            //Scope is the requested scope: OpenIdConnectScopes.OpenIdProfileis equivalent to the string 'openid profile': in the consent screen, this will result in 'Sign you in and read your profile'
            Scope = OpenIdConnectScope.OpenIdProfile,

            // ResponseType is set to request the id_token - which contains basic information about the signed-in user
            ResponseType = OpenIdConnectResponseType.IdToken,

            // ValidateIssuer set to false to allow work accounts from any organization to sign in to your application
            // To only allow users from a single organizations, set ValidateIssuer to true and 'tenant' setting in web.config to the tenant name or Id (example: contoso.onmicrosoft.com)
            // To allow users from only a list of specific organizations, set ValidateIssuer to true and use ValidIssuers parameter
            TokenValidationParameters = new TokenValidationParameters()
            {
                ValidateIssuer = false
            },

            // OpenIdConnectAuthenticationNotifications configures OWIN to send notification of failed authentications to OnAuthenticationFailed method
            Notifications = new OpenIdConnectAuthenticationNotifications
            {
                AuthenticationFailed = OnAuthenticationFailed
            }
        }
    );
}

【问题讨论】:

    标签: c# asp.net azure-active-directory


    【解决方案1】:

    要使用 Microsoft Graph 代表用户读取和写入资源,您的应用必须从 Azure AD 获取访问令牌,并将该令牌附加到它发送到 Microsoft Graph 的请求中。

    使用 OAuth 2.0 授权代码授权流从 Azure AD v2.0 端点获取访问令牌所需的基本步骤是:

    1.向 Azure AD 注册您的应用程序。

    2.获得授权。

    对于 Azure AD v2.0 终结点,使用 scope 参数请求权限。在此示例中,请求的 Microsoft Graph 权限适用于 User.ReadMail.Read,这将允许应用读取登录用户的个人资料和邮件。

    https://login.microsoftonline.com/{tenant}/oauth2/v2.0/authorize?
    client_id=6731de76-14a6-49ae-97bc-6eba6914391e
    &response_type=code
    &redirect_uri=http%3A%2F%2Flocalhost%2Fmyapp%2F
    &scope=user.read%20mail.read
    

    3.获取访问令牌。

    您的应用使用在上一步中收到的授权代码通过向 /token 端点发送 POST 请求来请求访问令牌。

    4.使用访问令牌调用 Microsoft Graph。

    对于登录用户,我使用https://graph.microsoft.com/v1.0/me?$select=surname

    更多详情可以参考这个article

    另外,您可以调用以指定资源 URI,授权码为 below

    var authContext = new AuthenticationContext(authorityString);
    var result = await authContext.AcquireTokenByAuthorizationCodeAsync
    (
        authorizationCode,
        redirectUri, // eg http://localhost:56950/
        clientCredential, // Application ID, application secret
        "https://graph.microsoft.com/"
    );
    

    【讨论】:

    • 我已经编辑了我的问题以包含我用来登录用户的代码。由于用户已成功签名,不应该已经为该用户生成访问令牌吗?我只是不明白如何提取该访问令牌以在我对图表的获取请求中使用。
    猜你喜欢
    • 1970-01-01
    • 2019-12-27
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多