URLEncoder and JavaScript encodeURIComponent

URLEncoder and JavaScript encodeURIComponent

Recently our system ran into a trouble about authentication. So I dive into the implementation we did in auth. I take part to design that, but I am not 100% know about the implementation.

After investigation, I found the problem.

The issue is coming from the way server side and client side encoding the string, not about the “special” characters.

        I just read the server side source codes, I just know that we are using java.net.URLEncoder from JDK to do the encoding. Doc is here for references: http://docs.oracle.com/javase/1.5.0/docs/api/java/net/URLEncoder.html

        And the client JS side is using encodeURLComponent() which is Similar. Doc is here for references: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/encodeURIComponent

        So here comes the problem, the 2 encoding ways are similar, not exactly the same. The difference characters are ~'()! and "+. We need to do something like this in server side or client side if we want to keep the auth changes as small as possible:


public static String encodeURIComponent(String component) {
String result = null;
 
try {
result = URLEncoder.encode(component, "UTF-8")
.replaceAll("\\%28", "(")
.replaceAll("\\%29", ")")
.replaceAll("\\+", "%20")
.replaceAll("\\%27", "'")
.replaceAll("\\%21", "!")
.replaceAll("\\%7E", "~");
} catch (UnsupportedEncodingException e) {
result = component;
}
 
return result;


By the way, why we need encoding for our string, because we do calculate query string in URL and post body. We just want to make sure it is the same thing after server side receive the query string in URL and post body.


References:
https://gist.github.com/declanqian/7892516
http://stackoverflow.com/questions/607176/java-equivalent-to-javascripts-encodeuricomponent-that-produces-identical-outpu
http://www.technicaladvices.com/2012/02/20/java-encoding-similiar-to-javascript-encodeuricomponent/

JS Doc
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/encodeURIComponent

Java Doc
http://docs.oracle.com/javase/1.5.0/docs/api/java/net/URLEncoder.html

你可能感兴趣的:(URLEncoder and JavaScript encodeURIComponent)