从Java到Azure API应用进行身份验证 [英] Authenticate to an Azure API App from Java

查看:211
本文介绍了从Java到Azure API应用进行身份验证的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我对此博文有类似的问题:使用以下工具验证Azure API应用ADAL ,但就我而言,我有一个客户,该客户的Java客户端托管在JBoss中,需要访问我的API.该服务的安全性为公开(已验证)",从浏览器访问它没有任何问题.我知道可以在.net中创建一个Azure API应用程序客户端,但是找不到有关如何从Java进行身份验证的示例.目前是否可行?如果有,是否有人可以提供帮助的示例或建议?

I have a similar issue to this post:Authenticate to Azure API App using ADAL but in my case I have a customer with a Java client hosted in JBoss who needs access to my API. The service is secured as 'Public (authenticated)' and I don't have any issues accessing it from a browser. I know that I can create an Azure API App Client in .net but I can't find any samples on how to authenticate from Java. Is this currently possible and if so does anyone have any samples or advice that would help?

推荐答案

我阅读了以下一些文档,以Java语言制作了一个示例,用于从AAD身份验证的客户端调用Azure API应用.

I reviewed some documents below to make a sample in Java for calling an Azure API app from client authenticated by AAD.

作为参考:

  1. https://azure .microsoft.com/en-us/documentation/articles/app-service-api-authentication-client-flow/
  2. https://azure .microsoft.com/en-us/documentation/articles/app-service-api-dotnet-add-authentication/
  3. https://azure.microsoft.com/en-us/documentation/articles/app-service-authentication-overview/
  1. https://azure.microsoft.com/en-us/documentation/articles/app-service-api-authentication-client-flow/
  2. https://azure.microsoft.com/en-us/documentation/articles/app-service-api-dotnet-add-authentication/
  3. https://azure.microsoft.com/en-us/documentation/articles/app-service-authentication-overview/

对于示例,我在Eclipse中创建了一个maven项目,并使用了库adal4jcommon-io& httpclient.这是下面pom.xml文件中的依赖项配置.

For the sample, I created a maven project in Eclipse and used libs adal4j, common-io & httpclient. Here is the dependencies configuration below in pom.xml file.

<dependencies>
    <dependency>
        <groupId>com.microsoft.azure</groupId>
        <artifactId>adal4j</artifactId>
        <version>1.1.2</version>
    </dependency>
    <dependency>
        <groupId>commons-io</groupId>
        <artifactId>commons-io</artifactId>
        <version>2.4</version>
    </dependency>
    <dependency>
        <groupId>org.apache.httpcomponents</groupId>
        <artifactId>httpclient</artifactId>
        <version>4.5.1</version>
    </dependency>
</dependencies>

已将示例代码保护为Public (authenticated),请注意代码中的注释.

The sample code for service secured as Public (authenticated), please pay attention to comments in code.

    String gateway_url = "https://<GatewayHost>.azurewebsites.net/";
    String app_id_uri = gateway_url + "login/aad";
    String authority = "https://login.microsoftonline.com/<aad-domain>.onmicrosoft.com";
    String clientId = "<clientId>";
    String clientSecret = "<key>";
    String url = "https://<ApiAppHost>.azurewebsites.net/...";
/*
 *  Get Access Token from Gateway Login URL with authentication provider name
 *  Note: Please refer to the aad sample in Java for Native Headless at https://github.com/Azure-Samples/active-directory-java-native-headless
 */
HttpsURLConnection conn = (HttpsURLConnection) new URL(app_id_uri).openConnection();
AuthenticationContext context = null;
    AuthenticationResult result = null;
    ExecutorService service = null;
    try {
        service = Executors.newFixedThreadPool(1);
        context = new AuthenticationContext(authority, false, service);
        ClientCredential credential = new ClientCredential(clientId, clientSecret);
        Future<AuthenticationResult> future = context.acquireToken(app_id_uri, credential, null);
        result = future.get();
    } finally {
        service.shutdown();
    }
    String accessToken = null;
    if (result == null) {
        throw new ServiceUnavailableException(
                "authentication result was null");
    } else {
        accessToken = result.getAccessToken();
        System.out.println("Access Token: " +accessToken);
    }
    /*
     * Using access token to get authentication token
     */
    String data = "{\"access_token\": \""+accessToken+"\"}";
    conn.setRequestMethod("POST");
    conn.setDoOutput(true);
    conn.addRequestProperty("Content-Length", data.length()+"");
    new DataOutputStream(conn.getOutputStream()).writeBytes(data);
    String authTokenResp = IOUtils.toString(conn.getInputStream());
    System.out.println("Get Authentication Token Response: " + authTokenResp);
    /*
     * The content of Authentication Token Response is as {"user": {"userId": "sid:xxx...xxx"}, "authenticationToken": "xxxx...xxxxx"}.
     * Need to extract the authenticationToken from Json.
     */
    Gson gson = new Gson();
    Map<String, Object> map = gson.fromJson(authTokenResp, Map.class);
    String authenticationToken = (String) map.get("authenticationToken");
    System.out.println("Authentication Token: "+authenticationToken);
    /*
     * Using authentication token as X-ZUMO-AUTH header to get data from Api App
     * Note: Must using Apache Common HttpClient supported HTTP 30x redirection, Class Http(s)URLConnection not support.
     *          There are three times continuous 302 redirection in accessing Api App with zumo token. 
     */
    HttpGet httpGet = new HttpGet(url);
    httpGet.addHeader("x-zumo-auth", authenticationToken);
    CloseableHttpClient httpclient = HttpClients.createDefault();
    HttpResponse resp = httpclient.execute(httpGet);
    String apiAppData = IOUtils.toString(resp.getEntity().getContent());
    System.out.println(apiAppData);

任何担心,请随时让我知道.

Any concern, please feel free to let me know.

这篇关于从Java到Azure API应用进行身份验证的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆