我需要为 Spring OAuth2 的实现构建一个自定义 request_uri。 应该使用什么特定代码来正确编码 request_uri 中的每个参数?
完整的未编码request_uri
如下,但会导致错误,指示未授予令牌:
http://localhost:9999/uaa/oauth/authorize?client_id=acme
&redirect_uri=http://localhost:8080/login&response_type=code
&state=13ab71ae-c8ed-4370-a60f-dd7fe47ed763
如您所见,各个参数是:
client_id=acme
redirect_uri=http://localhost:8080/login
response_type=code
state=13ab71ae-c8ed-4370-a60f-dd7fe47ed763
用于构造上述 request_uri 的代码是:
CsrfToken csrf = (CsrfToken) attr.getRequest().getAttribute(CsrfToken.class.getName());
String attrToken = csrf.getToken();
authorizationRequest.setState(attrToken);
String newRequestUri = "http://localhost:9999/uaa/oauth/authorize?";
String clientId = authorizationRequest.getClientId();
newRequestUri = newRequestUri + "client_id=" + clientId;
String redirectUri = authorizationRequest.getRedirectUri();
newRequestUri = newRequestUri + "&redirect_uri="+redirectUri;
Set<String> respTypes = authorizationRequest.getResponseTypes();
String respType = respTypes.iterator().next();//this plucks the first one, but is not safe for when there is a list.
newRequestUri = newRequestUri +"&response_type="+respType;
String state = authorizationRequest.getState();
newRequestUri = newRequestUri + "&state="+state;
attr.setAttribute("javax.servlet.forward.request_uri", newRequestUri, RequestAttributes.SCOPE_REQUEST);
//now re-set the request attributes to reflect the changes we just made
RequestContextHolder.setRequestAttributes(attr);
更具体地说,这个 OP 询问应该使用什么语法来编码上面代码中的以下字符串值:newRequestUri
、clientId
、redirectUri
、respType
和state
.
官方 OAuth2 规范说你可以使用Content application/x-www-form-urlencoded
-Type 和UTF-8
编码,但也给出了这个例子:
/authorize?response_type=code&client_id=s6BhdRkqt3
&state=xyz
&redirect_uri=https%3A%2F%2Fclient%2Eexample%2Ecom%2Fcb
类似地,Spring OAuth2 开发者指南只包含一个词的用法encode
。