gpt4 book ai didi

java - 在 JavaEE 中对 URLConnection 使用当前用户身份验证

转载 作者:行者123 更新时间:2023-11-28 22:52:10 25 4
gpt4 key购买 nike

我的用户使用基本身份验证登录我的网站。有什么方法可以使用经过身份验证的用户详细信息来充当 URLConnection 的身份 validator 吗?....

有点像

@get 
@Path("/rest/getInfo)
public String giveMeTheResult(){

URLConnection conn = new URL("/service/info");
Authenticator.setDefault(getCurrentUserAuthentication());

return (String) conn.getContent();

}

如何执行 getCurrentuserAuthentication 部分?

谢谢。

最佳答案

因为是basic auth,应该不会太差吧。我还没有这样做,但我认为你可以这样做:

public String giveMeTheResult(@Context HttpServletRequest request){

String authHeader = request.getHeader("Authorization");
String[] authChunks = authHeader.split(" ");
String decodedAuth = new String( Base64.getDecoder().decode(authChunks[1]));
String[] userInfo = decodedAuth.split(":");
// user name is userInfo[0], password is userInfo[1]

// not convinced that this is a good idea because it sets it for all
Authenticator.setDefault(new PasswordAuthentication(userInfo[0],
userInfo[1].toCharArray());

return (String) conn.getContent();
}

但警告 - 这完全未经测试,也没有错误检查!

关于java - 在 JavaEE 中对 URLConnection 使用当前用户身份验证,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36764255/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com