Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/csharp/257.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/blackberry/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C# 如何从Azure AD获取自定义属性_C#_Asp.net_Azure Active Directory - Fatal编程技术网

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

C# 如何从Azure AD获取自定义属性,c#,asp.net,azure-active-directory,C#,Asp.net,Azure Active Directory,我阅读了Microsoft提供的本教程,将Azure Ad集成到我的web应用程序中进行身份验证。 代码按预期工作。我运行这个程序,它会提示用户输入他们的Microsoft登录凭据,如果有效,他们会被重定向到主页 但是,我只能访问用户的基本信息,如GivenName和姓氏。我在Azure门户中创建了名为“extension\u e3f9d0…”的扩展属性 问题是我不知道用户登录后如何访问属性。我可以在Postman中调用API时检索这些自定义属性,如下所示: ?$select=扩展名\u e3

我阅读了Microsoft提供的本教程,将Azure Ad集成到我的web应用程序中进行身份验证。

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

但是,我只能访问用户的基本信息,如GivenName和姓氏。我在Azure门户中创建了名为“extension\u e3f9d0…”的扩展属性

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

?$select=扩展名\u 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
            }
        }
    );
}

要使用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.Read和Mail.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=姓氏

有关更多详细信息,请参阅此

此外,您还可以调用以指定资源URI,其授权代码为


我已经编辑了我的问题,以包含我用于登录用户的代码。既然用户已成功签名,那么不应该为该用户生成访问令牌吗?我只是不知道如何提取访问令牌,以便在对图形的get请求中使用。
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/"
);