我正在尝试从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之后加一个额外的“ /”,然后通过附加查询参数来继续。
最佳答案
好吧,我想出了一个解决方案:鉴于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