gpt4 book ai didi

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

转载 作者:太空宇宙 更新时间:2023-11-04 10:06:11 28 4
gpt4 key购买 nike

我正在使用 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";
}

最佳答案

首先我们需要从 auth 获取访问 token 。

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

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

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

以下是演示代码:

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

关于java - Spring Azure AD - 身份验证后获取用户的地址,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52894154/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com