java - 从 azure 登录获取 token

标签 java spring azure azure-active-directory

我正在使用 Azure AD 登录 Spring Boot 应用程序。虽然我可以登录,但我需要查看带有不记名 token 的用户信息。当用户从 azure 登录( https://login.microsoftonline.com/ {{adId}}/oauth2/token) 重定向回应用程序时,如何获取此 token ?

@EnableWebSecurity
@EnableGlobalMethodSecurity(prePostEnabled = true)
public class WebSecurityConfig extends WebSecurityConfigurerAdapter {
    @Autowired
    private OAuth2UserService<OidcUserRequest, OidcUser> oidcUserService;


    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http
                .authorizeRequests()
                .anyRequest().authenticated()
                .and()
                .oauth2Login()
                .userInfoEndpoint()
                .oidcUserService(oidcUserService);
    }


}

最佳答案

正如 Amogh 所说,从访问 token 获取用户信息的逻辑在不同语言中是相同的。有一个记录良好的 Azure 示例,它可以实现您想要在 Java 中实现的目标。请访问并克隆this sample获取不记名 token 。

看看AAD Controller具体部分:

    URL url = new URL("https://graph.microsoft.com/v1.0/users");
    HttpURLConnection conn = (HttpURLConnection) url.openConnection();

    conn.setRequestMethod("GET");
    conn.setRequestProperty("Authorization", "Bearer " + accessToken);
    conn.setRequestProperty("Accept","application/json");
    int httpResponseCode = conn.getResponseCode();

    String goodRespStr = HttpClientHelper.getResponseStringFromConn(conn, true);
    // logger.info("goodRespStr ->" + goodRespStr);
    int responseCode = conn.getResponseCode();
    JSONObject response = HttpClientHelper.processGoodRespStr(responseCode, goodRespStr);
    JSONArray users;

    users = JSONHelper.fetchDirectoryObjectJSONArray(response);

    StringBuilder builder = new StringBuilder();
    User user;
    for (int i = 0; i < users.length(); i++) {
        JSONObject thisUserJSONObject = users.optJSONObject(i);
        user = new User();
        JSONHelper.convertJSONObjectToDirectoryObject(thisUserJSONObject, user);
        builder.append(user.getUserPrincipalName() + "<br/>");
    }
    return builder.toString();
}

关于java - 从 azure 登录获取 token ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52550212/

相关文章:

java - 同一 URL 的 POST 和 GET - Controller - Spring

java - 在 Tomcat 中打开新线程

azure - 如何检索生成的 Azure Key Vault 证书的 PFX 密码?

java - Netbeans 8.0.1 的 MySQL 安装程序

java - 在集合中查找重复条目

java - Fork 和 Join 特性 jdk7 线程数

java - 如 Effective Java 一书中所述,理解 Java 中非静态成员类的创建

mysql - HTTP 状态 404 - 请求的资源不可用,未显示我的网页

azure - 角色内、共置缓存和 CacheService.exe

azure - 连接-MsolService : Authentication Error: Unexpected authentication failure