1

I'm using the sample provided by Microsoft, I authenticate myself just fine. I retrieve basic info about my user after authenticating. How do I retrieve more info about my user (e.g. street number, house number, phone number etc.)?

  1. I'm using this Azure AD Spring Boot Backend Sample - Github
  2. I start & login (https://localhost:8080)
  3. Authentication success!
  4. I get basic info about the user (e.g. Name, Surname)
  5. How do I get more info about the user (e.g. Street Number, House Number, Phone Number)?

Code (HomeController.java):

@GetMapping("/")
public String index(Model model, OAuth2AuthenticationToken auth) {
    final OAuth2AuthorizedClient client = this.authorizedClientService.loadAuthorizedClient(
            auth.getAuthorizedClientRegistrationId(),
            auth.getName());

    // Name, Surname
    model.addAttribute("userName", auth.getName());
    model.addAttribute("pageTitle", "Welcome, "+auth.getName());
    // Azure info
    model.addAttribute("clientName", client.getClientRegistration().getClientName());

    // HERE I WANT TO SEND A (MICROSOFT OR AD) GRAPH API REQUEST TO GET 
    // THIS USER'S ADDRESS (street number, house number, etc.)

    return "index";
}
aivarastee
  • 81
  • 2
  • 12

1 Answers1

2

First thing is that we need to get the access token from auth.

We could get access token with following code.

DefaultOidcUser user = (DefaultOidcUser)auth.getPrincipal();
String accessToken = user.getIdToken().getTokenValue(); 

How to send the request API with Java code, please have a try it with following code.

Azure AD graph REST API for get a user

https://graph.windows.net/myorganization/users/{user_id}?api-version=1.6

Microsoft graph Rest API for get a user

https://graph.microsoft.com/v1.0/users/{id | userPrincipalName}?$select=displayName,givenName,postalCode,...

Note: If you need a different property set, you can use the OData $select query parameter. For example, to return displayName, givenName, and postalCode, you would use the add the following to your query $select=displayName,givenName,postalCode

Follow is the demo code:

import com.google.gson.JsonObject;
import com.google.gson.JsonParser;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.util.EntityUtils;

 String url = "https://graph.windows.net/{yourtenantId}/users/{userObjectId}?api-version=1.6"; //take Azure AD graph for example.
 HttpClient client = HttpClientBuilder.create().build();
 HttpGet request = new HttpGet(url);
 request.addHeader("Authorization","Bearer "+ accessToken);
 HttpResponse response = client.execute(request);
 HttpEntity entity = response.getEntity();
 // Read the contents of an entity and return it as a String.
 String content = EntityUtils.toString(entity);
 JsonObject jsonObject = (JsonObject) new JsonParser().parse(content);
Tom Sun - MSFT
  • 24,161
  • 3
  • 30
  • 47