Java Authenticator 基于每个连接?
我正在构建一个 Eclipse 插件,它与使用基本身份验证的 REST 接口进行通信。 当身份验证失败时,我想弹出插件的设置对话框并重试。 通常我可以使用静态 Authenticator.setDefault() 为所有 HttpURLConnection 设置验证器,但由于我正在编写一个插件,所以我不想覆盖 Eclipse 的默认 Authenticator (org.eclipse.ui.internal.net.auth
);
我想在加载之前设置我的自定义 Authenticator,然后将 Eclipse 的默认设置恢复,但我想这会导致多线程的各种竞争问题,所以我很快就失去了这个想法。
谷歌搜索产生的各种结果基本上告诉我这是不可能的:
Java URLConnection API 应该有一个 setAuthenticator(Authenticator) 方法,以便在需要身份验证的多线程上下文中更轻松地使用此类。
如果应用程序包含很少的第三方插件,并且每个插件都使用自己的身份验证器,我们应该做什么? 每次调用“Authenticator.setDefault()”方法都会重写之前定义的Authenticator...
有什么不同的方法可以帮助我克服这个问题吗?
I'm building an Eclipse plugin that talks to a REST interface which uses Basic Authentication. When the authentication fails I would like to popup my plugin's settings dialog and retry. Normally I could use the static Authenticator.setDefault()
to setup an authenticator for all HttpURLConnection
's for this, but since I am writing a plugin I don't want to overwrite Eclipse's default Authenticator
(org.eclipse.ui.internal.net.auth
);
I thought of setting my custom Authenticator
before loading and putting Eclipse's default back afterwards, but I imagine this will cause all sorts of race issues with multithreading so I quickly lost that notion.
Google searches yield all sorts of results basically telling me it's not possible:
The Java URLConnection API should have a setAuthenticator(Authenticator) method for making it easier to use this class in multi-threaded context where authentication is required.
If applications contains few third party plugins and each plugin use its own Authenticator what we should do? Each invocation of "Authenticator.setDefault()" method rewrite previously defined Authenticator...
Are there any different approaches that might help me overcome this issue?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
如果 HttpURLConnection 无法实现,我建议使用 Apache 的 httpclient 库。
一个简单的例子:
If it is not possible with HttpURLConnection I would suggest using the httpclient library from Apache.
A quick example:
另一种方法是自己在连接上执行基本身份验证。
这还有一个优点,即在为后续请求提供凭据之前不需要未经身份验证的请求来接收 401。 通过请求抢占式身份验证,可以在 apache http 客户端中利用类似的行为。
Another approach would be to perform the basic authentication yourself on the connection.
This would also have the advantage of not requiring an unauthenticated request to receive a 401 before providing the credential on a subsequent request. Similar behavior can be leveraged in the apache http-client by requesting preemptive authentication.