首页 > 解决方案 > 使用适用于 java 的谷歌 OAuth2 客户端库访问 AzureAD API

问题描述

我的项目需要与 G-Suite 和 AzureAD 目录集成。它们都支持 OAuth2,如此此处所述。

我想使用 Google OAuth2 客户端访问 G-Suite 和 AzueAD API。我有几个相同的问题

  1. 是否可以使用 google-oauth-api-client 访问 AzureAD API?

  2. 有没有可以与 G-Suite SDK 和 AzureAD 一起使用的库?

我不想为我集成的每个提供者分离库。无论是 G-Suite、AzureAD 还是 SalesForce 或其他支持 OAuth2 的东西。

标签: google-oauth-java-client

解决方案


通过添加以下两个类,Google OAuth2 客户端库可用于针对任何 OAuth2 提供者进行身份验证:

public class ClientUsernamePasswordTokenRequest extends TokenRequest {

/**
 * @param transport      HTTP transport
 * @param jsonFactory    JSON factory
 * @param tokenServerUrl token server URL
 * @param grantType      grant type ({@code "authorization_code"}, {@code "password"},
 *                       {@code "client_credentials"}, {@code "refresh_token"} or absolute URI of the extension
 */
public ClientUsernamePasswordTokenRequest(HttpTransport transport, JsonFactory jsonFactory, GenericUrl tokenServerUrl, String grantType) {
    super(transport, jsonFactory, tokenServerUrl, grantType);
}

@Override
public TokenResponse execute() throws IOException {
    return convertStringToObject(executeUnparsed().parseAs(Map.class));
}

private TokenResponse convertStringToObject(Map content) {
    TokenResponse tokenResponse = new TokenResponse();
    String tokenType = (String) content.get("token_type");
    tokenResponse.setTokenType(tokenType);
    String scope = (String) content.get("scope");
    tokenResponse.setScope(scope);
    String accessToken = (String) content.get("access_token");

    tokenResponse.setAccessToken(accessToken);
    String refreshToken = (String) content.get("refresh_token");
    tokenResponse.setRefreshToken(refreshToken);
    return tokenResponse;
}


}

package com.identityforge.idfserver.backend.rest.auth;

import com.google.api.client.http.HttpExecuteInterceptor;
import com.google.api.client.http.HttpRequest;
import com.google.api.client.http.HttpRequestInitializer;
import com.google.api.client.http.UrlEncodedContent;
import com.google.api.client.util.Data;
import com.google.api.client.util.Preconditions;

import java.util.Map;

public class ClientParametersAuthentication implements HttpRequestInitializer, HttpExecuteInterceptor {

    /**
     * Client identifier issued to the client during the registration process.
     */
    private final String clientId;

    /**
     * Client password or {@code null} for none.
     */
    private final String password;
    /**
     * Client username
     */
    private final String username;

    /**
     * Resource for which access is requested
     */

    private final String resource;

    private final String clientSecret;

    /**
     * @param clientId     client identifier issued to the client during the registration process
     * @param password     password or {@code null} for none
     * @param username
     * @param resource
     * @param clientSecret
     */
    public ClientParametersAuthentication(String clientId, String password, String username, String resource, String clientSecret) {
        this.clientId = Preconditions.checkNotNull(clientId);
        this.password = Preconditions.checkNotNull(password);
        this.username = Preconditions.checkNotNull(username);
        this.resource = resource;
        this.clientSecret = clientSecret;
    }

    public void initialize(HttpRequest request) {
        request.setInterceptor(this);
    }

    public void intercept(HttpRequest request) {
        Map<String, Object> data = Data.mapOf(UrlEncodedContent.getContent(request).getData());
        data.put("client_id", clientId);
        data.put("password", password);
        data.put("username", username);
        if (resource != null)
            data.put("resource", resource);

        if (clientSecret != null) {
            data.put("client_secret", clientSecret);
        }
    }


}

现在可以通过在以下代码中提供凭据值来请求访问令牌

 private void fetchToken() throws IOException {
    TokenResponse tokenResponse;

    if (genericUrl == null) {
        genericUrl = new GenericUrl(tokenUrl);
    }
    if (authentication == null) {
        authentication = new ClientParametersAuthentication(clientId, passwd, username, resource, clientSecret);
    }
    if (tokenRequest == null) {
        tokenRequest = new ClientUsernamePasswordTokenRequest(new ApacheHttpTransport(), JacksonFactory.getDefaultInstance(), genericUrl, grantType);
        tokenRequest.setClientAuthentication(authentication);
    }
       tokenResponse = tokenRequest.execute();
        String accessToken = tokenResponse.getAccessToken();
        }

tokenUrl是身份验证端点。


推荐阅读