我正在尝试根据 OAuth2 授权代码流的请求生成重定向 URI。该请求包含主机名以及范围和授权代码。示例:
redirect_uri=myapp2://oauth2redirect&scope=email+profile
所以,这里的主机名是:myapp2://oauth2redirect
现在,当我执行以下代码为应用程序生成重定向 uri 时,它会在末尾添加一个额外的“/”(斜杠),而不是继续使用查询参数,即:
myapp2://oauth2redirect/?code=abcdefghijkl
myapp2://oauth2redirect/?
中的额外/不需要的“/”导致重定向失败。
理想情况下应该是: myapp2://oauth2redirect?code=abcdefghijkl&scope=
public Response getResponse() {
String uri = oAuthrequest.getRedirectURI();
UriBuilder uriBuilder = UriBuilder.fromUri(uri)
.queryParam("code", code);
if (oAuthrequest.getState() != null) {
uriBuilder.queryParam("state", oAuthrequest.getState());
}
if(scopeNames != null && scopeNames.size() > 0) {
uriBuilder.queryParam("scope", StringUtil.toSingleString(scopeNames, " "));
}
logger.info("OAuth2 Authorization response success");
return Response.status(302).cookie(cookies).location(uriBuilder.build()).build();
}
我认为 UriBuilder.fromUri(uri) 方法在 uri 中添加了额外的“/”,因为我已经调试并检查了字符串字段“uri”的值是否正确。但是,一旦执行此行,它就会在 uri 后面添加额外的“/”,然后继续附加查询参数。
最佳答案
好吧,我想出了一个 hacky 解决方案:鉴于 getRedirectURI()
将返回类似 "myapp2://oauth2redirect"
// builds an URI object from the URI string
java.net.URI uri = java.net.URI.create(getRedirectURI());
// uses the authory(oauth2redirect) as the path to build the uri
UriBuilder uriBuilder = UriBuilder.fromPath(
// forcefully adds the double slashes (//), without this,
// at this point, the uri would be: myapp2:oauth2redirect
"//" + uri.getAuthority())
.scheme(uri.getScheme());
uriBuilder.queryParam("code", "myCode");
uriBuilder.build(); // produces the uri: myapp2://oauth2redirect?code=myCode
关于java - 为什么 javax.ws.rs.core.UriBuilder、fromUri() 方法在主机名 URI 末尾添加额外的 "/"?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44801925/