如何从Azure AD获取自定义属性

时间:2018-12-26 21:16:34

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

我仔细阅读了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
            }
        }
    );
}

1 个答案:

答案 0 :(得分: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

enter image description here

有关更多详细信息,您可以参考此article

此外,您可以调用以指定授权代码为below的资源URI。

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/"
);