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



我正在使用Microsoft提供的示例,我可以很好地验证自己。我在身份验证后检索有关用户的基本信息。如何检索有关用户的更多信息(例如门牌号、门牌号、电话号码等(?

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

代码(家庭控制器.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";
}

第一件事是我们需要从身份验证获取访问令牌。

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

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图用于获取用户的 Rest API

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

最新更新