从CQ5中的存储库访问页面时的授权问题。

时间:2015-06-02 05:25:38

标签: httpurlconnection cq5 aem sling

我试图点击包含xml结构的页面。为此我使用此代码

            @Reference
            private SlingRepository repository;

            adminSession = repository.loginAdministrative( repository.getDefaultWorkspace());
            String pageUrl = "http://localhost:4504"+page+".abc.htm";
            conn = (HttpURLConnection)new URL(pageUrl).openConnection();
            conn.setRequestProperty("Accept-Charset", charset);
            conn.setRequestProperty("User-Agent", "Mozilla/5.0 (Windows; U; Windows NT 5.1; en-US; rv:1.9.2.3) Gecko/20100401"); // Do as if you'rusing Firefox 3.6.3
            urlResponse = new BufferedInputStream(conn.getInputStream());
            BufferedReader reader = new BufferedReader( new InputStreamReader(urlResponse) );

访问页面时遇到此问题

org.apache.sling.auth.core.impl.SlingAuthenticator getAnonymousResolver: `Anonymous access not allowed by configuration - requesting credentials`

我以管理员身份登录,每当我直接点击此urlfrom浏览器时,它正常工作,而在我的代码中访问它时我收到此错误。

任何建议?

2 个答案:

答案 0 :(得分:0)

如果您尝试在作者实例上调用url,我在其中一个项目中使用的以下方法可能有所帮助(使用apache commons HttpClient):

private InputStream getContent(final String url)
    HttpClient httpClient = new HttpClient();
    httpClient.getParams().setAuthenticationPreemptive(true);
    httpClient.getState().setCredentials(new AuthScope(null, -1, null),
        new UsernamePasswordCredentials("admin", "admin"));
    try {
        GetMethod get = new GetMethod(url);
        httpClient.executeMethod(get);
        if (get.getStatusCode() == HttpStatus.SC_OK) {
            return get.getResponseBodyAsStream();
        } else {
            LOGGER.error("HTTP Error: ", get.getStatusCode());
        }
    } catch (HttpException e) {
        LOGGER.error("HttpException: ", e);
    } catch (IOException e) {
        LOGGER.error("IOException: ", e);
    }
}

虽然它正在使用admin:admin它只适用于本地开发实例,如果你处于高效环境,我不会把管理密码放在纯文本中,即使它是onyl代码......

答案 1 :(得分:0)

你正在混合吊索凭证和放大器http凭据。当您登录sling-repository时,http会话不知道任何身份验证信息!