java - 如何使用 PKI 证书代替客户端 key ?

标签 java azure-active-directory microsoft-graph-api

我想知道是否有人可以建议我如何在当前设置中使用 PKI 证书而不是客户端 secret 字符串来访问 Java 中的图形。该证书将提供给我,并且 Azure 应用程序中的所有设置都将为我完成,我只需要知道如何在我的 java 设置中使用该证书。

我的 GraphAuthManager。我用这些信息构建了一个 OAuth20Service。

package com.mycompany.graph.connect;

import java.io.IOException;
import java.net.URISyntaxException;
import java.util.Scanner;
import java.util.concurrent.ExecutionException;
import java.util.logging.Level;

import com.github.scribejava.core.builder.ServiceBuilder;
import com.github.scribejava.core.model.OAuth2AccessToken;
import com.github.scribejava.core.model.OAuth2AccessTokenErrorResponse;
import com.github.scribejava.core.oauth.OAuth20Service;
import com.microsoft.graph.core.ClientException;
import com.microsoft.graph.logger.LoggerLevel;

//this modifying the example authentication manager to my purposes
public class GraphAuthManager {

    //extrnalised info like scopes,client secret,etc
    private OAuth2AccessToken mAccessToken;
    // this is set if we already have a refresh token

    /**
        * Initialization block. Runs before constructor to get a logger and start up
        * the ScribeJava OAuth2 authentication service
        */
    {
        if (Debug.DebugLevel == LoggerLevel.DEBUG) {
            DebugLogger.getInstance().writeLog(Level.INFO, "AuthenticationManager initialization block called");

            try (OAuth20Service service = new ServiceBuilder(Constants.CLIENT_ID).callback(Constants.REDIRECT_URL)
                    .scope(Constants.SCOPES).apiKey(Constants.CLIENT_ID).apiSecret(API_SECRET).debugStream(System.out)
                    .debug().build(MicrosoftAzureAD20Api.instance())) {
                mOAuthService = service;
            } catch (java.io.IOException | IllegalArgumentException ex) {
                try {
                    throw ex;
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        } else {
            try (OAuth20Service service = new ServiceBuilder(Constants.CLIENT_ID).callback(Constants.REDIRECT_URL)
                    .scope(Constants.SCOPES).apiKey(Constants.CLIENT_ID).apiKey(Constants.CLIENT_ID)
                    .apiSecret(API_SECRET).build(MicrosoftAzureAD20Api.instance())) {
                mOAuthService = service;
            } catch (java.io.IOException | IllegalArgumentException ex) {
                try {
                    throw ex;
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }

    private GraphAuthManager() throws IOException {
        DebugLogger.getInstance().writeLog(Level.INFO, "AuthenticationManager constructor called");
    }

    public static synchronized GraphAuthManager getInstance() throws java.io.IOException, java.net.ConnectException {
        return new GraphAuthManager();
    }

    public OAuth2AccessToken getRefreshTokenWithAuthToken(String authToken)
            throws OAuth2AccessTokenErrorResponse, IOException, InterruptedException, ExecutionException {


        try {
            System.out.println("trying for the first time");
            mAccessToken = mOAuthService.getAccessToken(authToken);
            return mAccessToken;
        }
        catch (IOException | InterruptedException | ExecutionException e) {
            // if a catch other than a response code error occurs, try it agaiin
            System.out.println("trying a second time");
            try {
                mAccessToken = mOAuthService.getAccessToken(authToken);
                return mAccessToken;
            } catch (IOException | InterruptedException | ExecutionException e2) {

                // TODO Auto-generated catch block
                // an error occured
                e2.printStackTrace();
                throw e2; // this is for bubbling up the exception to the class using graphauth to do
                            // validations
            }
        }

    }

    public OAuth2AccessToken getAccessTokenWithRefreshToken(String refreshToken)
            throws OAuth2AccessTokenErrorResponse, IOException, InterruptedException, ExecutionException {
        try {
            System.out.println("trying for the first time");
            OAuth2AccessToken mAccessToken = mOAuthService.refreshAccessToken(refreshToken);
            return mAccessToken;
        } catch (IOException | InterruptedException | ExecutionException e) {
            try {
                System.out.println("trying for the second time");
                OAuth2AccessToken mAccessToken = mOAuthService.refreshAccessToken(refreshToken);
                return mAccessToken;
            } catch (IOException | InterruptedException | ExecutionException e2) {
                // TODO Auto-generated catch block
                e2.printStackTrace();
                throw e2;
            }
        }


    }

    public OAuth20Service getOAuthService() {
        return mOAuthService;
    }

    public String getRefreshToken() {
        if (mAccessToken == null) {
            return "";
        }
        return mAccessToken.getRefreshToken();
    }

    public String getAccessToken() {
        if (mAccessToken == null) {
            return "";
        }
        return mAccessToken.getAccessToken();
    }
}

最佳答案

我快速浏览了一下 scribejava。好像现在只能支持使用client Secret。

要使用 PKI 证书而不是客户端 key ,您需要:

  1. 创建并上传自签名证书
$cert=New-SelfSignedCertificate -Subject "CN=AADCert" -CertStoreLocation "Cert:\CurrentUser\My"  -KeyExportPolicy Exportable -KeySpec Signature
$bin = $cert.RawData
$base64Value = [System.Convert]::ToBase64String($bin)
$bin = $cert.GetCertHash()
$base64Thumbprint = [System.Convert]::ToBase64String($bin)
$cert | Export-Certificate -FilePath D:\test.cer
$CertPassword = ConvertTo-SecureString -String “YourPassword” -Force –AsPlainText
$cert | Export-PfxCertificate -FilePath D:\test.pfx -Password $CertPassword

cer 文件将导出到 D:\test.cer。您可以将其上传到在 Azure AD 中注册的应用程序。

pfx 文件也会被导出。它是您证书的备份。它将用于获取 token 。

  • 添加Azure MSAL ,并获取 token
  • import com.microsoft.aad.msal4j.*;
    import java.io.IOException;
    import java.net.MalformedURLException;
    import java.net.URI;
    import java.util.HashSet;
    import java.util.Set;
    import java.util.concurrent.ExecutionException;
    import java.util.concurrent.ExecutorService;
    import java.util.concurrent.Executors;
    
    
    public class MsalTest {
        public static void main(String[] args) throws Exception {
    
            Set<String> scopes = new HashSet<>();
            scopes.add("openid");
            scopes.add("User.Read");
    
            String code = "The authorization code, AQABAAI......UQ_CIAA";
    
            IClientCredential clientCredential = ClientCredentialFactory.create(ClassLoader.getSystemResourceAsStream("./others/test.pfx"), "YourPassword");
    
            String clientId = "Your client id, dc17****-****-****-****-****e56da5e7";
    
            String authority = "https://login.microsoftonline.com/+tenantid, for example: https://login.microsoftonline.com/e4c9ab4e-bd27-40d5-8459-230ba2a757fb";
    
            URI redirectUri = new URI("redirect uri of your applicaiton in azure ad, https://localhost/");
    
            IAuthenticationResult result = GetTokenWithCertficate(scopes, code, clientCredential, clientId, authority, redirectUri);
    
            System.out.println(result.accessToken());
        }
    
        static IAuthenticationResult GetTokenWithCertficate(Set<String> scopes, String code, IClientCredential clientCredential, String clientId, String authority, URI redirectUri){
            IAuthenticationResult result = null;
            ExecutorService service = null;
            try{
                service = Executors.newFixedThreadPool(1);
                ConfidentialClientApplication app = ConfidentialClientApplication.builder(clientId, clientCredential).authority(authority).executorService(service).build();
                AuthorizationCodeParameters authorizationCodeParameters = AuthorizationCodeParameters.builder(code, redirectUri).scopes(scopes).build();
                result = app.acquireToken(authorizationCodeParameters).get();
            } catch (ExecutionException e) {
                e.printStackTrace();
            } catch (MalformedURLException e) {
                e.printStackTrace();
            } catch (InterruptedException e) {
                e.printStackTrace();
            } catch (IOException e) {
                e.printStackTrace();
            } finally {
                service.shutdown();
            }
    
            return result;
        }
    }
    

    关于java - 如何使用 PKI 证书代替客户端 key ?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57507312/

    相关文章:

    node.js - Microsoft Graph Webhook/订阅,将多个帖子发送到我的 notificationUrl

    azure - 使用 Microsoft Graph API 时重定向 URL 地址不正确

    java - Wildfly 服务器在 Wildfly :start 后关闭

    java - Struts 2 中的注释支持

    java - 每次添加东西时尝试取平均值

    java - 理解 HashMap 键- java

    azure-active-directory - Azure Active Directory v2.0守护程序和服务器端应用程序支持

    Azure AD B2C 自定义登录策略显示 SignUpSignIn

    Azure AD - 以编程方式创建新的服务主体

    java - 将 DirectoryObject 转换为用户