简体   繁体   中英

How to get custom properties from Azure AD

I went through this tutorial provided by Microsoft to integrate Azure Ad for authentication in my web app. https://docs.microsoft.com/en-us/azure/active-directory/develop/quickstart-v1-dotnet-webapi

The code works as expected. I run the program and it prompts the user for their Microsoft login credentials and if valid they are redirected to the homepage.

However, I only have access to basic information about the user such as GivenName and SurName. I created extended properties in the Azure Portal named like 'extension_e3f9d0...'

The problem is I have no idea how to access the attributes once the user is signed in. I'm able to retrieve these custom attributes when I call the API in Postman like so:

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

I try to make this call in c# but I don't know how to get the accessToken once the user is logged in, which is required in the request header

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);
                }
            }
        }
    }

Code to sign in user

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

To use Microsoft Graph to read and write resources on behalf of a user, your app must get an access token from Azure AD and attach the token to requests that it sends to Microsoft Graph.

The basic steps required to use the OAuth 2.0 authorization code grant flow to get an access token from the Azure AD v2.0 endpoint are:

1.Register your app with Azure AD.

2.Get authorization.

With the Azure AD v2.0 endpoint, permissions are requested using the scope parameter. In this example, the Microsoft Graph permissions requested are for User.Read and Mail.Read , which will allow the app to read the profile and mail of the signed-in user.

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.Get an access token.

Your app uses the authorization code received in the previous step to request an access token by sending a POST request to the /token endpoint.

4.Call Microsoft Graph with the access token.

For the signed-in user, I use https://graph.microsoft.com/v1.0/me?$select=surname

在此处输入图片说明

For more details, you could refer to this article .

Also, you could make a call to specify a resource URI with the authorization code as 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/"
);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM