Spring Azure AD-身份验证后获取用户的地址

时间:2018-10-19 14:13:12

标签: java spring azure spring-boot active-directory

我使用的是Microsoft提供的示例,我对自己的身份进行了很好的验证。验证后,我会检索有关用户的基本信息。如何获取有关我的用户的更多信息(例如,街道号,门牌号,电话号码等)?

  1. 我正在使用此Azure AD Spring Boot后端示例-Github
  2. 我启动并登录(https://localhost:8080
  3. 身份验证成功!
  4. 我获得了有关用户的基本信息(例如,姓名,姓氏)
  5. 如何获取有关用户的更多信息(例如,街道号码,门牌号码,电话号码)?

代码(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";
}

1 个答案:

答案 0 :(得分:0)

第一件事是我们需要从auth获取访问令牌。

我们可以使用以下代码获取访问令牌。

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

如何使用Java代码发送请求API,请尝试以下代码。

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,...
  

注意:如果您需要其他属性集,则可以使用OData $ select查询参数。例如,要返回displayName,givenName和postalCode,可以在查询$ select = displayName,givenName,postalCode中添加以下内容

下面是演示代码:

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