Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

URL encoding using the new Spring UriComponentsBuilder

Tags:

spring

I'm attempting to use spring's UriComponentsBuilder to generate some urls for oauth interaction. The query parameters include such entities as callback urls and parameter values with spaces in them.

Attempting to use UriComponentBuilder (because UriUtils is now deprecated)

UriComponentsBuilder urlBuilder = UriComponentsBuilder.fromHttpUrl(oauthURL); urlBuilder.queryParam("client_id", clientId); urlBuilder.queryParam("redirect_uri", redirectURI); urlBuilder.queryParam("scope", "test1 test2");  String url = urlBuilder.build(false).encode().toUriString(); 

Unfortunately, while the space in the scope parameter is successfully replaced with '+', the redirect_uri parameter is not at all url encoded.

E.g,

redirect_uri=https://oauth2-login-demo.appspot.com/code 

should have ended up

redirect_uri=https%3A%2F%2Foauth2-login-demo.appspot.com%2Fcode 

but was untouched. Diving into the code, specifically org.springframework.web.util.HierarchicalUriComponents.Type.QUERY_PARAM.isAllowed(c) :

if ('=' == c || '+' == c || '&' == c) {   return false; } else {   return isPchar(c) || '/' == c || '?' == c; } 

clearly allows ':' and '/' characters, which by gum, it shouldn't. It must be doing some other type of encoding, though for the life of me, I can't imagine what. Am I barking up the wrong tree(s) here?

Thanks

like image 926
ticktock Avatar asked Aug 08 '13 23:08

ticktock


People also ask

What is UriComponentsBuilder?

public class UriComponentsBuilder extends Object implements UriBuilder, Cloneable. Builder for UriComponents . Typical usage involves: Create a UriComponentsBuilder with one of the static factory methods (such as fromPath(String) or fromUri(URI) )

Why we use UriComponentsBuilder?

The main advantages of UriComponentsBuilder are the flexibility of using URI template variables, and a possibility of injecting it directly into Spring Controller methods. All examples and configurations are available here on GitHub.

How do you make a spring URI?

Method SummaryBuild a URI instance and replaces URI template variables with the values from an array. Set the URI fragment. Set the URI host which may contain URI template variables, and may also be null to clear the host of this builder. Append to the path of this builder.


1 Answers

UriComponentsBuilder is encoding your URI in accordance with RFC 3986, with section 3.4 about the 'query' component of a URI being of particular note.

Within the 'query' component, the characters '/' and ':' are permitted, and do not need escaping.

To take the '/' character for example: the 'query' component (which is clearly delimited by unescaped '?' and (optionally) '#' characters), is not hierarchical and the '/' character has no special meaning. So it doesn't need encoding.

like image 98
simonh Avatar answered Sep 23 '22 12:09

simonh